-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
status.go
3812 lines (3415 loc) · 120 KB
/
status.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"
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509/pkix"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/build"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/keyvisualizer/keyvisstorage"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/kvcoord"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/rangestats"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/allocator/storepool"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/liveness"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/server/diagnostics/diagnosticspb"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/server/status/statuspb"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/spanconfig"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/clusterunique"
"github.com/cockroachdb/cockroach/pkg/sql/contention"
"github.com/cockroachdb/cockroach/pkg/sql/contentionpb"
"github.com/cockroachdb/cockroach/pkg/sql/flowinfra"
"github.com/cockroachdb/cockroach/pkg/sql/privilege"
"github.com/cockroachdb/cockroach/pkg/sql/roleoption"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catconstants"
"github.com/cockroachdb/cockroach/pkg/sql/sqlinstance"
"github.com/cockroachdb/cockroach/pkg/sql/sqlstats/insights"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/contextutil"
"github.com/cockroachdb/cockroach/pkg/util/grpcutil"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/httputil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/log/logpb"
"github.com/cockroachdb/cockroach/pkg/util/metric"
"github.com/cockroachdb/cockroach/pkg/util/quotapool"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing/tracingpb"
"github.com/cockroachdb/cockroach/pkg/util/uint128"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime"
raft "go.etcd.io/raft/v3"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
// Default Maximum number of log entries returned.
defaultMaxLogEntries = 1000
// statusPrefix is the root of the cluster statistics and metrics API.
statusPrefix = "/_status/"
// statusVars exposes prometheus metrics for monitoring consumption.
statusVars = statusPrefix + "vars"
// loadStatusVars exposes prometheus metrics for instant monitoring of CPU load.
loadStatusVars = statusPrefix + "load"
// raftStateDormant is used when there is no known raft state.
raftStateDormant = "StateDormant"
// maxConcurrentRequests is the maximum number of RPC fan-out requests
// that will be made at any point of time.
maxConcurrentRequests = 100
// maxConcurrentPaginatedRequests is the maximum number of RPC fan-out
// requests that will be made at any point of time for a row-limited /
// paginated request. This should be much lower than maxConcurrentRequests
// as too much concurrency here can result in wasted results.
maxConcurrentPaginatedRequests = 4
)
var (
// Pattern for local used when determining the node ID.
localRE = regexp.MustCompile(`(?i)local`)
// Counter to count accesses to the prometheus vars endpoint /_status/vars .
telemetryPrometheusVars = telemetry.GetCounterOnce("monitoring.prometheus.vars")
// Counter to count accesses to the health check endpoint /health .
telemetryHealthCheck = telemetry.GetCounterOnce("monitoring.health.details")
)
type metricMarshaler interface {
json.Marshaler
PrintAsText(io.Writer) error
ScrapeIntoPrometheus(pm *metric.PrometheusExporter)
}
// baseStatusServer implements functionality shared by the tenantStatusServer
// and the full statusServer.
type baseStatusServer struct {
// Embedding the UnimplementedStatusServer lets us easily support
// treating the tenantStatusServer as implementing the StatusServer
// interface. We'd return an unimplemented error for the methods we
// didn't require anyway.
serverpb.UnimplementedStatusServer
log.AmbientContext
privilegeChecker *adminPrivilegeChecker
sessionRegistry *sql.SessionRegistry
closedSessionCache *sql.ClosedSessionCache
remoteFlowRunner *flowinfra.RemoteFlowRunner
st *cluster.Settings
sqlServer *SQLServer
rpcCtx *rpc.Context
stopper *stop.Stopper
serverIterator ServerIterator
clock *hlc.Clock
}
func isInternalAppName(app string) bool {
return strings.HasPrefix(app, catconstants.InternalAppNamePrefix)
}
// getLocalSessions returns a list of local sessions on this node. Note that the
// NodeID field is unset.
func (b *baseStatusServer) getLocalSessions(
ctx context.Context, req *serverpb.ListSessionsRequest,
) ([]serverpb.Session, error) {
ctx = forwardSQLIdentityThroughRPCCalls(ctx)
ctx = b.AnnotateCtx(ctx)
sessionUser, isAdmin, err := b.privilegeChecker.getUserAndRole(ctx)
if err != nil {
return nil, serverError(ctx, err)
}
hasViewActivityRedacted, err := b.privilegeChecker.hasRoleOption(ctx, sessionUser, roleoption.VIEWACTIVITYREDACTED)
if err != nil {
return nil, serverError(ctx, err)
}
hasViewActivity, err := b.privilegeChecker.hasRoleOption(ctx, sessionUser, roleoption.VIEWACTIVITY)
if err != nil {
return nil, serverError(ctx, err)
}
reqUsername, err := username.MakeSQLUsernameFromPreNormalizedStringChecked(req.Username)
if err != nil {
return nil, serverError(ctx, err)
}
if !isAdmin && !hasViewActivity && !hasViewActivityRedacted {
// For non-superusers, requests with an empty username is
// implicitly a request for the client's own sessions.
if reqUsername.Undefined() {
reqUsername = sessionUser
}
// Non-superusers are not allowed to query sessions others than their own.
if sessionUser != reqUsername {
return nil, status.Errorf(
codes.PermissionDenied,
"client user %q does not have permission to view sessions from user %q",
sessionUser, reqUsername)
}
}
// The empty username means "all sessions".
showAll := reqUsername.Undefined()
showInternal := SQLStatsShowInternal.Get(&b.st.SV) || req.IncludeInternal
sessions := b.sessionRegistry.SerializeAll()
var closedSessions []serverpb.Session
var closedSessionIDs map[uint128.Uint128]struct{}
if !req.ExcludeClosedSessions {
closedSessions = b.closedSessionCache.GetSerializedSessions()
closedSessionIDs = make(map[uint128.Uint128]struct{}, len(closedSessions))
for _, closedSession := range closedSessions {
closedSessionIDs[uint128.FromBytes(closedSession.ID)] = struct{}{}
}
}
reqUserNameNormalized := reqUsername.Normalized()
userSessions := make([]serverpb.Session, 0, len(sessions)+len(closedSessions))
addUserSession := func(session serverpb.Session) {
// We filter based on the session name instead of the executor type because we
// may want to surface certain internal sessions, such as those executed by
// the SQL over HTTP api, as non-internal.
if (reqUserNameNormalized != session.Username && !showAll) ||
(!showInternal && isInternalAppName(session.ApplicationName)) {
return
}
if !isAdmin && hasViewActivityRedacted && (reqUserNameNormalized != session.Username) {
// Remove queries with constants if user doesn't have correct privileges.
// Note that users can have both VIEWACTIVITYREDACTED and VIEWACTIVITY,
// with the former taking precedence.
for idx := range session.ActiveQueries {
session.ActiveQueries[idx].Sql = session.ActiveQueries[idx].SqlNoConstants
}
session.LastActiveQuery = session.LastActiveQueryNoConstants
}
userSessions = append(userSessions, session)
}
for _, session := range sessions {
// The same session can appear as both open and closed because reading the
// open and closed sessions is not synchronized. Prefer the closed session
// over the open one if the same session appears as both because it was
// closed in between reading the open sessions and reading the closed ones.
_, ok := closedSessionIDs[uint128.FromBytes(session.ID)]
if ok {
continue
}
addUserSession(session)
}
for _, session := range closedSessions {
addUserSession(session)
}
sort.Slice(userSessions, func(i, j int) bool {
return userSessions[i].Start.Before(userSessions[j].Start)
})
return userSessions, nil
}
// checkCancelPrivilege returns nil if the user has the necessary cancel action
// privileges for a session. This function returns a proper gRPC error status.
func (b *baseStatusServer) checkCancelPrivilege(
ctx context.Context, reqUsername username.SQLUsername, sessionUsername username.SQLUsername,
) error {
ctx = forwardSQLIdentityThroughRPCCalls(ctx)
ctx = b.AnnotateCtx(ctx)
ctxUsername, isCtxAdmin, err := b.privilegeChecker.getUserAndRole(ctx)
if err != nil {
return serverError(ctx, err)
}
if reqUsername.Undefined() {
reqUsername = ctxUsername
} else if reqUsername != ctxUsername && !isCtxAdmin {
// When CANCEL QUERY is run as a SQL statement, sessionUser is always root
// and the user who ran the statement is passed as req.Username.
return errRequiresAdmin
}
// A user can always cancel their own sessions/queries.
if sessionUsername == reqUsername {
return nil
}
// If reqUsername equals ctxUsername then isReqAdmin is isCtxAdmin and was
// checked inside getUserAndRole above.
isReqAdmin := isCtxAdmin
if reqUsername != ctxUsername {
isReqAdmin, err = b.privilegeChecker.hasAdminRole(ctx, reqUsername)
if err != nil {
return serverError(ctx, err)
}
}
// Admin users can cancel sessions/queries.
if isReqAdmin {
return nil
}
// Must have CANCELQUERY privilege to cancel other users'
// sessions/queries.
hasGlobalCancelQuery, err := b.privilegeChecker.hasGlobalPrivilege(ctx, reqUsername, privilege.CANCELQUERY)
if err != nil {
return serverError(ctx, err)
}
if !hasGlobalCancelQuery {
hasRoleCancelQuery, err := b.privilegeChecker.hasRoleOption(ctx, reqUsername, roleoption.CANCELQUERY)
if err != nil {
return serverError(ctx, err)
}
if !hasRoleCancelQuery {
return errRequiresRoleOption(roleoption.CANCELQUERY)
}
}
// Non-admins cannot cancel admins' sessions/queries.
isSessionAdmin, err := b.privilegeChecker.hasAdminRole(ctx, sessionUsername)
if err != nil {
return serverError(ctx, err)
}
if isSessionAdmin {
return status.Error(
codes.PermissionDenied, "permission denied to cancel admin session")
}
return nil
}
// ListLocalContentionEvents returns a list of contention events on this node.
func (b *baseStatusServer) ListLocalContentionEvents(
ctx context.Context, _ *serverpb.ListContentionEventsRequest,
) (*serverpb.ListContentionEventsResponse, error) {
ctx = forwardSQLIdentityThroughRPCCalls(ctx)
ctx = b.AnnotateCtx(ctx)
if err := b.privilegeChecker.requireViewActivityOrViewActivityRedactedPermission(ctx); err != nil {
// NB: not using serverError() here since the priv checker
// already returns a proper gRPC error status.
return nil, err
}
return &serverpb.ListContentionEventsResponse{
Events: b.sqlServer.execCfg.ContentionRegistry.Serialize(),
}, nil
}
func (b *baseStatusServer) ListLocalDistSQLFlows(
ctx context.Context, _ *serverpb.ListDistSQLFlowsRequest,
) (*serverpb.ListDistSQLFlowsResponse, error) {
ctx = forwardSQLIdentityThroughRPCCalls(ctx)
ctx = b.AnnotateCtx(ctx)
if err := b.privilegeChecker.requireViewActivityOrViewActivityRedactedPermission(ctx); err != nil {
// NB: not using serverError() here since the priv checker
// already returns a proper gRPC error status.
return nil, err
}
nodeIDOrZero, _ := b.sqlServer.sqlIDContainer.OptionalNodeID()
flows := b.remoteFlowRunner.Serialize()
response := &serverpb.ListDistSQLFlowsResponse{
Flows: make([]serverpb.DistSQLRemoteFlows, 0, len(flows)),
}
for _, f := range flows {
response.Flows = append(response.Flows, serverpb.DistSQLRemoteFlows{
FlowID: f.FlowID,
Infos: []serverpb.DistSQLRemoteFlows_Info{{
NodeID: nodeIDOrZero,
Timestamp: f.Timestamp,
Status: serverpb.DistSQLRemoteFlows_RUNNING,
Stmt: f.StatementSQL,
}},
})
}
// Per the contract of serverpb.ListDistSQLFlowsResponse, sort the flows
// lexicographically by FlowID.
sort.Slice(response.Flows, func(i, j int) bool {
return bytes.Compare(response.Flows[i].FlowID.GetBytes(), response.Flows[j].FlowID.GetBytes()) < 0
})
return response, nil
}
func (b *baseStatusServer) localExecutionInsights(
ctx context.Context,
) (*serverpb.ListExecutionInsightsResponse, error) {
var response serverpb.ListExecutionInsightsResponse
reader := b.sqlServer.pgServer.SQLServer.GetInsightsReader()
reader.IterateInsights(ctx, func(ctx context.Context, insight *insights.Insight) {
if insight == nil {
return
}
// Versions <=22.2.6 expects that Statement is not null when building the exec insights virtual table.
insightWithStmt := *insight
insightWithStmt.Statement = &insights.Statement{}
response.Insights = append(response.Insights, insightWithStmt)
})
return &response, nil
}
func (b *baseStatusServer) localTxnIDResolution(
req *serverpb.TxnIDResolutionRequest,
) *serverpb.TxnIDResolutionResponse {
txnIDCache := b.sqlServer.pgServer.SQLServer.GetTxnIDCache()
unresolvedTxnIDs := make(map[uuid.UUID]struct{}, len(req.TxnIDs))
for _, txnID := range req.TxnIDs {
unresolvedTxnIDs[txnID] = struct{}{}
}
resp := &serverpb.TxnIDResolutionResponse{
ResolvedTxnIDs: make([]contentionpb.ResolvedTxnID, 0, len(req.TxnIDs)),
}
for i := range req.TxnIDs {
if txnFingerprintID, found := txnIDCache.Lookup(req.TxnIDs[i]); found {
resp.ResolvedTxnIDs = append(resp.ResolvedTxnIDs, contentionpb.ResolvedTxnID{
TxnID: req.TxnIDs[i],
TxnFingerprintID: txnFingerprintID,
})
}
}
// If we encounter any transaction ID that we cannot resolve, we tell the
// txnID cache to drain its write buffer (note: The .DrainWriteBuffer() call
// is asynchronous). The client of this RPC will perform retries.
if len(unresolvedTxnIDs) > 0 {
txnIDCache.DrainWriteBuffer()
}
return resp
}
func (b *baseStatusServer) localTransactionContentionEvents(
shouldRedactContendingKey bool,
) *serverpb.TransactionContentionEventsResponse {
registry := b.sqlServer.execCfg.ContentionRegistry
resp := &serverpb.TransactionContentionEventsResponse{
Events: make([]contentionpb.ExtendedContentionEvent, 0),
}
// Ignore error returned by ForEachEvent() since if our own callback doesn't
// return error, ForEachEvent() also doesn't return error.
_ = registry.ForEachEvent(func(event *contentionpb.ExtendedContentionEvent) error {
if shouldRedactContendingKey {
event.BlockingEvent.Key = []byte{}
}
resp.Events = append(resp.Events, *event)
return nil
})
return resp
}
// A statusServer provides a RESTful status API.
type statusServer struct {
*baseStatusServer
cfg *base.Config
db *kv.DB
metricSource metricMarshaler
si systemInfoOnce
stmtDiagnosticsRequester StmtDiagnosticsRequester
internalExecutor *sql.InternalExecutor
// cancelSemaphore is a semaphore that limits the number of
// concurrent calls to the pgwire query cancellation endpoint. This
// is needed to avoid the risk of a DoS attack by malicious users
// that attempts to cancel random queries by spamming the request.
//
// See CancelQueryByKey() for details.
//
// The semaphore is initialized with a hard-coded limit of 256
// concurrent pgwire cancel requests (per node). We also add a
// 1-second penalty for failed cancellation requests in
// CancelQueryByKey, meaning that an attacker needs 1 second per
// guess. With an attacker randomly guessing a 32-bit secret, it
// would take 2^24 seconds to hit one query. If we suppose there are
// 256 concurrent queries actively running on a node, then it would
// take 2^16 seconds (18 hours) to hit any one of them.
cancelSemaphore *quotapool.IntPool
}
// systemStatusServer is an extension of the standard
// statusServer defined above with a few extra fields
// that support additional implementations of APIs that
// require system tenant access. This includes endpoints
// that require gossip, or information about nodes and
// stores.
// In general, add new RPC implementations to the base
// statusServer to ensure feature parity with system and
// app tenants.
type systemStatusServer struct {
*statusServer
gossip *gossip.Gossip
storePool *storepool.StorePool
stores *kvserver.Stores
nodeLiveness *liveness.NodeLiveness
spanConfigReporter spanconfig.Reporter
distSender *kvcoord.DistSender
rangeStatsFetcher *rangestats.Fetcher
node *Node
}
// StmtDiagnosticsRequester is the interface into *stmtdiagnostics.Registry
// used by AdminUI endpoints.
type StmtDiagnosticsRequester interface {
// InsertRequest adds an entry to system.statement_diagnostics_requests for
// tracing a query with the given fingerprint. Once this returns, calling
// stmtdiagnostics.ShouldCollectDiagnostics() on the current node will
// return true depending on the parameters below.
// - samplingProbability controls how likely we are to try and collect a
// diagnostics report for a given execution. The semantics with
// minExecutionLatency are as follows:
// - If samplingProbability is zero, we're always sampling. This is for
// compatibility with pre-22.2 versions where this parameter was not
// available.
// - If samplingProbability is non-zero, minExecutionLatency must be
// non-zero. We'll sample stmt executions with the given probability
// until:
// (a) we capture one that exceeds minExecutionLatency, or
// (b) we hit the expiresAfter point.
// - minExecutionLatency, if non-zero, determines the minimum execution
// latency of a query that satisfies the request. In other words, queries
// that ran faster than minExecutionLatency do not satisfy the condition
// and the bundle is not generated for them.
// - expiresAfter, if non-zero, indicates for how long the request should
// stay active.
InsertRequest(
ctx context.Context,
stmtFingerprint string,
samplingProbability float64,
minExecutionLatency time.Duration,
expiresAfter time.Duration,
) error
// CancelRequest updates an entry in system.statement_diagnostics_requests
// for tracing a query with the given fingerprint to be expired (thus,
// canceling any new tracing for it).
CancelRequest(ctx context.Context, requestID int64) error
}
// newStatusServer allocates and returns a statusServer.
func newStatusServer(
ambient log.AmbientContext,
st *cluster.Settings,
cfg *base.Config,
adminAuthzCheck *adminPrivilegeChecker,
db *kv.DB,
metricSource metricMarshaler,
rpcCtx *rpc.Context,
stopper *stop.Stopper,
sessionRegistry *sql.SessionRegistry,
closedSessionCache *sql.ClosedSessionCache,
remoteFlowRunner *flowinfra.RemoteFlowRunner,
internalExecutor *sql.InternalExecutor,
serverIterator ServerIterator,
clock *hlc.Clock,
) *statusServer {
ambient.AddLogTag("status", nil)
if !rpcCtx.TenantID.IsSystem() {
ambient.AddLogTag("tenant", rpcCtx.TenantID)
}
server := &statusServer{
baseStatusServer: &baseStatusServer{
AmbientContext: ambient,
privilegeChecker: adminAuthzCheck,
sessionRegistry: sessionRegistry,
closedSessionCache: closedSessionCache,
remoteFlowRunner: remoteFlowRunner,
st: st,
rpcCtx: rpcCtx,
stopper: stopper,
serverIterator: serverIterator,
clock: clock,
},
cfg: cfg,
db: db,
metricSource: metricSource,
internalExecutor: internalExecutor,
// See the docstring on cancelSemaphore for details about this initialization.
cancelSemaphore: quotapool.NewIntPool("pgwire-cancel", 256),
}
return server
}
// newSystemStatusServer allocates and returns a statusServer.
func newSystemStatusServer(
ambient log.AmbientContext,
st *cluster.Settings,
cfg *base.Config,
adminAuthzCheck *adminPrivilegeChecker,
db *kv.DB,
gossip *gossip.Gossip,
metricSource metricMarshaler,
nodeLiveness *liveness.NodeLiveness,
storePool *storepool.StorePool,
rpcCtx *rpc.Context,
stores *kvserver.Stores,
stopper *stop.Stopper,
sessionRegistry *sql.SessionRegistry,
closedSessionCache *sql.ClosedSessionCache,
remoteFlowRunner *flowinfra.RemoteFlowRunner,
internalExecutor *sql.InternalExecutor,
serverIterator ServerIterator,
spanConfigReporter spanconfig.Reporter,
clock *hlc.Clock,
distSender *kvcoord.DistSender,
rangeStatsFetcher *rangestats.Fetcher,
node *Node,
) *systemStatusServer {
server := newStatusServer(
ambient,
st,
cfg,
adminAuthzCheck,
db,
metricSource,
rpcCtx,
stopper,
sessionRegistry,
closedSessionCache,
remoteFlowRunner,
internalExecutor,
serverIterator,
clock,
)
return &systemStatusServer{
statusServer: server,
gossip: gossip,
storePool: storePool,
stores: stores,
nodeLiveness: nodeLiveness,
spanConfigReporter: spanConfigReporter,
distSender: distSender,
rangeStatsFetcher: rangeStatsFetcher,
node: node,
}
}
// setStmtDiagnosticsRequester is used to provide a StmtDiagnosticsRequester to
// the status server. This cannot be done at construction time because the
// implementation of StmtDiagnosticsRequester depends on an executor which in
// turn depends on the statusServer.
func (s *statusServer) setStmtDiagnosticsRequester(sr StmtDiagnosticsRequester) {
s.stmtDiagnosticsRequester = sr
}
// RegisterService registers the GRPC service.
func (s *statusServer) RegisterService(g *grpc.Server) {
serverpb.RegisterStatusServer(g, s)
}
// RegisterGateway starts the gateway (i.e. reverse
// proxy) that proxies HTTP requests to the appropriate gRPC endpoints.
func (s *statusServer) RegisterGateway(
ctx context.Context, mux *gwruntime.ServeMux, conn *grpc.ClientConn,
) error {
ctx = s.AnnotateCtx(ctx)
return serverpb.RegisterStatusHandler(ctx, mux, conn)
}
// RegisterService registers the GRPC service.
func (s *systemStatusServer) RegisterService(g *grpc.Server) {
serverpb.RegisterStatusServer(g, s)
}
func (s *statusServer) parseNodeID(nodeIDParam string) (roachpb.NodeID, bool, error) {
id, local, err := s.serverIterator.parseServerID(nodeIDParam)
return roachpb.NodeID(id), local, err
}
func (s *statusServer) dialNode(
ctx context.Context, nodeID roachpb.NodeID,
) (serverpb.StatusClient, error) {
conn, err := s.serverIterator.dialNode(ctx, serverID(nodeID))
if err != nil {
return nil, err
}
return serverpb.NewStatusClient(conn), nil
}
// Gossip returns gossip network status. It is implemented
// in the systemStatusServer since the system tenant has
// access to gossip.
func (s *systemStatusServer) Gossip(
ctx context.Context, req *serverpb.GossipRequest,
) (*gossip.InfoStatus, error) {
ctx = forwardSQLIdentityThroughRPCCalls(ctx)
ctx = s.AnnotateCtx(ctx)
if _, err := s.privilegeChecker.requireAdminUser(ctx); err != nil {
// NB: not using serverError() here since the priv checker
// already returns a proper gRPC error status.
return nil, err
}
nodeID, local, err := s.parseNodeID(req.NodeId)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, err.Error())
}
if local {
infoStatus := s.gossip.GetInfoStatus()
return &infoStatus, nil
}
status, err := s.dialNode(ctx, nodeID)
if err != nil {
return nil, serverError(ctx, err)
}
return status.Gossip(ctx, req)
}
func (s *systemStatusServer) EngineStats(
ctx context.Context, req *serverpb.EngineStatsRequest,
) (*serverpb.EngineStatsResponse, error) {
ctx = forwardSQLIdentityThroughRPCCalls(ctx)
ctx = s.AnnotateCtx(ctx)
if _, err := s.privilegeChecker.requireAdminUser(ctx); err != nil {
// NB: not using serverError() here since the priv checker
// already returns a proper gRPC error status.
return nil, err
}
nodeID, local, err := s.parseNodeID(req.NodeId)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, err.Error())
}
if !local {
status, err := s.dialNode(ctx, nodeID)
if err != nil {
return nil, serverError(ctx, err)
}
return status.EngineStats(ctx, req)
}
resp := new(serverpb.EngineStatsResponse)
err = s.stores.VisitStores(func(store *kvserver.Store) error {
engineStatsInfo := serverpb.EngineStatsInfo{
StoreID: store.Ident.StoreID,
TickersAndHistograms: nil,
EngineType: store.TODOEngine().Type(),
}
resp.Stats = append(resp.Stats, engineStatsInfo)
return nil
})
if err != nil {
return nil, serverError(ctx, err)
}
return resp, nil
}
// Allocator returns simulated allocator info for the ranges on the given node.
func (s *systemStatusServer) Allocator(
ctx context.Context, req *serverpb.AllocatorRequest,
) (*serverpb.AllocatorResponse, error) {
ctx = forwardSQLIdentityThroughRPCCalls(ctx)
ctx = s.AnnotateCtx(ctx)
if err := s.privilegeChecker.requireViewClusterMetadataPermission(ctx); err != nil {
// NB: not using serverError() here since the priv checker
// already returns a proper gRPC error status.
return nil, err
}
nodeID, local, err := s.parseNodeID(req.NodeId)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, err.Error())
}
if !local {
status, err := s.dialNode(ctx, nodeID)
if err != nil {
return nil, serverError(ctx, err)
}
return status.Allocator(ctx, req)
}
output := new(serverpb.AllocatorResponse)
err = s.stores.VisitStores(func(store *kvserver.Store) error {
// All ranges requested:
if len(req.RangeIDs) == 0 {
var err error
store.VisitReplicas(
func(rep *kvserver.Replica) bool {
if !rep.OwnsValidLease(ctx, store.Clock().NowAsClockTimestamp()) {
return true // continue.
}
var allocatorSpans tracingpb.Recording
allocatorSpans, err = store.ReplicateQueueDryRun(ctx, rep)
if err != nil {
return false // break and bubble up the error.
}
output.DryRuns = append(output.DryRuns, &serverpb.AllocatorDryRun{
RangeID: rep.RangeID,
Events: recordedSpansToTraceEvents(allocatorSpans),
})
return true // continue.
},
kvserver.WithReplicasInOrder(),
)
return err
}
// Specific ranges requested:
for _, rid := range req.RangeIDs {
rep, err := store.GetReplica(rid)
if err != nil {
// Not found: continue.
continue
}
if !rep.OwnsValidLease(ctx, store.Clock().NowAsClockTimestamp()) {
continue
}
allocatorSpans, err := store.ReplicateQueueDryRun(ctx, rep)
if err != nil {
return err
}
output.DryRuns = append(output.DryRuns, &serverpb.AllocatorDryRun{
RangeID: rep.RangeID,
Events: recordedSpansToTraceEvents(allocatorSpans),
})
}
return nil
})
if err != nil {
return nil, serverError(ctx, err)
}
return output, nil
}
func recordedSpansToTraceEvents(spans []tracingpb.RecordedSpan) []*serverpb.TraceEvent {
var output []*serverpb.TraceEvent
for _, sp := range spans {
for _, entry := range sp.Logs {
event := &serverpb.TraceEvent{
Time: entry.Time,
Message: entry.Msg().StripMarkers(),
}
output = append(output, event)
}
}
return output
}
// CriticalNodes retrieves nodes that are considered critical. A critical node
// is one whose unexpected termination could result in data loss. A node is
// considered critical if any of its replicas are unavailable or
// under-replicated. The response includes a list of node descriptors that are
// considered critical, and the corresponding SpanConfigConformanceReport that
// includes details of non-conforming ranges contributing to the criticality.
func (s *systemStatusServer) CriticalNodes(
ctx context.Context, req *serverpb.CriticalNodesRequest,
) (*serverpb.CriticalNodesResponse, error) {
ctx = s.AnnotateCtx(ctx)
if _, err := s.privilegeChecker.requireAdminUser(ctx); err != nil {
return nil, err
}
conformance, err := s.node.SpanConfigConformance(
ctx, &roachpb.SpanConfigConformanceRequest{
Spans: []roachpb.Span{keys.EverythingSpan},
})
if err != nil {
return nil, err
}
critical := make(map[roachpb.NodeID]bool)
for _, r := range conformance.Report.UnderReplicated {
for _, desc := range r.RangeDescriptor.Replicas().Descriptors() {
critical[desc.NodeID] = true
}
}
for _, r := range conformance.Report.Unavailable {
for _, desc := range r.RangeDescriptor.Replicas().Descriptors() {
critical[desc.NodeID] = true
}
}
res := &serverpb.CriticalNodesResponse{
CriticalNodes: nil,
Report: conformance.Report,
}
for nodeID := range critical {
ns, err := s.nodeStatus(ctx, &serverpb.NodeRequest{NodeId: nodeID.String()})
if err != nil {
return nil, err
}
res.CriticalNodes = append(res.CriticalNodes, ns.Desc)
}
return res, nil
}
// AllocatorRange returns simulated allocator info for the requested range.
func (s *systemStatusServer) AllocatorRange(
ctx context.Context, req *serverpb.AllocatorRangeRequest,
) (*serverpb.AllocatorRangeResponse, error) {
ctx = forwardSQLIdentityThroughRPCCalls(ctx)
ctx = s.AnnotateCtx(ctx)
err := s.privilegeChecker.requireViewClusterMetadataPermission(ctx)
if err != nil {
return nil, err
}
isLiveMap := s.nodeLiveness.GetIsLiveMap()
type nodeResponse struct {
nodeID roachpb.NodeID
resp *serverpb.AllocatorResponse
err error
}
responses := make(chan nodeResponse)
// TODO(bram): consider abstracting out this repeated pattern.
for nodeID := range isLiveMap {
nodeID := nodeID
if err := s.stopper.RunAsyncTask(
ctx,
"server.statusServer: requesting remote Allocator simulation",
func(ctx context.Context) {
_ = contextutil.RunWithTimeout(ctx, "allocator range", 3*time.Second, func(ctx context.Context) error {
status, err := s.dialNode(ctx, nodeID)
var allocatorResponse *serverpb.AllocatorResponse
if err == nil {
allocatorRequest := &serverpb.AllocatorRequest{
RangeIDs: []roachpb.RangeID{roachpb.RangeID(req.RangeId)},
}
allocatorResponse, err = status.Allocator(ctx, allocatorRequest)
}
response := nodeResponse{
nodeID: nodeID,
resp: allocatorResponse,
err: err,
}
select {
case responses <- response:
// Response processed.
case <-ctx.Done():
// Context completed, response no longer needed.
}
return nil
})
}); err != nil {
return nil, serverError(ctx, err)
}
}
errs := make(map[roachpb.NodeID]error)
for remainingResponses := len(isLiveMap); remainingResponses > 0; remainingResponses-- {
select {
case resp := <-responses:
if resp.err != nil {
errs[resp.nodeID] = resp.err
continue
}
if len(resp.resp.DryRuns) > 0 {
return &serverpb.AllocatorRangeResponse{
NodeID: resp.nodeID,
DryRun: resp.resp.DryRuns[0],
}, nil
}
case <-ctx.Done():
return nil, status.Errorf(codes.DeadlineExceeded, "request timed out")
}
}
// We didn't get a valid simulated Allocator run. Just return whatever errors
// we got instead. If we didn't even get any errors, then there is no active
// leaseholder for the range.
if len(errs) > 0 {
var buf bytes.Buffer
for nodeID, err := range errs {
if buf.Len() > 0 {
buf.WriteByte('\n')
}
fmt.Fprintf(&buf, "n%d: %s", nodeID, err)
}
return nil, serverErrorf(ctx, "%v", buf)
}
return &serverpb.AllocatorRangeResponse{}, nil
}
// Certificates returns the x509 certificates.