forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gateway.go
306 lines (264 loc) · 10 KB
/
gateway.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// Copyright 2016, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vtgate
import (
"flag"
"strings"
"sync"
"time"
log "github.com/golang/glog"
"golang.org/x/net/context"
"github.com/youtube/vitess/go/sqltypes"
"github.com/youtube/vitess/go/stats"
"github.com/youtube/vitess/go/vt/discovery"
"github.com/youtube/vitess/go/vt/tabletserver/querytypes"
"github.com/youtube/vitess/go/vt/topo"
querypb "github.com/youtube/vitess/go/vt/proto/query"
topodatapb "github.com/youtube/vitess/go/vt/proto/topodata"
)
var (
// GatewayImplementation controls the implementation of Gateway.
GatewayImplementation = flag.String("gateway_implementation", "shardgateway", "The implementation of gateway")
)
// A Gateway is the query processing module for each shard,
// which is used by ScatterConn.
type Gateway interface {
// InitializeConnections creates connections to VTTablets.
InitializeConnections(ctx context.Context) error
// Execute executes the non-streaming query for the specified keyspace, shard, and tablet type.
Execute(ctx context.Context, keyspace, shard string, tabletType topodatapb.TabletType, query string, bindVars map[string]interface{}, transactionID int64) (*sqltypes.Result, error)
// ExecuteBatch executes a group of queries for the specified keyspace, shard, and tablet type.
ExecuteBatch(ctx context.Context, keyspace, shard string, tabletType topodatapb.TabletType, queries []querytypes.BoundQuery, asTransaction bool, transactionID int64) ([]sqltypes.Result, error)
// StreamExecute executes a streaming query for the specified keyspace, shard, and tablet type.
StreamExecute(ctx context.Context, keyspace, shard string, tabletType topodatapb.TabletType, query string, bindVars map[string]interface{}, transactionID int64) (sqltypes.ResultStream, error)
// Begin starts a transaction for the specified keyspace, shard, and tablet type.
// It returns the transaction ID.
Begin(ctx context.Context, keyspace string, shard string, tabletType topodatapb.TabletType) (int64, error)
// Commit commits the current transaction for the specified keyspace, shard, and tablet type.
Commit(ctx context.Context, keyspace, shard string, tabletType topodatapb.TabletType, transactionID int64) error
// Rollback rolls back the current transaction for the specified keyspace, shard, and tablet type.
Rollback(ctx context.Context, keyspace, shard string, tabletType topodatapb.TabletType, transactionID int64) error
// SplitQuery splits a query into sub-queries for the specified keyspace, shard, and tablet type.
SplitQuery(ctx context.Context, keyspace, shard string, tabletType topodatapb.TabletType, sql string, bindVariables map[string]interface{}, splitColumn string, splitCount int64) ([]querytypes.QuerySplit, error)
// SplitQuery splits a query into sub-queries for the specified keyspace, shard, and tablet type.
// TODO(erez): Rename to SplitQuery after migration to SplitQuery V2.
SplitQueryV2(
ctx context.Context,
keyspace,
shard string,
tabletType topodatapb.TabletType,
sql string,
bindVariables map[string]interface{},
splitColumns []string,
splitCount int64,
numRowsPerQueryPart int64,
algorithm querypb.SplitQueryRequest_Algorithm) ([]querytypes.QuerySplit, error)
// Close shuts down underlying connections.
Close(ctx context.Context) error
// CacheStatus returns a list of GatewayEndPointCacheStatus per endpoint.
CacheStatus() GatewayEndPointCacheStatusList
}
// GatewayCreator is the func which can create the actual gateway object.
type GatewayCreator func(hc discovery.HealthCheck, topoServer topo.Server, serv topo.SrvTopoServer, cell string, retryDelay time.Duration, retryCount int, connTimeoutTotal, connTimeoutPerConn, connLife time.Duration, connTimings *stats.MultiTimings, tabletTypesToWait []topodatapb.TabletType) Gateway
var gatewayCreators = make(map[string]GatewayCreator)
// RegisterGatewayCreator registers a GatewayCreator with given name.
func RegisterGatewayCreator(name string, gc GatewayCreator) {
if _, ok := gatewayCreators[name]; ok {
log.Fatalf("Gateway %s already exists", name)
}
gatewayCreators[name] = gc
}
// GetGatewayCreator returns the GatewayCreator specified by GatewayImplementation flag.
func GetGatewayCreator() GatewayCreator {
gc, ok := gatewayCreators[*GatewayImplementation]
if !ok {
log.Fatalf("No gateway registered as %s", *GatewayImplementation)
}
return gc
}
// GetGatewayCreatorByName returns the GatewayCreator specified by the given name.
func GetGatewayCreatorByName(name string) GatewayCreator {
gc, ok := gatewayCreators[name]
if !ok {
log.Errorf("No gateway registered as %s", name)
return nil
}
return gc
}
// GatewayEndPointCacheStatusList is a slice of GatewayEndPointCacheStatus.
type GatewayEndPointCacheStatusList []*GatewayEndPointCacheStatus
// Len is part of sort.Interface.
func (gepcsl GatewayEndPointCacheStatusList) Len() int {
return len(gepcsl)
}
// Less is part of sort.Interface.
func (gepcsl GatewayEndPointCacheStatusList) Less(i, j int) bool {
iKey := strings.Join([]string{gepcsl[i].Keyspace, gepcsl[i].Shard, string(gepcsl[i].TabletType), gepcsl[i].Name}, ".")
jKey := strings.Join([]string{gepcsl[j].Keyspace, gepcsl[j].Shard, string(gepcsl[j].TabletType), gepcsl[j].Name}, ".")
return iKey < jKey
}
// Swap is part of sort.Interface.
func (gepcsl GatewayEndPointCacheStatusList) Swap(i, j int) {
gepcsl[i], gepcsl[j] = gepcsl[j], gepcsl[i]
}
// GatewayEndPointCacheStatus contains the status per endpoint for a gateway.
type GatewayEndPointCacheStatus struct {
Keyspace string
Shard string
TabletType topodatapb.TabletType
Name string
Addr string
QueryCount uint64
QueryError uint64
QPS uint64
AvgLatency float64 // in milliseconds
}
const (
aggrChanSize = 10000
)
var (
// aggrChan buffers queryInfo objects to be processed.
aggrChan chan *queryInfo
// muAggr protects below vars.
muAggr sync.Mutex
// aggregators holds all Aggregators created.
aggregators []*GatewayEndPointStatusAggregator
// gatewayStatsChanFull tracks the number of times
// aggrChan becomes full.
gatewayStatsChanFull *stats.Int
)
func init() {
// init global goroutines to aggregate stats.
aggrChan = make(chan *queryInfo, aggrChanSize)
gatewayStatsChanFull = stats.NewInt("GatewayStatsChanFullCount")
go resetAggregators()
go processQueryInfo()
}
// registerAggregator registers an aggregator to the global list.
func registerAggregator(a *GatewayEndPointStatusAggregator) {
muAggr.Lock()
defer muAggr.Unlock()
aggregators = append(aggregators, a)
}
// resetAggregators resets the next stats slot for all aggregators every second.
func resetAggregators() {
ticker := time.NewTicker(time.Second)
for range ticker.C {
muAggr.Lock()
for _, a := range aggregators {
a.resetNextSlot()
}
muAggr.Unlock()
}
}
// processQueryInfo processes the next queryInfo object.
func processQueryInfo() {
for qi := range aggrChan {
qi.aggr.processQueryInfo(qi)
}
}
// NewGatewayEndPointStatusAggregator creates a GatewayEndPointStatusAggregator.
func NewGatewayEndPointStatusAggregator() *GatewayEndPointStatusAggregator {
gepsa := &GatewayEndPointStatusAggregator{}
registerAggregator(gepsa)
return gepsa
}
// GatewayEndPointStatusAggregator tracks endpoint status for a gateway.
type GatewayEndPointStatusAggregator struct {
Keyspace string
Shard string
TabletType topodatapb.TabletType
Name string // the alternative name of an endpoint
Addr string // the host:port of an endpoint
// mu protects below fields.
mu sync.RWMutex
QueryCount uint64
QueryError uint64
// for QPS and latency (avg value over a minute)
tick uint32
queryCountInMinute [60]uint64
latencyInMinute [60]time.Duration
}
type queryInfo struct {
aggr *GatewayEndPointStatusAggregator
addr string
tabletType topodatapb.TabletType
elapsed time.Duration
hasError bool
}
// UpdateQueryInfo updates the aggregator with the given information about a query.
func (gepsa *GatewayEndPointStatusAggregator) UpdateQueryInfo(addr string, tabletType topodatapb.TabletType, elapsed time.Duration, hasError bool) {
qi := &queryInfo{
aggr: gepsa,
addr: addr,
tabletType: tabletType,
elapsed: elapsed,
hasError: hasError,
}
select {
case aggrChan <- qi:
default:
gatewayStatsChanFull.Add(1)
}
}
func (gepsa *GatewayEndPointStatusAggregator) processQueryInfo(qi *queryInfo) {
gepsa.mu.Lock()
defer gepsa.mu.Unlock()
if gepsa.TabletType != qi.tabletType {
gepsa.TabletType = qi.tabletType
// reset counters
gepsa.QueryCount = 0
gepsa.QueryError = 0
for i := 0; i < len(gepsa.queryCountInMinute); i++ {
gepsa.queryCountInMinute[i] = 0
}
for i := 0; i < len(gepsa.latencyInMinute); i++ {
gepsa.latencyInMinute[i] = 0
}
}
if qi.addr != "" {
gepsa.Addr = qi.addr
}
gepsa.QueryCount++
gepsa.queryCountInMinute[gepsa.tick]++
gepsa.latencyInMinute[gepsa.tick] += qi.elapsed
if qi.hasError {
gepsa.QueryError++
}
}
// GetCacheStatus returns a GatewayEndPointCacheStatus representing the current gateway status.
func (gepsa *GatewayEndPointStatusAggregator) GetCacheStatus() *GatewayEndPointCacheStatus {
status := &GatewayEndPointCacheStatus{
Keyspace: gepsa.Keyspace,
Shard: gepsa.Shard,
Name: gepsa.Name,
}
gepsa.mu.RLock()
defer gepsa.mu.RUnlock()
status.TabletType = gepsa.TabletType
status.Addr = gepsa.Addr
status.QueryCount = gepsa.QueryCount
status.QueryError = gepsa.QueryError
var totalQuery uint64
for _, c := range gepsa.queryCountInMinute {
totalQuery += c
}
var totalLatency time.Duration
for _, d := range gepsa.latencyInMinute {
totalLatency += d
}
status.QPS = totalQuery / 60
if totalQuery > 0 {
status.AvgLatency = float64(totalLatency.Nanoseconds()) / float64(totalQuery) / 1000000
}
return status
}
// resetNextSlot resets the next tracking slot.
func (gepsa *GatewayEndPointStatusAggregator) resetNextSlot() {
gepsa.mu.Lock()
defer gepsa.mu.Unlock()
gepsa.tick = (gepsa.tick + 1) % 60
gepsa.queryCountInMinute[gepsa.tick] = 0
gepsa.latencyInMinute[gepsa.tick] = time.Duration(0)
}