-
Notifications
You must be signed in to change notification settings - Fork 0
/
crdb_internal.go
455 lines (424 loc) · 13 KB
/
crdb_internal.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
// Copyright 2017 The Cockroach 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.
//
// Author: Raphael 'kena' Poss (knz@cockroachlabs.com)
package sql
import (
"reflect"
"sort"
"time"
"github.com/pkg/errors"
"golang.org/x/net/context"
"github.com/cockroachdb/cockroach/pkg/build"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
)
var crdbInternal = virtualSchema{
name: "crdb_internal",
tables: []virtualSchemaTable{
crdbInternalBuildInfoTable,
crdbInternalTablesTable,
crdbInternalLeasesTable,
crdbInternalSchemaChangesTable,
crdbInternalStmtStatsTable,
crdbInternalJobsTable,
},
}
var crdbInternalBuildInfoTable = virtualSchemaTable{
schema: `
CREATE TABLE crdb_internal.node_build_info (
node_id INT NOT NULL,
field STRING NOT NULL,
value STRING NOT NULL
);
`,
populate: func(_ context.Context, p *planner, addRow func(...parser.Datum) error) error {
leaseMgr := p.LeaseMgr()
nodeID := parser.NewDInt(parser.DInt(int64(leaseMgr.nodeID.Get())))
if err := addRow(
nodeID,
parser.NewDString("Name"),
parser.NewDString("CockroachDB"),
); err != nil {
return err
}
info := build.GetInfo()
s := reflect.ValueOf(&info).Elem()
t := s.Type()
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
if sv, ok := f.Interface().(string); ok {
fname := t.Field(i).Name
if err := addRow(nodeID, parser.NewDString(fname), parser.NewDString(sv)); err != nil {
return err
}
}
}
return nil
},
}
var crdbInternalTablesTable = virtualSchemaTable{
schema: `
CREATE TABLE crdb_internal.tables (
table_id INT NOT NULL,
parent_id INT NOT NULL,
name STRING NOT NULL,
database_name STRING NOT NULL,
version INT NOT NULL,
mod_time TIMESTAMP NOT NULL,
mod_time_logical DECIMAL NOT NULL,
format_version STRING NOT NULL,
state STRING NOT NULL,
sc_lease_node_id INT,
sc_lease_expiration_time TIMESTAMP,
create_table STRING NOT NULL
);
`,
populate: func(ctx context.Context, p *planner, addRow func(...parser.Datum) error) error {
descs, err := getAllDescriptors(ctx, p.txn)
if err != nil {
return err
}
dbNames := make(map[sqlbase.ID]string)
// Record database descriptors for name lookups.
for _, desc := range descs {
db, ok := desc.(*sqlbase.DatabaseDescriptor)
if ok {
dbNames[db.ID] = db.Name
}
}
// Note: we do not use forEachTableDesc() here because we want to
// include added and dropped descriptors.
for _, desc := range descs {
table, ok := desc.(*sqlbase.TableDescriptor)
if !ok || !userCanSeeDescriptor(table, p.session.User) {
continue
}
dbName := dbNames[table.ParentID]
if dbName == "" {
return errors.Errorf("could not find database %d", table.ParentID)
}
leaseNodeDatum := parser.DNull
leaseExpDatum := parser.DNull
if table.Lease != nil {
leaseNodeDatum = parser.NewDInt(parser.DInt(int64(table.Lease.NodeID)))
leaseExpDatum = parser.MakeDTimestamp(
time.Unix(0, table.Lease.ExpirationTime), time.Nanosecond,
)
}
create, err := p.showCreateTable(ctx, parser.Name(table.Name), table)
if err != nil {
return err
}
if err := addRow(
parser.NewDInt(parser.DInt(int64(table.ID))),
parser.NewDInt(parser.DInt(int64(table.ParentID))),
parser.NewDString(table.Name),
parser.NewDString(dbName),
parser.NewDInt(parser.DInt(int64(table.Version))),
parser.MakeDTimestamp(time.Unix(0, table.ModificationTime.WallTime), time.Microsecond),
parser.TimestampToDecimal(table.ModificationTime),
parser.NewDString(table.FormatVersion.String()),
parser.NewDString(table.State.String()),
leaseNodeDatum,
leaseExpDatum,
parser.NewDString(create),
); err != nil {
return err
}
}
return nil
},
}
var crdbInternalSchemaChangesTable = virtualSchemaTable{
schema: `
CREATE TABLE crdb_internal.schema_changes (
table_id INT NOT NULL,
parent_id INT NOT NULL,
name STRING NOT NULL,
type STRING NOT NULL,
target_id INT,
target_name STRING,
state STRING NOT NULL,
direction STRING NOT NULL
);
`,
populate: func(ctx context.Context, p *planner, addRow func(...parser.Datum) error) error {
descs, err := getAllDescriptors(ctx, p.txn)
if err != nil {
return err
}
// Note: we do not use forEachTableDesc() here because we want to
// include added and dropped descriptors.
for _, desc := range descs {
table, ok := desc.(*sqlbase.TableDescriptor)
if !ok || !userCanSeeDescriptor(table, p.session.User) {
continue
}
tableID := parser.NewDInt(parser.DInt(int64(table.ID)))
parentID := parser.NewDInt(parser.DInt(int64(table.ParentID)))
tableName := parser.NewDString(table.Name)
for _, mut := range table.Mutations {
mutType := "UNKNOWN"
targetID := parser.DNull
targetName := parser.DNull
switch d := mut.Descriptor_.(type) {
case *sqlbase.DescriptorMutation_Column:
mutType = "COLUMN"
targetID = parser.NewDInt(parser.DInt(int64(d.Column.ID)))
targetName = parser.NewDString(d.Column.Name)
case *sqlbase.DescriptorMutation_Index:
mutType = "INDEX"
targetID = parser.NewDInt(parser.DInt(int64(d.Index.ID)))
targetName = parser.NewDString(d.Index.Name)
}
if err := addRow(
tableID,
parentID,
tableName,
parser.NewDString(mutType),
targetID,
targetName,
parser.NewDString(mut.State.String()),
parser.NewDString(mut.Direction.String()),
); err != nil {
return err
}
}
}
return nil
},
}
var crdbInternalLeasesTable = virtualSchemaTable{
schema: `
CREATE TABLE crdb_internal.leases (
node_id INT NOT NULL,
table_id INT NOT NULL,
name STRING NOT NULL,
parent_id INT NOT NULL,
expiration TIMESTAMP NOT NULL,
released BOOL NOT NULL,
deleted BOOL NOT NULL
);
`,
populate: func(_ context.Context, p *planner, addRow func(...parser.Datum) error) error {
leaseMgr := p.LeaseMgr()
nodeID := parser.NewDInt(parser.DInt(int64(leaseMgr.nodeID.Get())))
leaseMgr.mu.Lock()
defer leaseMgr.mu.Unlock()
for tid, ts := range leaseMgr.mu.tables {
tableID := parser.NewDInt(parser.DInt(int64(tid)))
adder := func() error {
ts.mu.Lock()
defer ts.mu.Unlock()
deleted := parser.MakeDBool(parser.DBool(ts.deleted))
for _, state := range ts.active.data {
if !userCanSeeDescriptor(&state.TableDescriptor, p.session.User) {
continue
}
expCopy := state.expiration
if err := addRow(
nodeID,
tableID,
parser.NewDString(state.Name),
parser.NewDInt(parser.DInt(int64(state.ParentID))),
&expCopy,
parser.MakeDBool(parser.DBool(state.released)),
deleted,
); err != nil {
return err
}
}
return nil
}
if err := adder(); err != nil {
return err
}
}
return nil
},
}
var crdbInternalJobsTable = virtualSchemaTable{
schema: `
CREATE TABLE crdb_internal.jobs (
id INT,
type STRING,
description STRING,
username STRING,
descriptor_ids INT[],
status STRING,
created TIMESTAMP,
started TIMESTAMP,
finished TIMESTAMP,
modified TIMESTAMP,
fraction_completed FLOAT,
error STRING
);
`,
populate: func(ctx context.Context, p *planner, addRow func(...parser.Datum) error) error {
rows, err := p.queryRows(ctx, `SELECT id, status, created, payload FROM system.jobs`)
if err != nil {
return err
}
for _, r := range rows {
id, status, created, bytes := r[0], r[1], r[2], r[3]
payload, err := unmarshalJobPayload(bytes)
if err != nil {
return err
}
tsOrNull := func(micros int64) parser.Datum {
if micros == 0 {
return parser.DNull
}
ts := time.Unix(0, micros*time.Microsecond.Nanoseconds())
return parser.MakeDTimestamp(ts, time.Microsecond)
}
descriptorIDs := parser.NewDArray(parser.TypeInt)
for _, descID := range payload.DescriptorIDs {
if err := descriptorIDs.Append(parser.NewDInt(parser.DInt(int(descID)))); err != nil {
return err
}
}
if err := addRow(
id,
parser.NewDString(payload.typ()),
parser.NewDString(payload.Description),
parser.NewDString(payload.Username),
descriptorIDs,
status,
created,
tsOrNull(payload.StartedMicros),
tsOrNull(payload.FinishedMicros),
tsOrNull(payload.ModifiedMicros),
parser.NewDFloat(parser.DFloat(payload.FractionCompleted)),
parser.NewDString(payload.Error),
); err != nil {
return err
}
}
return nil
},
}
type stmtList []stmtKey
func (s stmtList) Len() int {
return len(s)
}
func (s stmtList) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s stmtList) Less(i, j int) bool {
return s[i].stmt < s[j].stmt
}
var crdbInternalStmtStatsTable = virtualSchemaTable{
schema: `
CREATE TABLE crdb_internal.node_statement_statistics (
node_id INT NOT NULL,
application_name STRING NOT NULL,
flags STRING NOT NULL,
key STRING NOT NULL,
anonymized STRING,
count INT NOT NULL,
first_attempt_count INT NOT NULL,
max_retries INT NOT NULL,
last_error STRING,
rows_avg FLOAT NOT NULL,
rows_var FLOAT NOT NULL,
parse_lat_avg FLOAT NOT NULL,
parse_lat_var FLOAT NOT NULL,
plan_lat_avg FLOAT NOT NULL,
plan_lat_var FLOAT NOT NULL,
run_lat_avg FLOAT NOT NULL,
run_lat_var FLOAT NOT NULL,
service_lat_avg FLOAT NOT NULL,
service_lat_var FLOAT NOT NULL,
overhead_lat_avg FLOAT NOT NULL,
overhead_lat_var FLOAT NOT NULL
);
`,
populate: func(_ context.Context, p *planner, addRow func(...parser.Datum) error) error {
if p.session.User != security.RootUser {
return errors.New("only root can access application statistics")
}
sqlStats := p.session.sqlStats
if sqlStats == nil {
return errors.New("cannot access sql statistics from this context")
}
leaseMgr := p.LeaseMgr()
nodeID := parser.NewDInt(parser.DInt(int64(leaseMgr.nodeID.Get())))
// Retrieve the application names and sort them to ensure the
// output is deterministic.
var appNames []string
sqlStats.Lock()
for n := range sqlStats.apps {
appNames = append(appNames, n)
}
sqlStats.Unlock()
sort.Strings(appNames)
// Now retrieve the application stats proper.
for _, appName := range appNames {
appStats := sqlStats.getStatsForApplication(appName)
// Retrieve the statement keys and sort them to ensure the
// output is deterministic.
var stmtKeys stmtList
appStats.Lock()
for k := range appStats.stmts {
stmtKeys = append(stmtKeys, k)
}
appStats.Unlock()
// Now retrieve the per-stmt stats proper.
for _, stmtKey := range stmtKeys {
anonymized := parser.DNull
anonStr, ok := scrubStmtStatKey(p.session.virtualSchemas, stmtKey.stmt)
if ok {
anonymized = parser.NewDString(anonStr)
}
s := appStats.getStatsForStmt(stmtKey)
s.Lock()
errString := parser.DNull
if s.data.LastErr != "" {
errString = parser.NewDString(s.data.LastErr)
}
err := addRow(
nodeID,
parser.NewDString(appName),
parser.NewDString(stmtKey.flags()),
parser.NewDString(stmtKey.stmt),
anonymized,
parser.NewDInt(parser.DInt(s.data.Count)),
parser.NewDInt(parser.DInt(s.data.FirstAttemptCount)),
parser.NewDInt(parser.DInt(s.data.MaxRetries)),
errString,
parser.NewDFloat(parser.DFloat(s.data.NumRows.Mean)),
parser.NewDFloat(parser.DFloat(s.data.NumRows.GetVariance(s.data.Count))),
parser.NewDFloat(parser.DFloat(s.data.ParseLat.Mean)),
parser.NewDFloat(parser.DFloat(s.data.ParseLat.GetVariance(s.data.Count))),
parser.NewDFloat(parser.DFloat(s.data.PlanLat.Mean)),
parser.NewDFloat(parser.DFloat(s.data.PlanLat.GetVariance(s.data.Count))),
parser.NewDFloat(parser.DFloat(s.data.RunLat.Mean)),
parser.NewDFloat(parser.DFloat(s.data.RunLat.GetVariance(s.data.Count))),
parser.NewDFloat(parser.DFloat(s.data.ServiceLat.Mean)),
parser.NewDFloat(parser.DFloat(s.data.ServiceLat.GetVariance(s.data.Count))),
parser.NewDFloat(parser.DFloat(s.data.OverheadLat.Mean)),
parser.NewDFloat(parser.DFloat(s.data.OverheadLat.GetVariance(s.data.Count))),
)
s.Unlock()
if err != nil {
return err
}
}
}
return nil
},
}