forked from cockroachdb/cockroach
-
Notifications
You must be signed in to change notification settings - Fork 0
/
admin.go
1239 lines (1115 loc) · 38.6 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.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// Author: Spencer Kimball (spencer.kimball@gmail.com)
// Author: Bram Gruneir (bram+code@cockroachlabs.com)
// Author: Cuong Do (cdo@cockroachlabs.com)
package server
import (
"bytes"
"fmt"
"strconv"
"strings"
"time"
"github.com/gogo/protobuf/proto"
gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/pkg/errors"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/config"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"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/settings"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/mon"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
)
const (
// adminPrefix is the prefix for RESTful endpoints used to provide an
// administrative interface to the cockroach cluster.
adminPrefix = "/_admin/v1/"
// eventLimit is the maximum number of events returned by any endpoints
// returning events.
apiEventLimit = 1000
)
// apiServerMessage is the standard body for all HTTP 500 responses.
var errAdminAPIError = grpc.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 {
server *Server
memMonitor mon.MemoryMonitor
memMetrics *sql.MemoryMetrics
}
// 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) *adminServer {
server := &adminServer{server: s, memMetrics: &s.adminMemMetrics}
// TODO(knz): We do not limit memory usage by admin operations
// yet. Is this wise?
server.memMonitor = mon.MakeUnlimitedMonitor(
context.Background(), "admin", nil, nil, noteworthyAdminMemoryUsageBytes,
)
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 {
return serverpb.RegisterAdminHandler(ctx, mux, conn)
}
// getUserProto will return the authenticated user. For now, this is just a stub until we
// figure out our authentication mechanism.
//
// TODO(cdo): Make this work when we have an authentication scheme for the
// API.
func (s *adminServer) getUser(_ proto.Message) string {
return security.RootUser
}
// 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
}
// checkQueryResults performs basic tests on the provided query results and returns
// the first error that was found.
func (s *adminServer) checkQueryResults(results []sql.Result, numResults int) error {
if a, e := len(results), numResults; a != e {
return errors.Errorf("# of results %d != expected %d", a, e)
}
for _, result := range results {
if result.Err != nil {
return errors.Errorf("%s", result.Err)
}
}
return nil
}
// firstNotFoundError returns the first table/database not found error in the
// provided results.
func (s *adminServer) firstNotFoundError(results []sql.Result) error {
for _, res := range results {
// TODO(cdo): Replace this crude suffix-matching with something more structured once we have
// more structured errors.
if res.Err != nil && strings.HasSuffix(res.Err.Error(), "does not exist") {
return res.Err
}
}
return nil
}
// NewContextAndSessionForRPC creates a context and SQL session to be used for
// serving an RPC request.
// The session will be initialized with a context derived from the returned one.
func (s *adminServer) NewContextAndSessionForRPC(
ctx context.Context, args sql.SessionArgs,
) (context.Context, *sql.Session) {
ctx = s.server.AnnotateCtx(ctx)
session := sql.NewSession(ctx, args, s.server.sqlExecutor, nil, s.memMetrics)
session.StartMonitor(&s.memMonitor, mon.BoundAccount{})
return ctx, session
}
// Databases is an endpoint that returns a list of databases.
func (s *adminServer) Databases(
ctx context.Context, req *serverpb.DatabasesRequest,
) (*serverpb.DatabasesResponse, error) {
args := sql.SessionArgs{User: s.getUser(req)}
ctx, session := s.NewContextAndSessionForRPC(ctx, args)
defer session.Finish(s.server.sqlExecutor)
r := s.server.sqlExecutor.ExecuteStatements(session, "SHOW DATABASES;", nil)
defer r.Close(ctx)
if err := s.checkQueryResults(r.ResultList, 1); err != nil {
return nil, s.serverError(err)
}
var resp serverpb.DatabasesResponse
for i, nRows := 0, r.ResultList[0].Rows.Len(); i < nRows; i++ {
row := r.ResultList[0].Rows.At(i)
dbDatum, ok := parser.AsDString(row[0])
if !ok {
return nil, s.serverErrorf("type assertion failed on db name: %T", row[0])
}
dbName := string(dbDatum)
if !s.server.sqlExecutor.IsVirtualDatabase(dbName) {
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) {
args := sql.SessionArgs{User: s.getUser(req)}
ctx, session := s.NewContextAndSessionForRPC(ctx, args)
defer session.Finish(s.server.sqlExecutor)
escDBName := parser.Name(req.Database).String()
if err := s.assertNotVirtualSchema(escDBName); err != nil {
return nil, err
}
// 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.
query := fmt.Sprintf("SHOW GRANTS ON DATABASE %s; SHOW TABLES FROM %s;", escDBName, escDBName)
r := s.server.sqlExecutor.ExecuteStatements(session, query, nil)
defer r.Close(ctx)
if err := s.firstNotFoundError(r.ResultList); err != nil {
return nil, grpc.Errorf(codes.NotFound, "%s", err)
}
if err := s.checkQueryResults(r.ResultList, 2); err != nil {
return nil, s.serverError(err)
}
// Marshal grants.
var resp serverpb.DatabaseDetailsResponse
{
const (
userCol = "User"
privilegesCol = "Privileges"
)
scanner := makeResultScanner(r.ResultList[0].Columns)
for i, nRows := 0, r.ResultList[0].Rows.Len(); i < nRows; i++ {
row := r.ResultList[0].Rows.At(i)
// 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.
{
const tableCol = "Table"
scanner := makeResultScanner(r.ResultList[1].Columns)
if a, e := len(r.ResultList[1].Columns), 1; a != e {
return nil, s.serverErrorf("show tables columns mismatch: %d != expected %d", a, e)
}
for i, nRows := 0, r.ResultList[1].Rows.Len(); i < nRows; i++ {
row := r.ResultList[1].Rows.At(i)
var tableName string
if err := scanner.Scan(row, tableCol, &tableName); err != nil {
return nil, err
}
resp.TableNames = append(resp.TableNames, tableName)
}
}
// Query the descriptor ID and zone configuration for this database.
{
path, err := s.queryDescriptorIDPath(ctx, session, []string{req.Database})
if err != nil {
return nil, s.serverError(err)
}
resp.DescriptorID = int64(path[1])
id, zone, zoneExists, err := s.queryZonePath(ctx, session, path)
if err != nil {
return nil, s.serverError(err)
}
if !zoneExists {
zone = config.DefaultZoneConfig()
}
resp.ZoneConfig = zone
switch id {
case path[1]:
resp.ZoneConfigLevel = serverpb.ZoneConfigurationLevel_DATABASE
default:
resp.ZoneConfigLevel = serverpb.ZoneConfigurationLevel_CLUSTER
}
}
return &resp, 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) {
args := sql.SessionArgs{User: s.getUser(req)}
ctx, session := s.NewContextAndSessionForRPC(ctx, args)
defer session.Finish(s.server.sqlExecutor)
escDBName := parser.Name(req.Database).String()
if err := s.assertNotVirtualSchema(escDBName); err != nil {
return nil, err
}
// TODO(cdo): Use real placeholders for the table and database names when we've extended our SQL
// grammar to allow that.
escTableName := parser.Name(req.Table).String()
escQualTable := fmt.Sprintf("%s.%s", escDBName, escTableName)
query := fmt.Sprintf("SHOW COLUMNS FROM %s; SHOW INDEX FROM %s; SHOW GRANTS ON TABLE %s; SHOW CREATE TABLE %s;",
escQualTable, escQualTable, escQualTable, escQualTable)
r := s.server.sqlExecutor.ExecuteStatements(session, query, nil)
defer r.Close(ctx)
if err := s.firstNotFoundError(r.ResultList); err != nil {
return nil, grpc.Errorf(codes.NotFound, "%s", err)
}
if err := s.checkQueryResults(r.ResultList, 4); err != nil {
return nil, err
}
var resp serverpb.TableDetailsResponse
// Marshal SHOW COLUMNS result.
//
// 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 marshalled JSON. I feel that this is counterintuitive, and this should be fixed
// for our API.
{
const (
fieldCol = "Field" // column name
typeCol = "Type"
nullCol = "Null"
defaultCol = "Default"
)
scanner := makeResultScanner(r.ResultList[0].Columns)
for i, nRows := 0, r.ResultList[0].Rows.Len(); i < nRows; i++ {
row := r.ResultList[0].Rows.At(i)
var col serverpb.TableDetailsResponse_Column
if err := scanner.Scan(row, fieldCol, &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
}
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
}
}
resp.Columns = append(resp.Columns, col)
}
}
// Marshal SHOW INDEX result.
{
const (
nameCol = "Name"
uniqueCol = "Unique"
seqCol = "Seq"
columnCol = "Column"
directionCol = "Direction"
storingCol = "Storing"
implicitCol = "Implicit"
)
scanner := makeResultScanner(r.ResultList[1].Columns)
for i, nRows := 0, r.ResultList[1].Rows.Len(); i < nRows; i++ {
row := r.ResultList[1].Rows.At(i)
// 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
}
if err := scanner.Scan(row, uniqueCol, &index.Unique); err != nil {
return nil, err
}
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.
{
const (
userCol = "User"
privilegesCol = "Privileges"
)
scanner := makeResultScanner(r.ResultList[2].Columns)
for i, nRows := 0, r.ResultList[2].Rows.Len(); i < nRows; i++ {
row := r.ResultList[2].Rows.At(i)
// 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 TABLE result.
{
const createTableCol = "CreateTable"
showResult := r.ResultList[3]
if showResult.Rows.Len() != 1 {
return nil, s.serverErrorf("CreateTable response not available.")
}
scanner := makeResultScanner(showResult.Columns)
var createStmt string
if err := scanner.Scan(showResult.Rows.At(0), createTableCol, &createStmt); err != nil {
return nil, err
}
resp.CreateTableStatement = createStmt
}
// 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.
{
iexecutor := sql.InternalExecutor{LeaseManager: s.server.leaseMgr}
var tableSpan roachpb.Span
if err := s.server.db.Txn(ctx, func(ctx context.Context, txn *client.Txn) error {
var err error
tableSpan, err = iexecutor.GetTableSpan(
ctx, s.getUser(req), txn, req.Database, req.Table,
)
return err
}); err != nil {
return nil, s.serverError(err)
}
tableRSpan := roachpb.RSpan{}
var err error
tableRSpan.Key, err = keys.Addr(tableSpan.Key)
if err != nil {
return nil, s.serverError(err)
}
tableRSpan.EndKey, err = keys.Addr(tableSpan.EndKey)
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
}
// Query the descriptor ID and zone configuration for this table.
{
path, err := s.queryDescriptorIDPath(ctx, session, []string{req.Database, req.Table})
if err != nil {
return nil, s.serverError(err)
}
resp.DescriptorID = int64(path[2])
id, zone, zoneExists, err := s.queryZonePath(ctx, session, path)
if err != nil {
return nil, s.serverError(err)
}
if !zoneExists {
zone = config.DefaultZoneConfig()
}
resp.ZoneConfig = zone
switch id {
case path[1]:
resp.ZoneConfigLevel = serverpb.ZoneConfigurationLevel_DATABASE
case path[2]:
resp.ZoneConfigLevel = serverpb.ZoneConfigurationLevel_TABLE
default:
resp.ZoneConfigLevel = serverpb.ZoneConfigurationLevel_CLUSTER
}
}
return &resp, nil
}
// TableStats is an endpoint that returns columns, indices, and other
// relevant details for the specified table.
func (s *adminServer) TableStats(
ctx context.Context, req *serverpb.TableStatsRequest,
) (*serverpb.TableStatsResponse, error) {
escDBName := parser.Name(req.Database).String()
if err := s.assertNotVirtualSchema(escDBName); err != nil {
return nil, err
}
// Get table span.
var tableSpan roachpb.Span
iexecutor := sql.InternalExecutor{LeaseManager: s.server.leaseMgr}
if err := s.server.db.Txn(ctx, func(ctx context.Context, txn *client.Txn) error {
var err error
tableSpan, err = iexecutor.GetTableSpan(ctx, s.getUser(req), txn, req.Database, req.Table)
return err
}); err != nil {
return nil, s.serverError(err)
}
startKey, err := keys.Addr(tableSpan.Key)
if err != nil {
return nil, s.serverError(err)
}
endKey, err := keys.Addr(tableSpan.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.
rangeDescKVs, err := s.server.db.Scan(ctx, keys.RangeMetaKey(startKey), keys.RangeMetaKey(endKey), 0)
if err != nil {
return nil, s.serverError(err)
}
// Extract a list of node IDs from the response.
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 {
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. Set a timeout on the context for
// these queries.
responses := make(chan nodeResponse)
nodeCtx, cancel := context.WithTimeout(ctx, base.NetworkTimeout)
defer cancel()
for nodeID := range nodeIDs {
nodeID := nodeID
if err := s.server.stopper.RunAsyncTask(nodeCtx, func(ctx context.Context) {
var spanResponse *serverpb.SpanStatsResponse
client, err := s.server.status.dialNode(nodeID)
if err == nil {
req := serverpb.SpanStatsRequest{
StartKey: startKey,
EndKey: endKey,
NodeID: nodeID.String(),
}
spanResponse, err = client.SpanStats(ctx, &req)
}
response := nodeResponse{
nodeID: nodeID,
resp: spanResponse,
err: err,
}
select {
case responses <- response:
// Response processed.
case <-ctx.Done():
// Context completed, response no longer needed.
}
}); 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)
}
case <-ctx.Done():
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) {
args := sql.SessionArgs{User: s.getUser(req)}
ctx, session := s.NewContextAndSessionForRPC(ctx, args)
defer session.Finish(s.server.sqlExecutor)
query := "SELECT username FROM system.users"
r := s.server.sqlExecutor.ExecuteStatements(session, query, nil)
defer r.Close(ctx)
if err := s.checkQueryResults(r.ResultList, 1); err != nil {
return nil, s.serverError(err)
}
var resp serverpb.UsersResponse
for i, nRows := 0, r.ResultList[0].Rows.Len(); i < nRows; i++ {
row := r.ResultList[0].Rows.At(i)
resp.Users = append(resp.Users, serverpb.UsersResponse_User{Username: string(parser.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) {
args := sql.SessionArgs{User: s.getUser(req)}
ctx, session := s.NewContextAndSessionForRPC(ctx, args)
defer session.Finish(s.server.sqlExecutor)
// 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 = $ ", parser.NewDString(req.Type))
}
if req.TargetId > 0 {
q.Append("AND targetID = $ ", parser.NewDInt(parser.DInt(req.TargetId)))
}
q.Append("ORDER BY timestamp DESC ")
q.Append("LIMIT $", parser.NewDInt(parser.DInt(apiEventLimit)))
if len(q.Errors()) > 0 {
return nil, s.serverErrors(q.Errors())
}
r := s.server.sqlExecutor.ExecuteStatements(session, q.String(), q.QueryArguments())
defer r.Close(ctx)
if err := s.checkQueryResults(r.ResultList, 1); err != nil {
return nil, s.serverError(err)
}
// Marshal response.
var resp serverpb.EventsResponse
scanner := makeResultScanner(r.ResultList[0].Columns)
for i, nRows := 0, r.ResultList[0].Rows.Len(); i < nRows; i++ {
row := r.ResultList[0].Rows.At(i)
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 err := scanner.ScanIndex(row, 5, &event.UniqueID); err != nil {
return nil, err
}
resp.Events = append(resp.Events, event)
}
return &resp, nil
}
// getUIData returns the values and timestamps for the given UI keys. Keys
// that are not found will not be returned.
func (s *adminServer) getUIData(
ctx context.Context, session *sql.Session, user string, keys []string,
) (*serverpb.GetUIDataResponse, error) {
if len(keys) == 0 {
return &serverpb.GetUIDataResponse{}, nil
}
// Query database.
query := makeSQLQuery()
query.Append("SELECT key, value, lastUpdated FROM system.ui WHERE key IN (")
for i, key := range keys {
if i != 0 {
query.Append(",")
}
query.Append("$", parser.NewDString(key))
}
query.Append(");")
if err := query.Errors(); err != nil {
return nil, s.serverErrorf("error constructing query: %v", err)
}
r := s.server.sqlExecutor.ExecuteStatements(session, query.String(), query.QueryArguments())
defer r.Close(ctx)
if err := s.checkQueryResults(r.ResultList, 1); err != nil {
return nil, s.serverError(err)
}
// Marshal results.
resp := serverpb.GetUIDataResponse{KeyValues: make(map[string]serverpb.GetUIDataResponse_Value)}
for i, nRows := 0, r.ResultList[0].Rows.Len(); i < nRows; i++ {
row := r.ResultList[0].Rows.At(i)
dKey, ok := parser.AsDString(row[0])
if !ok {
return nil, s.serverErrorf("unexpected type for UI key: %T", row[0])
}
dValue, ok := row[1].(*parser.DBytes)
if !ok {
return nil, s.serverErrorf("unexpected type for UI value: %T", row[1])
}
dLastUpdated, ok := row[2].(*parser.DTimestamp)
if !ok {
return nil, s.serverErrorf("unexpected type for UI lastUpdated: %T", row[2])
}
resp.KeyValues[string(dKey)] = serverpb.GetUIDataResponse_Value{
Value: []byte(*dValue),
LastUpdated: dLastUpdated.Time,
}
}
return &resp, nil
}
// SetUIData is an endpoint that stores the given key/value pairs in the
// system.ui table. See GetUIData for more details on semantics.
func (s *adminServer) SetUIData(
ctx context.Context, req *serverpb.SetUIDataRequest,
) (*serverpb.SetUIDataResponse, error) {
if len(req.KeyValues) == 0 {
return nil, grpc.Errorf(codes.InvalidArgument, "KeyValues cannot be empty")
}
args := sql.SessionArgs{User: s.getUser(req)}
ctx, session := s.NewContextAndSessionForRPC(ctx, args)
defer session.Finish(s.server.sqlExecutor)
for key, val := range req.KeyValues {
// Do an upsert of the key. We update each key in a separate transaction to
// avoid long-running transactions and possible deadlocks.
query := "UPSERT INTO system.ui (key, value, lastUpdated) VALUES ($1, $2, NOW())"
qargs := parser.MakePlaceholderInfo()
qargs.SetValue(`1`, parser.NewDString(key))
qargs.SetValue(`2`, parser.NewDBytes(parser.DBytes(val)))
r := s.server.sqlExecutor.ExecuteStatements(session, query, &qargs)
defer r.Close(ctx)
if err := s.checkQueryResults(r.ResultList, 1); err != nil {
return nil, s.serverError(err)
}
if a, e := r.ResultList[0].RowsAffected, 1; a != e {
return nil, s.serverErrorf("rows affected %d != expected %d", a, e)
}
}
return &serverpb.SetUIDataResponse{}, nil
}
// GetUIData returns data associated with the given keys, which was stored
// earlier through SetUIData.
//
// The stored values are meant to be opaque to the server. In the rare case that
// the server code needs to call this method, it should only read from keys that
// have the prefix `serverUIDataKeyPrefix`.
func (s *adminServer) GetUIData(
ctx context.Context, req *serverpb.GetUIDataRequest,
) (*serverpb.GetUIDataResponse, error) {
args := sql.SessionArgs{User: s.getUser(req)}
ctx, session := s.NewContextAndSessionForRPC(ctx, args)
defer session.Finish(s.server.sqlExecutor)
if len(req.Keys) == 0 {
return nil, grpc.Errorf(codes.InvalidArgument, "keys cannot be empty")
}
resp, err := s.getUIData(ctx, session, s.getUser(req), req.Keys)
if err != nil {
return nil, s.serverError(err)
}
return resp, nil
}
// Settings returns settings associated with the given keys.
func (s *adminServer) Settings(
ctx context.Context, req *serverpb.SettingsRequest,
) (*serverpb.SettingsResponse, error) {
keys := req.Keys
if len(keys) == 0 {
keys = settings.Keys()
}
resp := serverpb.SettingsResponse{KeyValues: make(map[string]serverpb.SettingsResponse_Value)}
for _, k := range keys {
v, desc, ok := settings.Lookup(k)
if !ok {
continue
}
resp.KeyValues[k] = serverpb.SettingsResponse_Value{
Type: v.Typ(),
Value: v.String(),
Description: desc,
}
}
return &resp, nil
}
// Cluster returns cluster metadata.
func (s *adminServer) Cluster(
_ context.Context, req *serverpb.ClusterRequest,
) (*serverpb.ClusterResponse, error) {
clusterID := s.server.node.ClusterID
if clusterID == (uuid.UUID{}) {
return nil, grpc.Errorf(codes.Unavailable, "cluster ID not yet available")
}
return &serverpb.ClusterResponse{ClusterID: clusterID.String()}, nil
}
// Health returns liveness for the node target of the request.
func (s *adminServer) Health(
ctx context.Context, req *serverpb.HealthRequest,
) (*serverpb.HealthResponse, error) {
isLive, err := s.server.nodeLiveness.IsLive(s.server.NodeID())
if err != nil {
return nil, grpc.Errorf(codes.Internal, err.Error())
}
if !isLive {
return nil, grpc.Errorf(codes.Unavailable, "node is not live")
}
return &serverpb.HealthResponse{}, nil
}
// Liveness returns the liveness state of all nodes on the cluster.
func (s *adminServer) Liveness(
context.Context, *serverpb.LivenessRequest,
) (*serverpb.LivenessResponse, error) {
return &serverpb.LivenessResponse{
Livenesses: s.server.nodeLiveness.GetLivenesses(),
}, nil
}
// Drain puts the node into the specified drain mode(s) and optionally
// instructs the process to terminate.
func (s *adminServer) Drain(req *serverpb.DrainRequest, stream serverpb.Admin_DrainServer) error {
on := make([]serverpb.DrainMode, len(req.On))
for i := range req.On {
on[i] = serverpb.DrainMode(req.On[i])
}
off := make([]serverpb.DrainMode, len(req.Off))
for i := range req.Off {
off[i] = serverpb.DrainMode(req.Off[i])
}
_ = s.server.Undrain(off)
nowOn, err := s.server.Drain(on)
if err != nil {
return err
}
res := serverpb.DrainResponse{
On: make([]int32, len(nowOn)),
}
for i := range nowOn {
res.On[i] = int32(nowOn[i])
}
if err := stream.Send(&res); err != nil {
return err
}
if !req.Shutdown {
return nil
}
s.server.grpc.Stop()
ctx := stream.Context()
go s.server.stopper.Stop(ctx)
select {
case <-s.server.stopper.IsStopped():
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// sqlQuery allows you to incrementally build a SQL query that uses
// placeholders. Instead of specific placeholders like $1, you instead use the
// temporary placeholder $.
type sqlQuery struct {
buf bytes.Buffer
pidx int
qargs parser.PlaceholderInfo
errs []error
}
func makeSQLQuery() *sqlQuery {
res := &sqlQuery{}
res.qargs.Clear()
return res
}
// String returns the full query.
func (q *sqlQuery) String() string {
if len(q.errs) > 0 {
return "couldn't generate query: please check Errors()"
}
return q.buf.String()
}
// Errors returns a slice containing all errors that have happened during the
// construction of this query.
func (q *sqlQuery) Errors() []error {
return q.errs
}
// QueryArguments returns a filled map of placeholders containing all arguments
// provided to this query through Append.
func (q *sqlQuery) QueryArguments() *parser.PlaceholderInfo {
return &q.qargs
}
// Append appends the provided string and any number of query parameters.
// Instead of using normal placeholders (e.g. $1, $2), use meta-placeholder $.
// This method rewrites the query so that it uses proper placeholders.
//
// For example, suppose we have the following calls:
//
// query.Append("SELECT * FROM foo WHERE a > $ AND a < $ ", arg1, arg2)
// query.Append("LIMIT $", limit)
//
// The query is rewritten into:
//