-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
admin.go
3947 lines (3615 loc) · 121 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"
apd "github.com/cockroachdb/apd/v3"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/config/zonepb"
"github.com/cockroachdb/cockroach/pkg/jobs"
"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/kvclient"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/allocator/storepool"
"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/username"
"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/privilege"
"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/sql/sqlutil"
"github.com/cockroachdb/cockroach/pkg/sql/syntheticprivilege"
"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/hlc"
"github.com/cockroachdb/cockroach/pkg/util/iterutil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/log/eventpb"
"github.com/cockroachdb/cockroach/pkg/util/log/logcrash"
"github.com/cockroachdb/cockroach/pkg/util/log/logpb"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/cockroach/pkg/util/tracing/tracingpb"
"github.com/cockroachdb/cockroach/pkg/util/tracing/tracingui"
"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/"
adminHealth = adminPrefix + "health"
// 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, // TODO(richardjcai): Remove this in 22.2.
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
internalExecutor *sql.InternalExecutor
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, adminAuthzCheck *adminPrivilegeChecker, ie *sql.InternalExecutor,
) *adminServer {
server := &adminServer{
adminPrivilegeChecker: adminAuthzCheck,
internalExecutor: 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 serverError(ctx context.Context, err error) error {
log.ErrorfDepth(ctx, 1, "%+v", err)
return errAdminAPIError
}
// serverErrorf logs the provided error and returns an error that should be returned by
// the RPC endpoint method.
func serverErrorf(ctx context.Context, format string, args ...interface{}) error {
log.ErrorfDepth(ctx, 1, format, args...)
return errAdminAPIError
}
// isNotFoundError returns true if err is a table/database not found error.
func 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, false /* strict */)
if err != nil {
return nil, serverError(ctx, 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, retErr error) {
ctx = s.server.AnnotateCtx(ctx)
sessionUser, err := userFromContext(ctx)
if err != nil {
return nil, serverError(ctx, err)
}
if err := s.requireViewActivityPermission(ctx); err != nil {
return nil, err
}
r, err := s.databasesHelper(ctx, req, sessionUser, 0, 0)
return r, maybeHandleNotFoundError(ctx, err)
}
// Note that the function returns plain errors, and it is the caller's
// responsibility to convert them to serverErrors.
func (s *adminServer) databasesHelper(
ctx context.Context,
req *serverpb.DatabasesRequest,
sessionUser username.SQLUsername,
limit, offset int,
) (_ *serverpb.DatabasesResponse, retErr error) {
it, err := s.server.sqlServer.internalExecutor.QueryIteratorEx(
ctx, "admin-show-dbs", nil, /* txn */
sessiondata.InternalExecutorOverride{User: sessionUser},
"SHOW DATABASES",
)
if err != nil {
return nil, err
}
// We have to make sure to close the iterator since we might return from the
// for loop early (before Next() returns false).
defer func(it sqlutil.InternalRows) { retErr = errors.CombineErrors(retErr, it.Close()) }(it)
var resp serverpb.DatabasesResponse
var hasNext bool
for hasNext, err = it.Next(ctx); hasNext; hasNext, err = it.Next(ctx) {
row := it.Cur()
dbDatum, ok := tree.AsDString(row[0])
if !ok {
return nil, errors.Errorf("type assertion failed on db name: %T", row[0])
}
dbName := string(dbDatum)
resp.Databases = append(resp.Databases, dbName)
}
if err != nil {
return nil, err
}
return &resp, nil
}
// maybeHandleNotFoundError checks the provided error and
// conditionally returns a gRPC NotFound code.
// It returns a gRPC error in any case.
func maybeHandleNotFoundError(ctx context.Context, err error) error {
if err == nil {
return nil
}
if isNotFoundError(err) {
return status.Errorf(codes.NotFound, "%s", err)
}
return serverError(ctx, err)
}
// 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, retErr error) {
ctx = s.server.AnnotateCtx(ctx)
userName, err := userFromContext(ctx)
if err != nil {
return nil, serverError(ctx, err)
}
if err := s.requireViewActivityPermission(ctx); err != nil {
return nil, err
}
r, err := s.databaseDetailsHelper(ctx, req, userName)
return r, maybeHandleNotFoundError(ctx, err)
}
// Note that the function returns plain errors, and it is the caller's
// responsibility to convert them to serverErrors.
func (s *adminServer) getDatabaseGrants(
ctx context.Context,
req *serverpb.DatabaseDetailsRequest,
userName username.SQLUsername,
limit, offset int,
) (resp []serverpb.DatabaseDetailsResponse_Grant, retErr error) {
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.
query := makeSQLQuery()
// We use Sprintf instead of the more canonical query argument approach, as
// that doesn't support arguments inside a SHOW subquery yet.
query.Append(fmt.Sprintf("SELECT * FROM [SHOW GRANTS ON DATABASE %s]", escDBName))
if limit > 0 {
query.Append(" LIMIT $", limit)
if offset > 0 {
query.Append(" OFFSET $", offset)
}
}
it, err := s.server.sqlServer.internalExecutor.QueryIteratorEx(
ctx, "admin-show-grants", nil, /* txn */
sessiondata.InternalExecutorOverride{User: userName},
// We only want to show the grants on the database.
query.String(), query.QueryArguments()...,
)
if err != nil {
return nil, err
}
// We have to make sure to close the iterator since we might return from the
// for loop early (before Next() returns false).
defer func(it sqlutil.InternalRows) { retErr = errors.CombineErrors(retErr, it.Close()) }(it)
{
const (
userCol = "grantee"
privilegesCol = "privilege_type"
)
ok, err := it.Next(ctx)
if err != nil {
return nil, err
}
if ok {
// If ok == false, the query returned 0 rows.
scanner := makeResultScanner(it.Types())
for ; ok; ok, err = it.Next(ctx) {
row := it.Cur()
// 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 = append(resp, grant)
}
if err = maybeHandleNotFoundError(ctx, err); err != nil {
return nil, err
}
}
}
return resp, nil
}
// Note that the function returns plain errors, and it is the caller's
// responsibility to convert them to serverErrors.
func (s *adminServer) getDatabaseTables(
ctx context.Context,
req *serverpb.DatabaseDetailsRequest,
userName username.SQLUsername,
limit, offset int,
) (resp []string, retErr error) {
query := makeSQLQuery()
query.Append(`SELECT table_schema, table_name FROM information_schema.tables
WHERE table_catalog = $ AND table_type != 'SYSTEM VIEW'`, req.Database)
query.Append(" ORDER BY table_name")
if limit > 0 {
query.Append(" LIMIT $", limit)
if offset > 0 {
query.Append(" OFFSET $", offset)
}
}
// Marshal table names.
it, err := s.server.sqlServer.internalExecutor.QueryIteratorEx(
ctx, "admin-show-tables", nil, /* txn */
sessiondata.InternalExecutorOverride{User: userName, Database: req.Database},
query.String(), query.QueryArguments()...)
if err != nil {
return nil, err
}
// We have to make sure to close the iterator since we might return from the
// for loop early (before Next() returns false).
defer func(it sqlutil.InternalRows) { retErr = errors.CombineErrors(retErr, it.Close()) }(it)
{
ok, err := it.Next(ctx)
if err != nil {
return nil, err
}
if ok {
// If ok == false, the query returned 0 rows.
scanner := makeResultScanner(it.Types())
for ; ok; ok, err = it.Next(ctx) {
row := it.Cur()
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 = append(resp, fmt.Sprintf("%s.%s",
tree.NameStringP(&schemaName), tree.NameStringP(&tableName)))
}
if err != nil {
return nil, err
}
}
}
return resp, nil
}
// Note that the function returns plain errors, and it is the caller's
// responsibility to convert them to serverErrors.
func (s *adminServer) getMiscDatabaseDetails(
ctx context.Context,
req *serverpb.DatabaseDetailsRequest,
userName username.SQLUsername,
resp *serverpb.DatabaseDetailsResponse,
) (*serverpb.DatabaseDetailsResponse, error) {
if resp == nil {
resp = &serverpb.DatabaseDetailsResponse{}
}
// Query the descriptor ID and zone configuration for this database.
databaseID, err := s.queryDatabaseID(ctx, userName, req.Database)
if err != nil {
return nil, err
}
resp.DescriptorID = int64(databaseID)
id, zone, zoneExists, err := s.queryZonePath(ctx, userName, []descpb.ID{databaseID})
if err != nil {
return nil, 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
}
// Note that the function returns plain errors, and it is the caller's
// responsibility to convert them to serverErrors.
func (s *adminServer) databaseDetailsHelper(
ctx context.Context, req *serverpb.DatabaseDetailsRequest, userName username.SQLUsername,
) (_ *serverpb.DatabaseDetailsResponse, retErr error) {
var resp serverpb.DatabaseDetailsResponse
var err error
resp.Grants, err = s.getDatabaseGrants(ctx, req, userName, 0, 0)
if err != nil {
return nil, err
}
resp.TableNames, err = s.getDatabaseTables(ctx, req, userName, 0, 0)
if err != nil {
return nil, err
}
_, err = s.getMiscDatabaseDetails(ctx, req, userName, &resp)
if err != nil {
return nil, err
}
if req.IncludeStats {
tableSpans, err := s.getDatabaseTableSpans(ctx, userName, req.Database, resp.TableNames)
if err != nil {
return nil, err
}
resp.Stats, err = s.getDatabaseStats(ctx, tableSpans)
if err != nil {
return nil, err
}
resp.Stats.NumIndexRecommendations, err = s.getNumDatabaseIndexRecommendations(ctx, req.Database, resp.TableNames)
if err != nil {
return nil, err
}
}
return &resp, nil
}
// Note that the function returns plain errors, and it is the caller's
// responsibility to convert them to serverErrors.
func (s *adminServer) getDatabaseTableSpans(
ctx context.Context, userName username.SQLUsername, dbName string, tableNames []string,
) (map[string]roachpb.Span, error) {
tableSpans := make(map[string]roachpb.Span, len(tableNames))
for _, tableName := range tableNames {
fullyQualifiedTableName, err := getFullyQualifiedTableName(dbName, tableName)
if err != nil {
return nil, err
}
tableID, err := s.queryTableID(ctx, userName, dbName, fullyQualifiedTableName)
if err != nil {
return nil, err
}
tableSpans[tableName] = generateTableSpan(tableID)
}
return tableSpans, nil
}
// Note that the function returns plain errors, and it is the caller's
// responsibility to convert them to serverErrors.
func (s *adminServer) getDatabaseStats(
ctx context.Context, tableSpans map[string]roachpb.Span,
) (*serverpb.DatabaseDetailsResponse_Stats, error) {
var stats serverpb.DatabaseDetailsResponse_Stats
type tableStatsResponse struct {
name string
resp *serverpb.TableStatsResponse
err error
}
responses := make(chan tableStatsResponse, len(tableSpans))
for tableName, tableSpan := range tableSpans {
// Because Go reuses loop variables across iterations, we must
// make these local, stable copies for the async task to close
// over, else our results will be nondeterministic.
tableName := tableName
tableSpan := tableSpan
if err := s.server.stopper.RunAsyncTask(
ctx, "server.adminServer: requesting table stats",
func(ctx context.Context) {
statsResponse, err := s.statsForSpan(ctx, tableSpan)
responses <- tableStatsResponse{
name: tableName,
resp: statsResponse,
err: err,
}
}); err != nil {
return nil, err
}
}
// Track all nodes storing databases.
nodeIDs := make(map[roachpb.NodeID]struct{})
for i := 0; i < len(tableSpans); i++ {
select {
case response := <-responses:
if response.err != nil {
stats.MissingTables = append(
stats.MissingTables,
&serverpb.DatabaseDetailsResponse_Stats_MissingTable{
Name: response.name,
ErrorMessage: response.err.Error(),
})
} else {
stats.RangeCount += response.resp.RangeCount
stats.ApproximateDiskBytes += response.resp.ApproximateDiskBytes
for _, id := range response.resp.NodeIDs {
nodeIDs[id] = struct{}{}
}
}
case <-ctx.Done():
return nil, ctx.Err()
}
}
stats.NodeIDs = make([]roachpb.NodeID, 0, len(nodeIDs))
for id := range nodeIDs {
stats.NodeIDs = append(stats.NodeIDs, id)
}
sort.Slice(stats.NodeIDs, func(i, j int) bool {
return stats.NodeIDs[i] < stats.NodeIDs[j]
})
return &stats, nil
}
func (s *adminServer) getNumDatabaseIndexRecommendations(
ctx context.Context, databaseName string, tableNames []string,
) (int32, error) {
var numDatabaseIndexRecommendations int
idxUsageStatsProvider := s.server.sqlServer.pgServer.SQLServer.GetLocalIndexStatistics()
for _, tableName := range tableNames {
tableIndexStatsRequest := &serverpb.TableIndexStatsRequest{
Database: databaseName,
Table: tableName,
}
tableIndexStatsResponse, err := getTableIndexUsageStats(ctx, tableIndexStatsRequest, idxUsageStatsProvider, s.ie, s.server.st, s.server.sqlServer.execCfg)
if err != nil {
return 0, err
}
numDatabaseIndexRecommendations += len(tableIndexStatsResponse.IndexRecommendations)
}
return int32(numDatabaseIndexRecommendations), 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.
//
// Note that the function returns plain errors, and it is the caller's
// responsibility to convert them to serverErrors.
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, retErr error) {
ctx = s.server.AnnotateCtx(ctx)
userName, err := userFromContext(ctx)
if err != nil {
return nil, serverError(ctx, err)
}
if err := s.requireViewActivityPermission(ctx); err != nil {
return nil, err
}
r, err := s.tableDetailsHelper(ctx, req, userName)
return r, maybeHandleNotFoundError(ctx, err)
}
// Note that the function returns plain errors, and it is the caller's
// responsibility to convert them to serverErrors.
func (s *adminServer) tableDetailsHelper(
ctx context.Context, req *serverpb.TableDetailsRequest, userName username.SQLUsername,
) (_ *serverpb.TableDetailsResponse, retErr error) {
escQualTable, err := getFullyQualifiedTableName(req.Database, req.Table)
if err != nil {
return nil, err
}
var resp serverpb.TableDetailsResponse
// Marshal SHOW COLUMNS result.
it, err := s.server.sqlServer.internalExecutor.QueryIteratorEx(
ctx, "admin-show-columns",
nil, /* txn */
sessiondata.InternalExecutorOverride{User: userName},
fmt.Sprintf("SHOW COLUMNS FROM %s", escQualTable),
)
if err != nil {
return nil, err
}
// We have to make sure to close the iterator since we might return from the
// for loop early (before Next() returns false).
defer func(it sqlutil.InternalRows) { retErr = errors.CombineErrors(retErr, it.Close()) }(it)
// 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"
)
ok, err := it.Next(ctx)
if err != nil {
return nil, err
}
if ok {
// If ok == false, the query returned 0 rows.
scanner := makeResultScanner(it.Types())
for ; ok; ok, err = it.Next(ctx) {
row := it.Cur()
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)
}
if err != nil {
return nil, err
}
}
}
// Marshal SHOW INDEX result.
it, err = s.server.sqlServer.internalExecutor.QueryIteratorEx(
ctx, "admin-showindex", nil, /* txn */
sessiondata.InternalExecutorOverride{User: userName},
fmt.Sprintf("SHOW INDEX FROM %s", escQualTable),
)
if err != nil {
return nil, err
}
// We have to make sure to close the iterator since we might return from the
// for loop early (before Next() returns false).
defer func(it sqlutil.InternalRows) { retErr = errors.CombineErrors(retErr, it.Close()) }(it)
{
const (
nameCol = "index_name"
nonUniqueCol = "non_unique"
seqCol = "seq_in_index"
columnCol = "column_name"
directionCol = "direction"
storingCol = "storing"
implicitCol = "implicit"
)
ok, err := it.Next(ctx)
if err != nil {
return nil, err
}
if ok {
// If ok == false, the query returned 0 rows.
scanner := makeResultScanner(it.Types())
for ; ok; ok, err = it.Next(ctx) {
row := it.Cur()
// 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)
}
if err != nil {
return nil, err
}
}
}
// Marshal SHOW GRANTS result.
it, err = s.server.sqlServer.internalExecutor.QueryIteratorEx(
ctx, "admin-show-grants", nil, /* txn */
sessiondata.InternalExecutorOverride{User: userName},
fmt.Sprintf("SHOW GRANTS ON TABLE %s", escQualTable),
)
if err != nil {
return nil, err
}
// We have to make sure to close the iterator since we might return from the
// for loop early (before Next() returns false).
defer func(it sqlutil.InternalRows) { retErr = errors.CombineErrors(retErr, it.Close()) }(it)
{
const (
userCol = "grantee"
privilegesCol = "privilege_type"
)
ok, err := it.Next(ctx)
if err != nil {
return nil, err
}
if ok {
// If ok == false, the query returned 0 rows.
scanner := makeResultScanner(it.Types())
for ; ok; ok, err = it.Next(ctx) {
row := it.Cur()
// 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)
}
if err != nil {
return nil, err
}
}
}
// Marshal SHOW CREATE result.
row, cols, err := s.server.sqlServer.internalExecutor.QueryRowExWithCols(
ctx, "admin-show-create", nil, /* txn */
sessiondata.InternalExecutorOverride{User: userName},
fmt.Sprintf("SHOW CREATE %s", escQualTable),
)
if err != nil {
return nil, err
}
{
const createCol = "create_statement"
if row == nil {
return nil, errors.New("create response not available")
}
scanner := makeResultScanner(cols)
var createStmt string
if err := scanner.Scan(row, createCol, &createStmt); err != nil {
return nil, err
}
resp.CreateTableStatement = createStmt
}
// MVCC Garbage result.
row, cols, err = s.server.sqlServer.internalExecutor.QueryRowExWithCols(
ctx, "admin-show-mvcc-garbage-info", nil,
sessiondata.InternalExecutorOverride{User: userName},
`WITH
range_stats AS (
SELECT
crdb_internal.range_stats(start_key) AS d
FROM
crdb_internal.ranges_no_leases
WHERE
table_id = $1::REGCLASS
),
aggregated AS (
SELECT
sum((d->>'live_bytes')::INT8) AS live,
sum(
(d->>'key_bytes')::INT8 +
(d->>'val_bytes')::INT8 +
COALESCE((d->>'range_key_bytes')::INT8, 0) +
COALESCE((d->>'range_val_bytes')::INT8, 0) +
(d->>'sys_bytes')::INT8) AS total
FROM
range_stats
)
SELECT
COALESCE(total, 0)::INT8 as total_bytes,
COALESCE(live, 0)::INT8 as live_bytes,
COALESCE(live / NULLIF(total,0), 0)::FLOAT8 as live_percentage
FROM aggregated`,
escQualTable,
)
if err != nil {
return nil, err
}
if row != nil {
scanner := makeResultScanner(cols)
var totalBytes int64
if err := scanner.Scan(row, "total_bytes", &totalBytes); err != nil {
return nil, err
}
resp.DataTotalBytes = totalBytes
var liveBytes int64
if err := scanner.Scan(row, "live_bytes", &liveBytes); err != nil {
return nil, err
}
resp.DataLiveBytes = liveBytes
var livePct float32
if err := scanner.Scan(row, "live_percentage", &livePct); err != nil {
return nil, err
}
resp.DataLivePercentage = livePct
}
// Marshal SHOW STATISTICS result.
row, cols, err = s.server.sqlServer.internalExecutor.QueryRowExWithCols(
ctx, "admin-show-statistics", nil, /* txn */
sessiondata.InternalExecutorOverride{User: userName},
fmt.Sprintf("SELECT max(created) AS created FROM [SHOW STATISTICS FOR TABLE %s]", escQualTable),
)
if err != nil {
return nil, err
}
if row != nil {
scanner := makeResultScanner(cols)
const createdCol = "created"
var createdTs *time.Time
if err := scanner.Scan(row, createdCol, &createdTs); err != nil {
return nil, err
}
resp.StatsLastCreatedAt = createdTs
}
// Marshal SHOW ZONE CONFIGURATION result.
row, cols, err = s.server.sqlServer.internalExecutor.QueryRowExWithCols(
ctx, "admin-show-zone-config", nil, /* txn */
sessiondata.InternalExecutorOverride{User: userName},
fmt.Sprintf("SHOW ZONE CONFIGURATION FOR TABLE %s", escQualTable))
if err != nil {
return nil, err
}
{
const rawConfigSQLColName = "raw_config_sql"