-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
admin.go
2556 lines (2313 loc) · 76.7 KB
/
admin.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 2014 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package server
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/cockroachdb/apd/v2"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/config/zonepb"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/liveness"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/liveness/livenesspb"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/server/debug"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/roleoption"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/ts/catalog"
"github.com/cockroachdb/cockroach/pkg/util/contextutil"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime"
gwutil "github.com/grpc-ecosystem/grpc-gateway/utilities"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
// adminPrefix is the prefix for RESTful endpoints used to provide an
// administrative interface to the cockroach cluster.
adminPrefix = "/_admin/v1/"
// defaultAPIEventLimit is the default maximum number of events returned by any
// endpoints returning events.
defaultAPIEventLimit = 1000
)
// Number of empty ranges for table descriptors that aren't actually tables. These
// cause special cases in range count computations because we split along them anyway,
// but they're not SQL tables.
func nonTableDescriptorRangeCount() int64 {
// NB: explicitly reference them for IDE usage.
return int64(len([]int{
keys.MetaRangesID,
keys.SystemRangesID,
keys.TimeseriesRangesID,
keys.LivenessRangesID,
keys.PublicSchemaID,
keys.TenantsRangesID,
}))
}
// apiServerMessage is the standard body for all HTTP 500 responses.
var errAdminAPIError = status.Errorf(codes.Internal, "An internal server error "+
"has occurred. Please check your CockroachDB logs for more details.")
// A adminServer provides a RESTful HTTP API to administration of
// the cockroach cluster.
type adminServer struct {
*adminPrivilegeChecker
server *Server
memMonitor *mon.BytesMonitor
}
// noteworthyAdminMemoryUsageBytes is the minimum size tracked by the
// admin SQL pool before the pool start explicitly logging overall
// usage growth in the log.
var noteworthyAdminMemoryUsageBytes = envutil.EnvOrDefaultInt64("COCKROACH_NOTEWORTHY_ADMIN_MEMORY_USAGE", 100*1024)
// newAdminServer allocates and returns a new REST server for
// administrative APIs.
func newAdminServer(s *Server, ie *sql.InternalExecutor) *adminServer {
server := &adminServer{
adminPrivilegeChecker: &adminPrivilegeChecker{ie: ie},
server: s,
}
// TODO(knz): We do not limit memory usage by admin operations
// yet. Is this wise?
server.memMonitor = mon.NewUnlimitedMonitor(
context.Background(),
"admin",
mon.MemoryResource,
nil,
nil,
noteworthyAdminMemoryUsageBytes,
s.ClusterSettings(),
)
return server
}
// RegisterService registers the GRPC service.
func (s *adminServer) RegisterService(g *grpc.Server) {
serverpb.RegisterAdminServer(g, s)
}
// RegisterGateway starts the gateway (i.e. reverse proxy) that proxies HTTP requests
// to the appropriate gRPC endpoints.
func (s *adminServer) RegisterGateway(
ctx context.Context, mux *gwruntime.ServeMux, conn *grpc.ClientConn,
) error {
// Register the /_admin/v1/stmtbundle endpoint, which serves statement support
// bundles as files.
stmtBundlePattern := gwruntime.MustPattern(gwruntime.NewPattern(
1, /* version */
[]int{
int(gwutil.OpLitPush), 0, int(gwutil.OpLitPush), 1, int(gwutil.OpLitPush), 2,
int(gwutil.OpPush), 0, int(gwutil.OpConcatN), 1, int(gwutil.OpCapture), 3},
[]string{"_admin", "v1", "stmtbundle", "id"},
"", /* verb */
))
mux.Handle("GET", stmtBundlePattern, func(
w http.ResponseWriter, req *http.Request, pathParams map[string]string,
) {
idStr, ok := pathParams["id"]
if !ok {
http.Error(w, "missing id", http.StatusBadRequest)
return
}
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
http.Error(w, "invalid id", http.StatusBadRequest)
return
}
s.getStatementBundle(ctx, id, w)
})
// Register the endpoints defined in the proto.
return serverpb.RegisterAdminHandler(ctx, mux, conn)
}
// serverError logs the provided error and returns an error that should be returned by
// the RPC endpoint method.
func (s *adminServer) serverError(err error) error {
log.ErrorfDepth(context.TODO(), 1, "%s", err)
return errAdminAPIError
}
// serverErrorf logs the provided error and returns an error that should be returned by
// the RPC endpoint method.
func (s *adminServer) serverErrorf(format string, args ...interface{}) error {
log.ErrorfDepth(context.TODO(), 1, format, args...)
return errAdminAPIError
}
// serverErrors logs the provided errors and returns an error that should be returned by
// the RPC endpoint method.
func (s *adminServer) serverErrors(errors []error) error {
log.ErrorfDepth(context.TODO(), 1, "%v", errors)
return errAdminAPIError
}
// isNotFoundError returns true if err is a table/database not found error.
func (s *adminServer) isNotFoundError(err error) bool {
// TODO(cdo): Replace this crude suffix-matching with something more structured once we have
// more structured errors.
return err != nil && strings.HasSuffix(err.Error(), "does not exist")
}
// AllMetricMetadata returns all metrics' metadata.
func (s *adminServer) AllMetricMetadata(
ctx context.Context, req *serverpb.MetricMetadataRequest,
) (*serverpb.MetricMetadataResponse, error) {
resp := &serverpb.MetricMetadataResponse{
Metadata: s.server.recorder.GetMetricsMetadata(),
}
return resp, nil
}
// ChartCatalog returns a catalog of Admin UI charts useful for debugging.
func (s *adminServer) ChartCatalog(
ctx context.Context, req *serverpb.ChartCatalogRequest,
) (*serverpb.ChartCatalogResponse, error) {
metricsMetadata := s.server.recorder.GetMetricsMetadata()
chartCatalog, err := catalog.GenerateCatalog(metricsMetadata)
if err != nil {
return nil, err
}
resp := &serverpb.ChartCatalogResponse{
Catalog: chartCatalog,
}
return resp, nil
}
// Databases is an endpoint that returns a list of databases.
func (s *adminServer) Databases(
ctx context.Context, req *serverpb.DatabasesRequest,
) (*serverpb.DatabasesResponse, error) {
ctx = s.server.AnnotateCtx(ctx)
sessionUser, err := userFromContext(ctx)
if err != nil {
return nil, err
}
rows, err := s.server.sqlServer.internalExecutor.QueryEx(
ctx, "admin-show-dbs", nil, /* txn */
sessiondata.InternalExecutorOverride{User: sessionUser},
"SHOW DATABASES",
)
if err != nil {
return nil, s.serverError(err)
}
var resp serverpb.DatabasesResponse
for _, row := range rows {
dbDatum, ok := tree.AsDString(row[0])
if !ok {
return nil, s.serverErrorf("type assertion failed on db name: %T", row[0])
}
dbName := string(dbDatum)
resp.Databases = append(resp.Databases, dbName)
}
return &resp, nil
}
// DatabaseDetails is an endpoint that returns grants and a list of table names
// for the specified database.
func (s *adminServer) DatabaseDetails(
ctx context.Context, req *serverpb.DatabaseDetailsRequest,
) (*serverpb.DatabaseDetailsResponse, error) {
ctx = s.server.AnnotateCtx(ctx)
userName, err := userFromContext(ctx)
if err != nil {
return nil, err
}
escDBName := tree.NameStringP(&req.Database)
// Placeholders don't work with SHOW statements, so we need to manually
// escape the database name.
//
// TODO(cdo): Use placeholders when they're supported by SHOW.
// Marshal grants.
rows, cols, err := s.server.sqlServer.internalExecutor.QueryWithCols(
ctx, "admin-show-grants", nil, /* txn */
sessiondata.InternalExecutorOverride{User: userName},
// We only want to show the grants on the database.
// Since public schemas inherit grants from the database,
// it is safe to query only the public schema here.
fmt.Sprintf("SELECT * FROM [SHOW GRANTS ON DATABASE %s] WHERE schema_name = 'public'", escDBName),
)
if s.isNotFoundError(err) {
return nil, status.Errorf(codes.NotFound, "%s", err)
}
if err != nil {
return nil, s.serverError(err)
}
var resp serverpb.DatabaseDetailsResponse
{
const (
schemaCol = "schema_name"
userCol = "grantee"
privilegesCol = "privilege_type"
)
scanner := makeResultScanner(cols)
for _, row := range rows {
var schemaName string
if err := scanner.Scan(row, schemaCol, &schemaName); err != nil {
return nil, err
}
// Marshal grant, splitting comma-separated privileges into a proper slice.
var grant serverpb.DatabaseDetailsResponse_Grant
var privileges string
if err := scanner.Scan(row, userCol, &grant.User); err != nil {
return nil, err
}
if err := scanner.Scan(row, privilegesCol, &privileges); err != nil {
return nil, err
}
grant.Privileges = strings.Split(privileges, ",")
resp.Grants = append(resp.Grants, grant)
}
}
// Marshal table names.
rows, cols, err = s.server.sqlServer.internalExecutor.QueryWithCols(
ctx, "admin-show-tables", nil, /* txn */
sessiondata.InternalExecutorOverride{User: userName, Database: req.Database},
`SELECT table_schema, table_name FROM information_schema.tables
WHERE table_catalog = $1 AND table_type != 'SYSTEM VIEW';`, req.Database)
if s.isNotFoundError(err) {
return nil, status.Errorf(codes.NotFound, "%s", err)
}
if err != nil {
return nil, s.serverError(err)
}
// Marshal table names.
{
scanner := makeResultScanner(cols)
for _, row := range rows {
var schemaName, tableName string
if err := scanner.Scan(row, "table_schema", &schemaName); err != nil {
return nil, err
}
if err := scanner.Scan(row, "table_name", &tableName); err != nil {
return nil, err
}
resp.TableNames = append(resp.TableNames, fmt.Sprintf("%s.%s",
tree.NameStringP(&schemaName), tree.NameStringP(&tableName)))
}
}
// Query the descriptor ID and zone configuration for this database.
{
databaseID, err := s.queryDatabaseID(ctx, userName, req.Database)
if err != nil {
return nil, s.serverError(err)
}
resp.DescriptorID = int64(databaseID)
id, zone, zoneExists, err := s.queryZonePath(ctx, userName, []descpb.ID{databaseID})
if err != nil {
return nil, s.serverError(err)
}
if !zoneExists {
zone = s.server.cfg.DefaultZoneConfig
}
resp.ZoneConfig = zone
switch id {
case databaseID:
resp.ZoneConfigLevel = serverpb.ZoneConfigurationLevel_DATABASE
default:
resp.ZoneConfigLevel = serverpb.ZoneConfigurationLevel_CLUSTER
}
}
return &resp, nil
}
// getFullyQualifiedTableName, given a database name and a tableName that either
// is a unqualified name or a schema-qualified name, returns a maximally
// qualified name: either database.table if the input wasn't schema qualified,
// or database.schema.table if it was.
func getFullyQualifiedTableName(dbName string, tableName string) (string, error) {
name, err := parser.ParseQualifiedTableName(tableName)
if err != nil {
// If we got a parse error, it could be that the user passed us an unescaped
// table name. Quote the whole thing and try again.
name, err = parser.ParseQualifiedTableName(tree.NameStringP(&tableName))
if err != nil {
return "", err
}
}
if !name.ExplicitSchema {
// If the schema wasn't explicitly set, craft the qualified table name to be
// database.table.
name.SchemaName = tree.Name(dbName)
name.ExplicitSchema = true
} else {
// Otherwise, add the database to the beginning of the name:
// database.schema.table.
name.CatalogName = tree.Name(dbName)
name.ExplicitCatalog = true
}
return name.String(), nil
}
// TableDetails is an endpoint that returns columns, indices, and other
// relevant details for the specified table.
func (s *adminServer) TableDetails(
ctx context.Context, req *serverpb.TableDetailsRequest,
) (*serverpb.TableDetailsResponse, error) {
ctx = s.server.AnnotateCtx(ctx)
userName, err := userFromContext(ctx)
if err != nil {
return nil, err
}
escQualTable, err := getFullyQualifiedTableName(req.Database, req.Table)
if err != nil {
return nil, err
}
var resp serverpb.TableDetailsResponse
// Marshal SHOW COLUMNS result.
rows, cols, err := s.server.sqlServer.internalExecutor.QueryWithCols(
ctx, "admin-show-columns",
nil, /* txn */
sessiondata.InternalExecutorOverride{User: userName},
fmt.Sprintf("SHOW COLUMNS FROM %s", escQualTable),
)
if s.isNotFoundError(err) {
return nil, status.Errorf(codes.NotFound, "%s", err)
}
if err != nil {
return nil, s.serverError(err)
}
// TODO(cdo): protobuf v3's default behavior for fields with zero values (e.g. empty strings)
// is to suppress them. So, if protobuf field "foo" is an empty string, "foo" won't show
// up in the marshaled JSON. I feel that this is counterintuitive, and this should be fixed
// for our API.
{
const (
colCol = "column_name"
typeCol = "data_type"
nullCol = "is_nullable"
defaultCol = "column_default"
genCol = "generation_expression"
hiddenCol = "is_hidden"
)
scanner := makeResultScanner(cols)
for _, row := range rows {
var col serverpb.TableDetailsResponse_Column
if err := scanner.Scan(row, colCol, &col.Name); err != nil {
return nil, err
}
if err := scanner.Scan(row, typeCol, &col.Type); err != nil {
return nil, err
}
if err := scanner.Scan(row, nullCol, &col.Nullable); err != nil {
return nil, err
}
if err := scanner.Scan(row, hiddenCol, &col.Hidden); err != nil {
return nil, err
}
isDefaultNull, err := scanner.IsNull(row, defaultCol)
if err != nil {
return nil, err
}
if !isDefaultNull {
if err := scanner.Scan(row, defaultCol, &col.DefaultValue); err != nil {
return nil, err
}
}
isGenNull, err := scanner.IsNull(row, genCol)
if err != nil {
return nil, err
}
if !isGenNull {
if err := scanner.Scan(row, genCol, &col.GenerationExpression); err != nil {
return nil, err
}
}
resp.Columns = append(resp.Columns, col)
}
}
// Marshal SHOW INDEX result.
rows, cols, err = s.server.sqlServer.internalExecutor.QueryWithCols(
ctx, "admin-showindex", nil, /* txn */
sessiondata.InternalExecutorOverride{User: userName},
fmt.Sprintf("SHOW INDEX FROM %s", escQualTable),
)
if s.isNotFoundError(err) {
return nil, status.Errorf(codes.NotFound, "%s", err)
}
if err != nil {
return nil, s.serverError(err)
}
{
const (
nameCol = "index_name"
nonUniqueCol = "non_unique"
seqCol = "seq_in_index"
columnCol = "column_name"
directionCol = "direction"
storingCol = "storing"
implicitCol = "implicit"
)
scanner := makeResultScanner(cols)
for _, row := range rows {
// Marshal grant, splitting comma-separated privileges into a proper slice.
var index serverpb.TableDetailsResponse_Index
if err := scanner.Scan(row, nameCol, &index.Name); err != nil {
return nil, err
}
var nonUnique bool
if err := scanner.Scan(row, nonUniqueCol, &nonUnique); err != nil {
return nil, err
}
index.Unique = !nonUnique
if err := scanner.Scan(row, seqCol, &index.Seq); err != nil {
return nil, err
}
if err := scanner.Scan(row, columnCol, &index.Column); err != nil {
return nil, err
}
if err := scanner.Scan(row, directionCol, &index.Direction); err != nil {
return nil, err
}
if err := scanner.Scan(row, storingCol, &index.Storing); err != nil {
return nil, err
}
if err := scanner.Scan(row, implicitCol, &index.Implicit); err != nil {
return nil, err
}
resp.Indexes = append(resp.Indexes, index)
}
}
// Marshal SHOW GRANTS result.
rows, cols, err = s.server.sqlServer.internalExecutor.QueryWithCols(
ctx, "admin-show-grants", nil, /* txn */
sessiondata.InternalExecutorOverride{User: userName},
fmt.Sprintf("SHOW GRANTS ON TABLE %s", escQualTable),
)
if s.isNotFoundError(err) {
return nil, status.Errorf(codes.NotFound, "%s", err)
}
if err != nil {
return nil, s.serverError(err)
}
{
const (
userCol = "grantee"
privilegesCol = "privilege_type"
)
scanner := makeResultScanner(cols)
for _, row := range rows {
// Marshal grant, splitting comma-separated privileges into a proper slice.
var grant serverpb.TableDetailsResponse_Grant
var privileges string
if err := scanner.Scan(row, userCol, &grant.User); err != nil {
return nil, err
}
if err := scanner.Scan(row, privilegesCol, &privileges); err != nil {
return nil, err
}
grant.Privileges = strings.Split(privileges, ",")
resp.Grants = append(resp.Grants, grant)
}
}
// Marshal SHOW CREATE result.
rows, cols, err = s.server.sqlServer.internalExecutor.QueryWithCols(
ctx, "admin-show-create", nil, /* txn */
sessiondata.InternalExecutorOverride{User: userName},
fmt.Sprintf("SHOW CREATE %s", escQualTable),
)
if s.isNotFoundError(err) {
return nil, status.Errorf(codes.NotFound, "%s", err)
}
if err != nil {
return nil, s.serverError(err)
}
{
const createCol = "create_statement"
if len(rows) != 1 {
return nil, s.serverErrorf("create response not available.")
}
scanner := makeResultScanner(cols)
var createStmt string
if err := scanner.Scan(rows[0], createCol, &createStmt); err != nil {
return nil, err
}
resp.CreateTableStatement = createStmt
}
var tableID descpb.ID
// Query the descriptor ID and zone configuration for this table.
{
databaseID, err := s.queryDatabaseID(ctx, userName, req.Database)
if err != nil {
return nil, s.serverError(err)
}
tableID, err = s.queryTableID(ctx, userName, req.Database, escQualTable)
if err != nil {
return nil, s.serverError(err)
}
resp.DescriptorID = int64(tableID)
id, zone, zoneExists, err := s.queryZonePath(ctx, userName, []descpb.ID{databaseID, tableID})
if err != nil {
return nil, s.serverError(err)
}
if !zoneExists {
zone = s.server.cfg.DefaultZoneConfig
}
resp.ZoneConfig = zone
switch id {
case databaseID:
resp.ZoneConfigLevel = serverpb.ZoneConfigurationLevel_DATABASE
case tableID:
resp.ZoneConfigLevel = serverpb.ZoneConfigurationLevel_TABLE
default:
resp.ZoneConfigLevel = serverpb.ZoneConfigurationLevel_CLUSTER
}
}
// Get the number of ranges in the table. We get the key span for the table
// data. Then, we count the number of ranges that make up that key span.
{
tableSpan := generateTableSpan(tableID)
tableRSpan, err := keys.SpanAddr(tableSpan)
if err != nil {
return nil, s.serverError(err)
}
rangeCount, err := s.server.distSender.CountRanges(ctx, tableRSpan)
if err != nil {
return nil, s.serverError(err)
}
resp.RangeCount = rangeCount
}
return &resp, nil
}
// generateTableSpan generates a table's key span.
//
// NOTE: this doesn't make sense for interleaved (children) table. As of
// 03/2018, callers around here use it anyway.
func generateTableSpan(tableID descpb.ID) roachpb.Span {
tableStartKey := keys.TODOSQLCodec.TablePrefix(uint32(tableID))
tableEndKey := tableStartKey.PrefixEnd()
return roachpb.Span{Key: tableStartKey, EndKey: tableEndKey}
}
// TableStats is an endpoint that returns disk usage and replication statistics
// for the specified table.
func (s *adminServer) TableStats(
ctx context.Context, req *serverpb.TableStatsRequest,
) (*serverpb.TableStatsResponse, error) {
ctx = s.server.AnnotateCtx(ctx)
userName, err := s.requireAdminUser(ctx)
if err != nil {
return nil, err
}
escQualTable, err := getFullyQualifiedTableName(req.Database, req.Table)
if err != nil {
return nil, err
}
tableID, err := s.queryTableID(ctx, userName, req.Database, escQualTable)
if err != nil {
return nil, s.serverError(err)
}
tableSpan := generateTableSpan(tableID)
return s.statsForSpan(ctx, tableSpan)
}
// NonTableStats is an endpoint that returns disk usage and replication
// statistics for non-table parts of the system.
func (s *adminServer) NonTableStats(
ctx context.Context, req *serverpb.NonTableStatsRequest,
) (*serverpb.NonTableStatsResponse, error) {
ctx = s.server.AnnotateCtx(ctx)
if _, err := s.requireAdminUser(ctx); err != nil {
return nil, err
}
timeSeriesStats, err := s.statsForSpan(ctx, roachpb.Span{
Key: keys.TimeseriesPrefix,
EndKey: keys.TimeseriesPrefix.PrefixEnd(),
})
if err != nil {
return nil, err
}
response := serverpb.NonTableStatsResponse{
TimeSeriesStats: timeSeriesStats,
}
spansForInternalUse := []roachpb.Span{
{
Key: keys.LocalMax,
EndKey: keys.TimeseriesPrefix,
},
{
Key: keys.TimeseriesKeyMax,
EndKey: keys.TableDataMin,
},
}
for _, span := range spansForInternalUse {
nonTableStats, err := s.statsForSpan(ctx, span)
if err != nil {
return nil, err
}
if response.InternalUseStats == nil {
response.InternalUseStats = nonTableStats
} else {
response.InternalUseStats.Add(nonTableStats)
}
}
// There are six empty ranges for table descriptors 17, 18, 19, 22, 29, and
// 37 that aren't actually tables (a.k.a. the PseudoTableIDs in pkg/keys).
// No data is ever really written to them since they don't have actual
// tables. Some backend work could probably be done to eliminate these empty
// ranges, but it may be more trouble than it's worth. In the meantime,
// sweeping them under the general-purpose "Internal use" label in
// the "Non-Table" section of the Databases page.
response.InternalUseStats.RangeCount += nonTableDescriptorRangeCount()
return &response, nil
}
func (s *adminServer) statsForSpan(
ctx context.Context, span roachpb.Span,
) (*serverpb.TableStatsResponse, error) {
startKey, err := keys.Addr(span.Key)
if err != nil {
return nil, s.serverError(err)
}
endKey, err := keys.Addr(span.EndKey)
if err != nil {
return nil, s.serverError(err)
}
// Get current range descriptors for table. This is done by scanning over
// meta2 keys for the range. A special case occurs if we wish to include
// the meta1 key range itself, in which case we'll get KeyMin back and that
// cannot be scanned (due to range-local addressing confusion). This is
// handled appropriately by adjusting the bounds to grab the descriptors
// for all ranges (including range1, which is not only gossiped but also
// persisted in meta1).
startMetaKey := keys.RangeMetaKey(startKey)
if bytes.Equal(startMetaKey, roachpb.RKeyMin) {
// This is the special case described above. The following key instructs
// the code below to scan all of the addressing, i.e. grab all of the
// descriptors including that for r1.
startMetaKey = keys.RangeMetaKey(keys.MustAddr(keys.Meta2Prefix))
}
rangeDescKVs, err := s.server.db.Scan(ctx, startMetaKey, keys.RangeMetaKey(endKey), 0)
if err != nil {
return nil, s.serverError(err)
}
// This map will store the nodes we need to fan out to.
nodeIDs := make(map[roachpb.NodeID]struct{})
for _, kv := range rangeDescKVs {
var rng roachpb.RangeDescriptor
if err := kv.Value.GetProto(&rng); err != nil {
return nil, s.serverError(err)
}
for _, repl := range rng.Replicas().All() {
nodeIDs[repl.NodeID] = struct{}{}
}
}
// Construct TableStatsResponse by sending an RPC to every node involved.
tableStatResponse := serverpb.TableStatsResponse{
NodeCount: int64(len(nodeIDs)),
// TODO(mrtracy): The "RangeCount" returned by TableStats is more
// accurate than the "RangeCount" returned by TableDetails, because this
// method always consistently queries the meta2 key range for the table;
// in contrast, TableDetails uses a method on the DistSender, which
// queries using a range metadata cache and thus may return stale data
// for tables that are rapidly splitting. However, one potential
// *advantage* of using the DistSender is that it will populate the
// DistSender's range metadata cache in the case where meta2 information
// for this table is not already present; the query used by TableStats
// does not populate the DistSender cache. We should consider plumbing
// TableStats' meta2 query through the DistSender so that it will share
// the advantage of populating the cache (without the disadvantage of
// potentially returning stale data).
// See Github #5435 for some discussion.
RangeCount: int64(len(rangeDescKVs)),
}
type nodeResponse struct {
nodeID roachpb.NodeID
resp *serverpb.SpanStatsResponse
err error
}
// Send a SpanStats query to each node.
responses := make(chan nodeResponse, len(nodeIDs))
for nodeID := range nodeIDs {
nodeID := nodeID // avoid data race
if err := s.server.stopper.RunAsyncTask(
ctx, "server.adminServer: requesting remote stats",
func(ctx context.Context) {
// Set a generous timeout on the context for each individual query.
var spanResponse *serverpb.SpanStatsResponse
err := contextutil.RunWithTimeout(ctx, "request remote stats", 5*base.NetworkTimeout,
func(ctx context.Context) error {
client, err := s.server.status.dialNode(ctx, nodeID)
if err == nil {
req := serverpb.SpanStatsRequest{
StartKey: startKey,
EndKey: endKey,
NodeID: nodeID.String(),
}
spanResponse, err = client.SpanStats(ctx, &req)
}
return err
})
// Channel is buffered, can always write.
responses <- nodeResponse{
nodeID: nodeID,
resp: spanResponse,
err: err,
}
}); err != nil {
return nil, err
}
}
for remainingResponses := len(nodeIDs); remainingResponses > 0; remainingResponses-- {
select {
case resp := <-responses:
// For nodes which returned an error, note that the node's data
// is missing. For successful calls, aggregate statistics.
if resp.err != nil {
tableStatResponse.MissingNodes = append(
tableStatResponse.MissingNodes,
serverpb.TableStatsResponse_MissingNode{
NodeID: resp.nodeID.String(),
ErrorMessage: resp.err.Error(),
},
)
} else {
tableStatResponse.Stats.Add(resp.resp.TotalStats)
tableStatResponse.ReplicaCount += int64(resp.resp.RangeCount)
tableStatResponse.ApproximateDiskBytes += resp.resp.ApproximateDiskBytes
}
case <-ctx.Done():
// Caller gave up, stop doing work.
return nil, ctx.Err()
}
}
return &tableStatResponse, nil
}
// Users returns a list of users, stripped of any passwords.
func (s *adminServer) Users(
ctx context.Context, req *serverpb.UsersRequest,
) (*serverpb.UsersResponse, error) {
ctx = s.server.AnnotateCtx(ctx)
userName, err := userFromContext(ctx)
if err != nil {
return nil, err
}
query := `SELECT username FROM system.users WHERE "isRole" = false`
rows, err := s.server.sqlServer.internalExecutor.QueryEx(
ctx, "admin-users", nil, /* txn */
sessiondata.InternalExecutorOverride{User: userName},
query,
)
if err != nil {
return nil, s.serverError(err)
}
var resp serverpb.UsersResponse
for _, row := range rows {
resp.Users = append(resp.Users, serverpb.UsersResponse_User{Username: string(tree.MustBeDString(row[0]))})
}
return &resp, nil
}
// Events is an endpoint that returns the latest event log entries, with the following
// optional URL parameters:
//
// type=STRING returns events with this type (e.g. "create_table")
// targetID=INT returns events for that have this targetID
func (s *adminServer) Events(
ctx context.Context, req *serverpb.EventsRequest,
) (*serverpb.EventsResponse, error) {
ctx = s.server.AnnotateCtx(ctx)
userName, isAdmin, err := s.getUserAndRole(ctx)
if err != nil {
return nil, err
}
redactEvents := false
if isAdmin {
// We obey the redacted bit only if the user is admin.
redactEvents = !req.UnredactedEvents
}
limit := req.Limit
if limit == 0 {
limit = defaultAPIEventLimit
}
// Execute the query.
q := makeSQLQuery()
q.Append(`SELECT timestamp, "eventType", "targetID", "reportingID", info, "uniqueID" `)
q.Append("FROM system.eventlog ")
q.Append("WHERE true ") // This simplifies the WHERE clause logic below.
if len(req.Type) > 0 {
q.Append(`AND "eventType" = $ `, req.Type)
}
if req.TargetId > 0 {
q.Append(`AND "targetID" = $ `, req.TargetId)
}
q.Append("ORDER BY timestamp DESC ")
if limit > 0 {
q.Append("LIMIT $", limit)
}
if len(q.Errors()) > 0 {
return nil, s.serverErrors(q.Errors())
}
rows, cols, err := s.server.sqlServer.internalExecutor.QueryWithCols(
ctx, "admin-events", nil, /* txn */
sessiondata.InternalExecutorOverride{User: userName},
q.String(), q.QueryArguments()...)
if err != nil {
return nil, s.serverError(err)
}
// Marshal response.
var resp serverpb.EventsResponse
scanner := makeResultScanner(cols)
for _, row := range rows {
var event serverpb.EventsResponse_Event
var ts time.Time
if err := scanner.ScanIndex(row, 0, &ts); err != nil {
return nil, err
}
event.Timestamp = ts
if err := scanner.ScanIndex(row, 1, &event.EventType); err != nil {
return nil, err
}
if err := scanner.ScanIndex(row, 2, &event.TargetID); err != nil {
return nil, err
}
if err := scanner.ScanIndex(row, 3, &event.ReportingID); err != nil {
return nil, err
}
if err := scanner.ScanIndex(row, 4, &event.Info); err != nil {
return nil, err
}
if event.EventType == string(sql.EventLogSetClusterSetting) {
if redactEvents {
event.Info = redactSettingsChange(event.Info)
}
}
if err := scanner.ScanIndex(row, 5, &event.UniqueID); err != nil {
return nil, err
}
resp.Events = append(resp.Events, event)
}
return &resp, nil
}
// make a best-effort attempt at redacting the setting value.
func redactSettingsChange(info string) string {
var s sql.EventLogSetClusterSettingDetail
if err := json.Unmarshal([]byte(info), &s); err != nil {
return ""
}
s.Value = "<hidden>"
ret, err := json.Marshal(s)
if err != nil {
return ""
}
return string(ret)
}
// RangeLog is an endpoint that returns the latest range log entries.
func (s *adminServer) RangeLog(