-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathcrdb_internal.go
2345 lines (2180 loc) · 71 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
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.
package sql
import (
"bytes"
"context"
"fmt"
"net"
"net/url"
"sort"
"strings"
"time"
"github.com/pkg/errors"
"github.com/cockroachdb/cockroach/pkg/build"
"github.com/cockroachdb/cockroach/pkg/config"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/server/status"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/sql/sem/builtins"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sem/types"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/util/json"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
)
const crdbInternalName = "crdb_internal"
var crdbInternal = virtualSchema{
name: crdbInternalName,
tableDefs: []virtualSchemaDef{
crdbInternalBackwardDependenciesTable,
crdbInternalBuildInfoTable,
crdbInternalBuiltinFunctionsTable,
crdbInternalClusterQueriesTable,
crdbInternalClusterSessionsTable,
crdbInternalClusterSettingsTable,
crdbInternalCreateStmtsTable,
crdbInternalForwardDependenciesTable,
crdbInternalGossipNodesTable,
crdbInternalGossipAlertsTable,
crdbInternalGossipLivenessTable,
crdbInternalGossipNetworkTable,
crdbInternalIndexColumnsTable,
crdbInternalJobsTable,
crdbInternalKVNodeStatusTable,
crdbInternalKVStoreStatusTable,
crdbInternalLeasesTable,
crdbInternalLocalQueriesTable,
crdbInternalLocalSessionsTable,
crdbInternalLocalMetricsTable,
crdbInternalPartitionsTable,
crdbInternalRangesNoLeasesTable,
crdbInternalRangesView,
crdbInternalRuntimeInfoTable,
crdbInternalSchemaChangesTable,
crdbInternalSessionTraceTable,
crdbInternalSessionVariablesTable,
crdbInternalStmtStatsTable,
crdbInternalTableColumnsTable,
crdbInternalTableIndexesTable,
crdbInternalTablesTable,
crdbInternalZonesTable,
},
validWithNoDatabaseContext: true,
}
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, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
execCfg := p.ExecCfg()
nodeID := tree.NewDInt(tree.DInt(int64(execCfg.NodeID.Get())))
info := build.GetInfo()
for k, v := range map[string]string{
"Name": "CockroachDB",
"ClusterID": execCfg.ClusterID().String(),
"Organization": execCfg.Organization(),
"Build": info.Short(),
"Version": info.Tag,
"Channel": info.Channel,
} {
if err := addRow(
nodeID,
tree.NewDString(k),
tree.NewDString(v),
); err != nil {
return err
}
}
return nil
},
}
var crdbInternalRuntimeInfoTable = virtualSchemaTable{
schema: `
CREATE TABLE crdb_internal.node_runtime_info (
node_id INT NOT NULL,
component STRING NOT NULL,
field STRING NOT NULL,
value STRING NOT NULL
);
`,
populate: func(ctx context.Context, p *planner, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
if err := p.RequireSuperUser(ctx, "access the node runtime information"); err != nil {
return err
}
node := p.ExecCfg().NodeInfo
nodeID := tree.NewDInt(tree.DInt(int64(node.NodeID.Get())))
dbURL, err := node.PGURL(url.User(security.RootUser))
if err != nil {
return err
}
for _, item := range []struct {
component string
url *url.URL
}{
{"DB", dbURL}, {"UI", node.AdminURL()},
} {
var user string
if item.url.User != nil {
user = item.url.User.String()
}
host, port, err := net.SplitHostPort(item.url.Host)
if err != nil {
return err
}
for _, kv := range [][2]string{
{"URL", item.url.String()},
{"Scheme", item.url.Scheme},
{"User", user},
{"Host", host},
{"Port", port},
{"URI", item.url.RequestURI()},
} {
k, v := kv[0], kv[1]
if err := addRow(
nodeID,
tree.NewDString(item.component),
tree.NewDString(k),
tree.NewDString(v),
); 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,
drop_time TIMESTAMP,
audit_mode STRING NOT NULL
);
`,
populate: func(ctx context.Context, p *planner, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
descs, err := p.Tables().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 || p.CheckAnyPrivilege(ctx, table) != nil {
continue
}
dbName := dbNames[table.GetParentID()]
if dbName == "" {
// The parent database was deleted. This is possible e.g. when
// a database is dropped with CASCADE, and someone queries
// this virtual table before the dropped table descriptors are
// effectively deleted.
dbName = fmt.Sprintf("[%d]", table.GetParentID())
}
leaseNodeDatum := tree.DNull
leaseExpDatum := tree.DNull
if table.Lease != nil {
leaseNodeDatum = tree.NewDInt(tree.DInt(int64(table.Lease.NodeID)))
leaseExpDatum = tree.MakeDTimestamp(
timeutil.Unix(0, table.Lease.ExpirationTime), time.Nanosecond,
)
}
dropTimeDatum := tree.DNull
if table.DropTime != 0 {
dropTimeDatum = tree.MakeDTimestamp(
timeutil.Unix(0, table.DropTime), time.Nanosecond,
)
}
if err := addRow(
tree.NewDInt(tree.DInt(int64(table.ID))),
tree.NewDInt(tree.DInt(int64(table.GetParentID()))),
tree.NewDString(table.Name),
tree.NewDString(dbName),
tree.NewDInt(tree.DInt(int64(table.Version))),
tree.MakeDTimestamp(timeutil.Unix(0, table.ModificationTime.WallTime), time.Microsecond),
tree.TimestampToDecimal(table.ModificationTime),
tree.NewDString(table.FormatVersion.String()),
tree.NewDString(table.State.String()),
leaseNodeDatum,
leaseExpDatum,
dropTimeDatum,
tree.NewDString(table.AuditMode.String()),
); 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, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
descs, err := p.Tables().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 || p.CheckAnyPrivilege(ctx, table) != nil {
continue
}
tableID := tree.NewDInt(tree.DInt(int64(table.ID)))
parentID := tree.NewDInt(tree.DInt(int64(table.GetParentID())))
tableName := tree.NewDString(table.Name)
for _, mut := range table.Mutations {
mutType := "UNKNOWN"
targetID := tree.DNull
targetName := tree.DNull
switch d := mut.Descriptor_.(type) {
case *sqlbase.DescriptorMutation_Column:
mutType = "COLUMN"
targetID = tree.NewDInt(tree.DInt(int64(d.Column.ID)))
targetName = tree.NewDString(d.Column.Name)
case *sqlbase.DescriptorMutation_Index:
mutType = "INDEX"
targetID = tree.NewDInt(tree.DInt(int64(d.Index.ID)))
targetName = tree.NewDString(d.Index.Name)
}
if err := addRow(
tableID,
parentID,
tableName,
tree.NewDString(mutType),
targetID,
targetName,
tree.NewDString(mut.State.String()),
tree.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,
deleted BOOL NOT NULL
);
`,
populate: func(ctx context.Context, p *planner, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
leaseMgr := p.LeaseMgr()
nodeID := tree.NewDInt(tree.DInt(int64(leaseMgr.execCfg.NodeID.Get())))
leaseMgr.mu.Lock()
defer leaseMgr.mu.Unlock()
for tid, ts := range leaseMgr.mu.tables {
tableID := tree.NewDInt(tree.DInt(int64(tid)))
adder := func() error {
ts.mu.Lock()
defer ts.mu.Unlock()
dropped := tree.MakeDBool(tree.DBool(ts.mu.dropped))
for _, state := range ts.mu.active.data {
if p.CheckAnyPrivilege(ctx, &state.TableDescriptor) != nil {
continue
}
state.mu.Lock()
lease := state.mu.lease
state.mu.Unlock()
if lease == nil {
continue
}
if err := addRow(
nodeID,
tableID,
tree.NewDString(state.Name),
tree.NewDInt(tree.DInt(int64(state.GetParentID()))),
&lease.expiration,
dropped,
); err != nil {
return err
}
}
return nil
}
if err := adder(); err != nil {
return err
}
}
return nil
},
}
func tsOrNull(micros int64) tree.Datum {
if micros == 0 {
return tree.DNull
}
ts := timeutil.Unix(0, micros*time.Microsecond.Nanoseconds())
return tree.MakeDTimestamp(ts, time.Microsecond)
}
var crdbInternalJobsTable = virtualSchemaTable{
schema: `
CREATE TABLE crdb_internal.jobs (
job_id INT,
job_type STRING,
description STRING,
user_name STRING,
descriptor_ids INT[],
status STRING,
running_status STRING,
created TIMESTAMP,
started TIMESTAMP,
finished TIMESTAMP,
modified TIMESTAMP,
fraction_completed FLOAT,
high_water_timestamp DECIMAL,
error STRING,
coordinator_id INT
);
`,
populate: func(ctx context.Context, p *planner, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
query := `SELECT id, status, created, payload, progress FROM system.jobs`
rows, _ /* cols */, err :=
p.ExtendedEvalContext().ExecCfg.InternalExecutor.QueryWithSessionArgs(
ctx, "crdb-internal-jobs-table", p.txn, SessionArgs{User: p.SessionData().User}, query)
if err != nil {
return err
}
for _, r := range rows {
id, status, created, payloadBytes, progressBytes := r[0], r[1], r[2], r[3], r[4]
var jobType, description, username, descriptorIDs, started, runningStatus,
finished, modified, fractionCompleted, highWaterTimestamp, errorStr, leaseNode = tree.DNull,
tree.DNull, tree.DNull, tree.DNull, tree.DNull, tree.DNull, tree.DNull, tree.DNull,
tree.DNull, tree.DNull, tree.DNull, tree.DNull
// Extract data from the payload.
payload, err := jobs.UnmarshalPayload(payloadBytes)
if err != nil {
errorStr = tree.NewDString(fmt.Sprintf("error decoding payload: %v", err))
} else {
jobType = tree.NewDString(payload.Type().String())
description = tree.NewDString(payload.Description)
username = tree.NewDString(payload.Username)
descriptorIDsArr := tree.NewDArray(types.Int)
for _, descID := range payload.DescriptorIDs {
if err := descriptorIDsArr.Append(tree.NewDInt(tree.DInt(int(descID)))); err != nil {
return err
}
}
descriptorIDs = descriptorIDsArr
started = tsOrNull(payload.StartedMicros)
finished = tsOrNull(payload.FinishedMicros)
if payload.Lease != nil {
leaseNode = tree.NewDInt(tree.DInt(payload.Lease.NodeID))
}
errorStr = tree.NewDString(payload.Error)
}
// Extract data from the progress field.
if progressBytes != tree.DNull {
progress, err := jobs.UnmarshalProgress(progressBytes)
if err != nil {
baseErr := ""
if s, ok := errorStr.(*tree.DString); ok {
baseErr = string(*s)
if baseErr != "" {
baseErr += "\n"
}
}
errorStr = tree.NewDString(fmt.Sprintf("%serror decoding progress: %v", baseErr, err))
} else {
// Progress contains either fractionCompleted for traditional jobs,
// or the highWaterTimestamp for change feeds.
if highwater := progress.GetHighWater(); highwater != nil {
highWaterTimestamp = tree.TimestampToDecimal(*highwater)
} else {
fractionCompleted = tree.NewDFloat(tree.DFloat(progress.GetFractionCompleted()))
}
modified = tsOrNull(progress.ModifiedMicros)
runningStatusStr := ""
if len(progress.RunningStatus) > 0 {
if s, ok := status.(*tree.DString); ok {
if jobs.Status(string(*s)) == jobs.StatusRunning {
runningStatusStr = progress.RunningStatus
}
}
}
runningStatus = tree.NewDString(runningStatusStr)
}
}
// Report the data.
if err := addRow(
id,
jobType,
description,
username,
descriptorIDs,
status,
runningStatus,
created,
started,
finished,
modified,
fractionCompleted,
highWaterTimestamp,
errorStr,
leaseNode,
); 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(ctx context.Context, p *planner, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
if err := p.RequireSuperUser(ctx, "access application statistics"); err != nil {
return err
}
sqlStats := p.statsCollector.SQLStats()
if sqlStats == nil {
return errors.New("cannot access sql statistics from this context")
}
leaseMgr := p.LeaseMgr()
nodeID := tree.NewDInt(tree.DInt(int64(leaseMgr.execCfg.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 := tree.DNull
anonStr, ok := scrubStmtStatKey(p.getVirtualTabler(), stmtKey.stmt)
if ok {
anonymized = tree.NewDString(anonStr)
}
s := appStats.getStatsForStmt(stmtKey)
s.Lock()
errString := tree.DNull
if s.data.LastErr != "" {
errString = tree.NewDString(s.data.LastErr)
}
err := addRow(
nodeID,
tree.NewDString(appName),
tree.NewDString(stmtKey.flags()),
tree.NewDString(stmtKey.stmt),
anonymized,
tree.NewDInt(tree.DInt(s.data.Count)),
tree.NewDInt(tree.DInt(s.data.FirstAttemptCount)),
tree.NewDInt(tree.DInt(s.data.MaxRetries)),
errString,
tree.NewDFloat(tree.DFloat(s.data.NumRows.Mean)),
tree.NewDFloat(tree.DFloat(s.data.NumRows.GetVariance(s.data.Count))),
tree.NewDFloat(tree.DFloat(s.data.ParseLat.Mean)),
tree.NewDFloat(tree.DFloat(s.data.ParseLat.GetVariance(s.data.Count))),
tree.NewDFloat(tree.DFloat(s.data.PlanLat.Mean)),
tree.NewDFloat(tree.DFloat(s.data.PlanLat.GetVariance(s.data.Count))),
tree.NewDFloat(tree.DFloat(s.data.RunLat.Mean)),
tree.NewDFloat(tree.DFloat(s.data.RunLat.GetVariance(s.data.Count))),
tree.NewDFloat(tree.DFloat(s.data.ServiceLat.Mean)),
tree.NewDFloat(tree.DFloat(s.data.ServiceLat.GetVariance(s.data.Count))),
tree.NewDFloat(tree.DFloat(s.data.OverheadLat.Mean)),
tree.NewDFloat(tree.DFloat(s.data.OverheadLat.GetVariance(s.data.Count))),
)
s.Unlock()
if err != nil {
return err
}
}
}
return nil
},
}
// crdbInternalSessionTraceTable exposes the latest trace collected on this
// session (via SET TRACING={ON/OFF})
var crdbInternalSessionTraceTable = virtualSchemaTable{
schema: `
CREATE TABLE crdb_internal.session_trace (
span_idx INT NOT NULL, -- The span's index.
message_idx INT NOT NULL, -- The message's index within its span.
timestamp TIMESTAMPTZ NOT NULL,-- The message's timestamp.
duration INTERVAL, -- The span's duration. Set only on the first
-- (dummy) message on a span.
-- NULL if the span was not finished at the time
-- the trace has been collected.
operation STRING NULL, -- The span's operation.
loc STRING NOT NULL, -- The file name / line number prefix, if any.
tag STRING NOT NULL, -- The logging tag, if any.
message STRING NOT NULL, -- The logged message.
age INTERVAL NOT NULL -- The age of this message relative to the beginning of the trace.
);
`,
populate: func(ctx context.Context, p *planner, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
rows, err := p.ExtendedEvalContext().Tracing.getSessionTrace()
if err != nil {
return err
}
for _, r := range rows {
if err := addRow(r[:]...); err != nil {
return err
}
}
return nil
},
}
// crdbInternalClusterSettingsTable exposes the list of current
// cluster settings.
var crdbInternalClusterSettingsTable = virtualSchemaTable{
schema: `
CREATE TABLE crdb_internal.cluster_settings (
variable STRING NOT NULL,
value STRING NOT NULL,
type STRING NOT NULL,
description STRING NOT NULL
);
`,
populate: func(ctx context.Context, p *planner, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
if err := p.RequireSuperUser(ctx, "read crdb_internal.cluster_settings"); err != nil {
return err
}
for _, k := range settings.Keys() {
setting, _ := settings.Lookup(k)
if err := addRow(
tree.NewDString(k),
tree.NewDString(setting.String(&p.ExecCfg().Settings.SV)),
tree.NewDString(setting.Typ()),
tree.NewDString(setting.Description()),
); err != nil {
return err
}
}
return nil
},
}
// crdbInternalSessionVariablesTable exposes the session variables.
var crdbInternalSessionVariablesTable = virtualSchemaTable{
schema: `
CREATE TABLE crdb_internal.session_variables (
variable STRING NOT NULL,
value STRING NOT NULL
);
`,
populate: func(ctx context.Context, p *planner, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
for _, vName := range varNames {
gen := varGen[vName]
value := gen.Get(&p.extendedEvalCtx)
if err := addRow(
tree.NewDString(vName),
tree.NewDString(value),
); err != nil {
return err
}
}
return nil
},
}
const queriesSchemaPattern = `
CREATE TABLE crdb_internal.%s (
query_id STRING, -- the cluster-unique ID of the query
node_id INT NOT NULL, -- the node on which the query is running
user_name STRING, -- the user running the query
start TIMESTAMP, -- the start time of the query
query STRING, -- the SQL code of the query
client_address STRING, -- the address of the client that issued the query
application_name STRING, -- the name of the application as per SET application_name
distributed BOOL, -- whether the query is running distributed
phase STRING -- the current execution phase
);
`
// crdbInternalLocalQueriesTable exposes the list of running queries
// on the current node. The results are dependent on the current user.
var crdbInternalLocalQueriesTable = virtualSchemaTable{
schema: fmt.Sprintf(queriesSchemaPattern, "node_queries"),
populate: func(ctx context.Context, p *planner, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
req := serverpb.ListSessionsRequest{Username: p.SessionData().User}
response, err := p.extendedEvalCtx.StatusServer.ListLocalSessions(ctx, &req)
if err != nil {
return err
}
return populateQueriesTable(ctx, addRow, response)
},
}
// crdbInternalClusterQueriesTable exposes the list of running queries
// on the entire cluster. The result is dependent on the current user.
var crdbInternalClusterQueriesTable = virtualSchemaTable{
schema: fmt.Sprintf(queriesSchemaPattern, "cluster_queries"),
populate: func(ctx context.Context, p *planner, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
req := serverpb.ListSessionsRequest{Username: p.SessionData().User}
response, err := p.extendedEvalCtx.StatusServer.ListSessions(ctx, &req)
if err != nil {
return err
}
return populateQueriesTable(ctx, addRow, response)
},
}
func populateQueriesTable(
ctx context.Context, addRow func(...tree.Datum) error, response *serverpb.ListSessionsResponse,
) error {
for _, session := range response.Sessions {
for _, query := range session.ActiveQueries {
isDistributedDatum := tree.DNull
phase := strings.ToLower(query.Phase.String())
if phase == "executing" {
isDistributedDatum = tree.DBoolFalse
if query.IsDistributed {
isDistributedDatum = tree.DBoolTrue
}
}
if err := addRow(
tree.NewDString(query.ID),
tree.NewDInt(tree.DInt(session.NodeID)),
tree.NewDString(session.Username),
tree.MakeDTimestamp(query.Start, time.Microsecond),
tree.NewDString(query.Sql),
tree.NewDString(session.ClientAddress),
tree.NewDString(session.ApplicationName),
isDistributedDatum,
tree.NewDString(phase),
); err != nil {
return err
}
}
}
for _, rpcErr := range response.Errors {
log.Warning(ctx, rpcErr.Message)
if rpcErr.NodeID != 0 {
// Add a row with this node ID, the error for query, and
// nulls for all other columns.
if err := addRow(
tree.DNull, // query ID
tree.NewDInt(tree.DInt(rpcErr.NodeID)), // node ID
tree.DNull, // username
tree.DNull, // start
tree.NewDString("-- "+rpcErr.Message), // query
tree.DNull, // client_address
tree.DNull, // application_name
tree.DNull, // distributed
tree.DNull, // phase
); err != nil {
return err
}
}
}
return nil
}
const sessionsSchemaPattern = `
CREATE TABLE crdb_internal.%s (
node_id INT NOT NULL, -- the node on which the query is running
session_id STRING, -- the ID of the session
user_name STRING, -- the user running the query
client_address STRING, -- the address of the client that issued the query
application_name STRING, -- the name of the application as per SET application_name
active_queries STRING, -- the currently running queries as SQL
last_active_query STRING, -- the query that finished last on this session as SQL
session_start TIMESTAMP, -- the time when the session was opened
oldest_query_start TIMESTAMP, -- the time when the oldest query in the session was started
kv_txn STRING, -- the ID of the current KV transaction
alloc_bytes INT, -- the number of bytes allocated by the session
max_alloc_bytes INT -- the high water mark of bytes allocated by the session
);
`
// crdbInternalLocalSessionsTable exposes the list of running sessions
// on the current node. The results are dependent on the current user.
var crdbInternalLocalSessionsTable = virtualSchemaTable{
schema: fmt.Sprintf(sessionsSchemaPattern, "node_sessions"),
populate: func(ctx context.Context, p *planner, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
req := serverpb.ListSessionsRequest{Username: p.SessionData().User}
response, err := p.extendedEvalCtx.StatusServer.ListLocalSessions(ctx, &req)
if err != nil {
return err
}
return populateSessionsTable(ctx, addRow, response)
},
}
// crdbInternalClusterSessionsTable exposes the list of running sessions
// on the entire cluster. The result is dependent on the current user.
var crdbInternalClusterSessionsTable = virtualSchemaTable{
schema: fmt.Sprintf(sessionsSchemaPattern, "cluster_sessions"),
populate: func(ctx context.Context, p *planner, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
req := serverpb.ListSessionsRequest{Username: p.SessionData().User}
response, err := p.extendedEvalCtx.StatusServer.ListSessions(ctx, &req)
if err != nil {
return err
}
return populateSessionsTable(ctx, addRow, response)
},
}
func populateSessionsTable(
ctx context.Context, addRow func(...tree.Datum) error, response *serverpb.ListSessionsResponse,
) error {
for _, session := range response.Sessions {
// Generate active_queries and oldest_query_start
var activeQueries bytes.Buffer
var oldestStart time.Time
var oldestStartDatum tree.Datum
for idx, query := range session.ActiveQueries {
if idx > 0 {
activeQueries.WriteString("; ")
}
activeQueries.WriteString(query.Sql)
if oldestStart.IsZero() || query.Start.Before(oldestStart) {
oldestStart = query.Start
}
}
if oldestStart.IsZero() {
oldestStartDatum = tree.DNull
} else {
oldestStartDatum = tree.MakeDTimestamp(oldestStart, time.Microsecond)
}
kvTxnIDDatum := tree.DNull
if session.KvTxnID != nil {
kvTxnIDDatum = tree.NewDString(session.KvTxnID.String())
}
sessionID := BytesToClusterWideID(session.ID)
if err := addRow(
tree.NewDInt(tree.DInt(session.NodeID)),
tree.NewDString(sessionID.String()),
tree.NewDString(session.Username),
tree.NewDString(session.ClientAddress),
tree.NewDString(session.ApplicationName),
tree.NewDString(activeQueries.String()),
tree.NewDString(session.LastActiveQuery),
tree.MakeDTimestamp(session.Start, time.Microsecond),
oldestStartDatum,
kvTxnIDDatum,
tree.NewDInt(tree.DInt(session.AllocBytes)),
tree.NewDInt(tree.DInt(session.MaxAllocBytes)),
); err != nil {
return err
}
}
for _, rpcErr := range response.Errors {
log.Warning(ctx, rpcErr.Message)
if rpcErr.NodeID != 0 {
// Add a row with this node ID, error in active queries, and nulls
// for all other columns.
if err := addRow(
tree.NewDInt(tree.DInt(rpcErr.NodeID)), // node ID
tree.DNull, // session ID
tree.DNull, // username
tree.DNull, // client address
tree.DNull, // application name
tree.NewDString("-- "+rpcErr.Message), // active queries
tree.DNull, // last active query
tree.DNull, // session start
tree.DNull, // oldest_query_start
tree.DNull, // kv_txn
tree.DNull, // alloc_bytes
tree.DNull, // max_alloc_bytes
); err != nil {
return err
}
}
}
return nil
}
// crdbInternalLocalMetricsTable exposes a snapshot of the metrics on the
// current node.
var crdbInternalLocalMetricsTable = virtualSchemaTable{
schema: `CREATE TABLE crdb_internal.node_metrics (
store_id INT NULL, -- the store, if any, for this metric
name STRING NOT NULL, -- name of the metric
value FLOAT NOT NULL -- value of the metric
);`,
populate: func(ctx context.Context, p *planner, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
if err := p.RequireSuperUser(ctx, "read crdb_internal.node_metrics"); err != nil {
return err
}
mr := p.ExecCfg().MetricsRecorder
if mr == nil {
return nil
}
nodeStatus := mr.GenerateNodeStatus(ctx)
for i := 0; i <= len(nodeStatus.StoreStatuses); i++ {
storeID := tree.DNull
mtr := nodeStatus.Metrics
if i > 0 {
storeID = tree.NewDInt(tree.DInt(nodeStatus.StoreStatuses[i-1].Desc.StoreID))
mtr = nodeStatus.StoreStatuses[i-1].Metrics
}
for name, value := range mtr {
if err := addRow(
storeID,
tree.NewDString(name),
tree.NewDFloat(tree.DFloat(value)),
); err != nil {
return err
}
}
}
return nil
},
}
// crdbInternalBuiltinFunctionsTable exposes the built-in function
// metadata.
var crdbInternalBuiltinFunctionsTable = virtualSchemaTable{
schema: `
CREATE TABLE crdb_internal.builtin_functions (
function STRING NOT NULL,
signature STRING NOT NULL,
category STRING NOT NULL,
details STRING NOT NULL
);
`,
populate: func(ctx context.Context, _ *planner, _ *DatabaseDescriptor, addRow func(...tree.Datum) error) error {
for _, name := range builtins.AllBuiltinNames {
props, overloads := builtins.GetBuiltinProperties(name)
for _, f := range overloads {
if err := addRow(
tree.NewDString(name),
tree.NewDString(f.Signature(false /* simplify */)),
tree.NewDString(props.Category),
tree.NewDString(f.Info),
); err != nil {
return err
}