forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
schema_info.go
594 lines (548 loc) · 16.6 KB
/
schema_info.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
// Copyright 2012, 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 tabletserver
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strconv"
"sync"
"time"
log "github.com/golang/glog"
"github.com/youtube/vitess/go/acl"
"github.com/youtube/vitess/go/cache"
mproto "github.com/youtube/vitess/go/mysql/proto"
"github.com/youtube/vitess/go/sqltypes"
"github.com/youtube/vitess/go/stats"
"github.com/youtube/vitess/go/timer"
"github.com/youtube/vitess/go/vt/dbconnpool"
"github.com/youtube/vitess/go/vt/schema"
"github.com/youtube/vitess/go/vt/tableacl"
"github.com/youtube/vitess/go/vt/tabletserver/planbuilder"
)
const base_show_tables = "select table_name, table_type, unix_timestamp(create_time), table_comment from information_schema.tables where table_schema = database()"
const maxTableCount = 10000
type ExecPlan struct {
*planbuilder.ExecPlan
TableInfo *TableInfo
Fields []mproto.Field
Rules *QueryRules
Authorized tableacl.ACL
mu sync.Mutex
QueryCount int64
Time time.Duration
RowCount int64
ErrorCount int64
}
func (*ExecPlan) Size() int {
return 1
}
func (ep *ExecPlan) AddStats(queryCount int64, duration time.Duration, rowCount, errorCount int64) {
ep.mu.Lock()
ep.QueryCount += queryCount
ep.Time += duration
ep.RowCount += rowCount
ep.ErrorCount += errorCount
ep.mu.Unlock()
}
func (ep *ExecPlan) Stats() (queryCount int64, duration time.Duration, rowCount, errorCount int64) {
ep.mu.Lock()
queryCount = ep.QueryCount
duration = ep.Time
rowCount = ep.RowCount
errorCount = ep.ErrorCount
ep.mu.Unlock()
return
}
type SchemaOverride struct {
Name string
PKColumns []string
Cache *struct {
Type string
Prefix string
Table string
}
}
type SchemaInfo struct {
mu sync.Mutex
tables map[string]*TableInfo
queryCacheSize int
queries *cache.LRUCache
rules *QueryRules
connPool *dbconnpool.ConnectionPool
cachePool *CachePool
reloadTime time.Duration
lastChange time.Time
ticks *timer.Timer
}
func NewSchemaInfo(queryCacheSize int, reloadTime time.Duration, idleTimeout time.Duration) *SchemaInfo {
si := &SchemaInfo{
queryCacheSize: queryCacheSize,
queries: cache.NewLRUCache(int64(queryCacheSize)),
rules: NewQueryRules(),
connPool: dbconnpool.NewConnectionPool("", 2, idleTimeout),
reloadTime: reloadTime,
ticks: timer.NewTimer(reloadTime),
}
stats.Publish("QueryCacheLength", stats.IntFunc(si.queries.Length))
stats.Publish("QueryCacheSize", stats.IntFunc(si.queries.Size))
stats.Publish("QueryCacheCapacity", stats.IntFunc(si.queries.Capacity))
stats.Publish("QueryCacheOldest", stats.StringFunc(func() string {
return fmt.Sprintf("%v", si.queries.Oldest())
}))
stats.Publish("SchemaReloadTime", stats.DurationFunc(func() time.Duration {
return si.reloadTime
}))
_ = stats.NewMultiCountersFunc("TableStats", []string{"Table", "Stats"}, si.getTableStats)
stats.Publish("TableInvalidations", stats.CountersFunc(si.getTableInvalidations))
_ = stats.NewMultiCountersFunc("QueryCounts", []string{"Table", "Plan"}, si.getQueryCount)
_ = stats.NewMultiCountersFunc("QueryTimesNs", []string{"Table", "Plan"}, si.getQueryTime)
_ = stats.NewMultiCountersFunc("QueryRowCounts", []string{"Table", "Plan"}, si.getQueryRowCount)
_ = stats.NewMultiCountersFunc("QueryErrorCounts", []string{"Table", "Plan"}, si.getQueryErrorCount)
http.Handle("/debug/query_plans", si)
http.Handle("/debug/query_stats", si)
http.Handle("/debug/table_stats", si)
http.Handle("/debug/schema", si)
return si
}
func (si *SchemaInfo) Open(connFactory dbconnpool.CreateConnectionFunc, schemaOverrides []SchemaOverride, cachePool *CachePool, qrs *QueryRules, strictMode bool) {
si.connPool.Open(connFactory)
conn := getOrPanic(si.connPool)
defer conn.Recycle()
if strictMode && !conn.(*dbconnpool.PooledDBConnection).VerifyStrict() {
panic(NewTabletError(FATAL, "Could not verify strict mode"))
}
si.cachePool = cachePool
tables, err := conn.ExecuteFetch(base_show_tables, maxTableCount, false)
if err != nil {
panic(NewTabletError(FATAL, "Could not get table list: %v", err))
}
si.tables = make(map[string]*TableInfo, len(tables.Rows))
// TODO(sougou): Fix this in the parser.
si.tables["dual"] = &TableInfo{Table: schema.NewTable("dual")}
si.tables["DUAL"] = &TableInfo{Table: schema.NewTable("DUAL")}
for _, row := range tables.Rows {
tableName := row[0].String()
si.updateLastChange(row[2])
tableInfo := NewTableInfo(
conn,
tableName,
row[1].String(), // table_type
row[2], // create_time
row[3].String(), // table_comment
si.cachePool,
)
if tableInfo == nil {
continue
}
si.tables[tableName] = tableInfo
}
if schemaOverrides != nil {
si.override(schemaOverrides)
}
// Clear is not really needed. Doing it for good measure.
si.queries.Clear()
si.rules = qrs.Copy()
si.ticks.Start(func() { si.Reload() })
}
func (si *SchemaInfo) updateLastChange(createTime sqltypes.Value) {
if createTime.IsNull() {
return
}
t, err := strconv.ParseInt(createTime.String(), 10, 64)
if err != nil {
log.Warningf("Could not parse time %s: %v", createTime.String(), err)
return
}
if si.lastChange.Unix() < t {
si.lastChange = time.Unix(t, 0)
}
}
func (si *SchemaInfo) override(schemaOverrides []SchemaOverride) {
for _, override := range schemaOverrides {
table, ok := si.tables[override.Name]
if !ok {
log.Warningf("Table not found for override: %v", override)
continue
}
if override.PKColumns != nil {
if err := table.SetPK(override.PKColumns); err != nil {
log.Warningf("%v: %v", err, override)
continue
}
}
if si.cachePool.IsClosed() || override.Cache == nil {
continue
}
switch override.Cache.Type {
case "RW":
table.CacheType = schema.CACHE_RW
table.Cache = NewRowCache(table, si.cachePool)
case "W":
table.CacheType = schema.CACHE_W
if override.Cache.Table == "" {
log.Warningf("Incomplete cache specs: %v", override)
continue
}
totable, ok := si.tables[override.Cache.Table]
if !ok {
log.Warningf("Table not found: %v", override)
continue
}
if totable.Cache == nil {
log.Warningf("Table has no cache: %v", override)
continue
}
table.Cache = totable.Cache
default:
log.Warningf("Ignoring cache override: %v", override)
}
}
}
func (si *SchemaInfo) Close() {
si.ticks.Stop()
si.connPool.Close()
si.tables = nil
si.queries.Clear()
si.rules = NewQueryRules()
}
func (si *SchemaInfo) Reload() {
defer logError()
conn := getOrPanic(si.connPool)
defer conn.Recycle()
tables, err := conn.ExecuteFetch(fmt.Sprintf("%s and unix_timestamp(create_time) > %v", base_show_tables, si.lastChange.Unix()), maxTableCount, false)
if err != nil {
log.Warningf("Could not get table list for reload: %v", err)
return
}
log.Infof("Reloading schema")
for _, row := range tables.Rows {
tableName := row[0].String()
si.updateLastChange(row[2])
log.Infof("Reloading: %s", tableName)
si.mu.Lock()
_, ok := si.tables[tableName]
si.mu.Unlock()
if ok {
si.DropTable(tableName)
}
si.createTable(conn, tableName)
}
}
// safe to call this if Close has been called, as si.ticks will be stopped
// and won't fire
func (si *SchemaInfo) triggerReload() {
si.ticks.Trigger()
}
func (si *SchemaInfo) CreateTable(tableName string) {
conn := getOrPanic(si.connPool)
defer conn.Recycle()
si.createTable(conn, tableName)
}
func (si *SchemaInfo) createTable(conn dbconnpool.PoolConnection, tableName string) {
tables, err := conn.ExecuteFetch(fmt.Sprintf("%s and table_name = '%s'", base_show_tables, tableName), 1, false)
if err != nil {
panic(NewTabletError(FAIL, "Error fetching table %s: %v", tableName, err))
}
if len(tables.Rows) != 1 {
panic(NewTabletError(FAIL, "rows for %s !=1: %v", tableName, len(tables.Rows)))
}
tableInfo := NewTableInfo(
conn,
tableName,
tables.Rows[0][1].String(), // table_type
tables.Rows[0][2], // create_time
tables.Rows[0][3].String(), // table_comment
si.cachePool,
)
if tableInfo == nil {
panic(NewTabletError(FATAL, "Could not read table info: %s", tableName))
}
if tableInfo.CacheType == schema.CACHE_NONE {
log.Infof("Initialized table: %s", tableName)
} else {
log.Infof("Initialized cached table: %s", tableInfo.Cache.prefix)
}
si.mu.Lock()
defer si.mu.Unlock()
if _, ok := si.tables[tableName]; ok {
panic(NewTabletError(FAIL, "Table %s already exists", tableName))
}
si.tables[tableName] = tableInfo
}
func (si *SchemaInfo) DropTable(tableName string) {
si.mu.Lock()
defer si.mu.Unlock()
delete(si.tables, tableName)
si.queries.Clear()
log.Infof("Table %s forgotten", tableName)
}
func (si *SchemaInfo) GetPlan(logStats *SQLQueryStats, sql string) (plan *ExecPlan) {
si.mu.Lock()
defer si.mu.Unlock()
if plan := si.getQuery(sql); plan != nil {
return plan
}
var tableInfo *TableInfo
GetTable := func(tableName string) (table *schema.Table, ok bool) {
tableInfo, ok = si.tables[tableName]
if !ok {
return nil, false
}
return tableInfo.Table, true
}
splan, err := planbuilder.GetExecPlan(sql, GetTable)
if err != nil {
panic(NewTabletError(FAIL, "%s", err))
}
plan = &ExecPlan{ExecPlan: splan, TableInfo: tableInfo}
plan.Rules = si.rules.filterByPlan(sql, plan.PlanId, plan.TableName)
plan.Authorized = tableacl.Authorized(plan.TableName, plan.PlanId.MinRole())
if plan.PlanId.IsSelect() {
if plan.FieldQuery == nil {
log.Warningf("Cannot cache field info: %s", sql)
} else {
conn := getOrPanic(si.connPool)
defer conn.Recycle()
sql := plan.FieldQuery.Query
r, err := conn.ExecuteFetch(sql, 1, true)
logStats.QuerySources |= QUERY_SOURCE_MYSQL
logStats.NumberOfQueries += 1
logStats.AddRewrittenSql(sql)
if err != nil {
panic(NewTabletError(FAIL, "Error fetching fields: %v", err))
}
plan.Fields = r.Fields
}
} else if plan.PlanId == planbuilder.PLAN_DDL || plan.PlanId == planbuilder.PLAN_SET {
return plan
}
si.queries.Set(sql, plan)
return plan
}
// GetStreamPlan is similar to GetPlan, but doesn't use the cache
// and doesn't enforce a limit. It also just returns the parsed query.
func (si *SchemaInfo) GetStreamPlan(sql string) *planbuilder.ExecPlan {
GetTable := func(tableName string) (*schema.Table, bool) {
tableInfo, ok := si.tables[tableName]
if !ok {
return nil, false
}
return tableInfo.Table, true
}
plan, err := planbuilder.GetStreamExecPlan(sql, GetTable)
if err != nil {
panic(NewTabletError(FAIL, "%s", err))
}
return plan
}
func (si *SchemaInfo) SetRules(qrs *QueryRules) {
si.mu.Lock()
defer si.mu.Unlock()
si.rules = qrs.Copy()
si.queries.Clear()
}
func (si *SchemaInfo) GetRules() (qrs *QueryRules) {
si.mu.Lock()
defer si.mu.Unlock()
return si.rules.Copy()
}
func (si *SchemaInfo) GetTable(tableName string) *TableInfo {
si.mu.Lock()
defer si.mu.Unlock()
return si.tables[tableName]
}
func (si *SchemaInfo) GetSchema() []*schema.Table {
si.mu.Lock()
defer si.mu.Unlock()
tables := make([]*schema.Table, 0, len(si.tables))
for _, v := range si.tables {
tables = append(tables, v.Table)
}
return tables
}
func (si *SchemaInfo) getQuery(sql string) *ExecPlan {
if cacheResult, ok := si.queries.Get(sql); ok {
return cacheResult.(*ExecPlan)
}
return nil
}
func (si *SchemaInfo) SetQueryCacheSize(size int) {
if size <= 0 {
panic(NewTabletError(FAIL, "cache size %v out of range", size))
}
si.queryCacheSize = size
si.queries.SetCapacity(int64(size))
}
func (si *SchemaInfo) SetReloadTime(reloadTime time.Duration) {
si.reloadTime = reloadTime
si.ticks.Trigger()
si.ticks.SetInterval(reloadTime)
}
func (si *SchemaInfo) getTableStats() map[string]int64 {
si.mu.Lock()
defer si.mu.Unlock()
tstats := make(map[string]int64)
for k, v := range si.tables {
if v.CacheType != schema.CACHE_NONE {
hits, absent, misses, _ := v.Stats()
tstats[k+".Hits"] = hits
tstats[k+".Absent"] = absent
tstats[k+".Misses"] = misses
}
}
return tstats
}
func (si *SchemaInfo) getTableInvalidations() map[string]int64 {
si.mu.Lock()
defer si.mu.Unlock()
tstats := make(map[string]int64)
for k, v := range si.tables {
if v.CacheType != schema.CACHE_NONE {
_, _, _, invalidations := v.Stats()
tstats[k] = invalidations
}
}
return tstats
}
func (si *SchemaInfo) getQueryCount() map[string]int64 {
f := func(plan *ExecPlan) int64 {
queryCount, _, _, _ := plan.Stats()
return queryCount
}
return si.getQueryStats(f)
}
func (si *SchemaInfo) getQueryTime() map[string]int64 {
f := func(plan *ExecPlan) int64 {
_, time, _, _ := plan.Stats()
return int64(time)
}
return si.getQueryStats(f)
}
func (si *SchemaInfo) getQueryRowCount() map[string]int64 {
f := func(plan *ExecPlan) int64 {
_, _, rowCount, _ := plan.Stats()
return rowCount
}
return si.getQueryStats(f)
}
func (si *SchemaInfo) getQueryErrorCount() map[string]int64 {
f := func(plan *ExecPlan) int64 {
_, _, _, errorCount := plan.Stats()
return errorCount
}
return si.getQueryStats(f)
}
type queryStatsFunc func(*ExecPlan) int64
func (si *SchemaInfo) getQueryStats(f queryStatsFunc) map[string]int64 {
keys := si.queries.Keys()
qstats := make(map[string]int64)
for _, v := range keys {
if plan := si.getQuery(v); plan != nil {
table := plan.TableName
if table == "" {
table = "Join"
}
planType := plan.PlanId.String()
data := f(plan)
qstats[table+"."+planType] += data
}
}
return qstats
}
type perQueryStats struct {
Query string
Table string
Plan planbuilder.PlanType
QueryCount int64
Time time.Duration
RowCount int64
ErrorCount int64
}
func (si *SchemaInfo) ServeHTTP(response http.ResponseWriter, request *http.Request) {
if err := acl.CheckAccessHTTP(request, acl.DEBUGGING); err != nil {
acl.SendError(response, err)
return
}
if request.URL.Path == "/debug/query_plans" {
keys := si.queries.Keys()
response.Header().Set("Content-Type", "text/plain")
response.Write([]byte(fmt.Sprintf("Length: %d\n", len(keys))))
for _, v := range keys {
response.Write([]byte(fmt.Sprintf("%#v\n", v)))
if plan := si.getQuery(v); plan != nil {
if b, err := json.MarshalIndent(plan.ExecPlan, "", " "); err != nil {
response.Write([]byte(err.Error()))
} else {
response.Write(b)
}
response.Write(([]byte)("\n\n"))
}
}
} else if request.URL.Path == "/debug/query_stats" {
keys := si.queries.Keys()
response.Header().Set("Content-Type", "application/json; charset=utf-8")
qstats := make([]perQueryStats, 0, len(keys))
for _, v := range keys {
if plan := si.getQuery(v); plan != nil {
var pqstats perQueryStats
pqstats.Query = unicoded(v)
pqstats.Table = plan.TableName
pqstats.Plan = plan.PlanId
pqstats.QueryCount, pqstats.Time, pqstats.RowCount, pqstats.ErrorCount = plan.Stats()
qstats = append(qstats, pqstats)
}
}
if b, err := json.MarshalIndent(qstats, "", " "); err != nil {
response.Write([]byte(err.Error()))
} else {
response.Write(b)
}
} else if request.URL.Path == "/debug/table_stats" {
response.Header().Set("Content-Type", "application/json; charset=utf-8")
si.mu.Lock()
tstats := make(map[string]struct{ hits, absent, misses, invalidations int64 })
var temp, totals struct{ hits, absent, misses, invalidations int64 }
for k, v := range si.tables {
if v.CacheType != schema.CACHE_NONE {
temp.hits, temp.absent, temp.misses, temp.invalidations = v.Stats()
tstats[k] = temp
totals.hits += temp.hits
totals.absent += temp.absent
totals.misses += temp.misses
totals.invalidations += temp.invalidations
}
}
si.mu.Unlock()
response.Write([]byte("{\n"))
for k, v := range tstats {
fmt.Fprintf(response, "\"%s\": {\"Hits\": %v, \"Absent\": %v, \"Misses\": %v, \"Invalidations\": %v},\n", k, v.hits, v.absent, v.misses, v.invalidations)
}
fmt.Fprintf(response, "\"Totals\": {\"Hits\": %v, \"Absent\": %v, \"Misses\": %v, \"Invalidations\": %v}\n", totals.hits, totals.absent, totals.misses, totals.invalidations)
response.Write([]byte("}\n"))
} else if request.URL.Path == "/debug/schema" {
response.Header().Set("Content-Type", "application/json; charset=utf-8")
tables := si.GetSchema()
b, err := json.MarshalIndent(tables, "", " ")
if err != nil {
response.Write([]byte(err.Error()))
return
}
buf := bytes.NewBuffer(nil)
json.HTMLEscape(buf, b)
response.Write(buf.Bytes())
} else {
response.WriteHeader(http.StatusNotFound)
}
}
func applyFieldFilter(columnNumbers []int, input []mproto.Field) (output []mproto.Field) {
output = make([]mproto.Field, len(columnNumbers))
for colIndex, colPointer := range columnNumbers {
if colPointer >= 0 {
output[colIndex] = input[colPointer]
}
}
return output
}