-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
combined_statement_stats.go
1785 lines (1589 loc) · 55.5 KB
/
combined_statement_stats.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 2021 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 (
"context"
"fmt"
"strconv"
"strings"
"time"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/server/authserver"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/server/srverrors"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/appstatspb"
"github.com/cockroachdb/cockroach/pkg/sql/isql"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catconstants"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlstats"
"github.com/cockroachdb/cockroach/pkg/sql/sqlstats/persistedsqlstats/sqlstatsutil"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
)
func getTimeFromSeconds(seconds int64) *time.Time {
if seconds != 0 {
t := timeutil.Unix(seconds, 0)
return &t
}
return nil
}
func closeIterator(it isql.Rows, err error) error {
if it != nil {
closeErr := it.Close()
if closeErr != nil {
err = errors.CombineErrors(err, closeErr)
}
}
return err
}
func (s *statusServer) CombinedStatementStats(
ctx context.Context, req *serverpb.CombinedStatementsStatsRequest,
) (*serverpb.StatementsResponse, error) {
ctx = authserver.ForwardSQLIdentityThroughRPCCalls(ctx)
ctx = s.AnnotateCtx(ctx)
if err := s.privilegeChecker.RequireViewActivityOrViewActivityRedactedPermission(ctx); err != nil {
return nil, err
}
return getCombinedStatementStats(
ctx,
req,
s.sqlServer.pgServer.SQLServer.GetSQLStatsProvider(),
s.internalExecutor,
s.st,
s.sqlServer.execCfg.SQLStatsTestingKnobs)
}
func getCombinedStatementStats(
ctx context.Context,
req *serverpb.CombinedStatementsStatsRequest,
statsProvider sqlstats.Provider,
ie *sql.InternalExecutor,
settings *cluster.Settings,
testingKnobs *sqlstats.TestingKnobs,
) (*serverpb.StatementsResponse, error) {
var err error
showInternal := SQLStatsShowInternal.Get(&settings.SV)
whereClause, orderAndLimit, args := getCombinedStatementsQueryClausesAndArgs(
req, testingKnobs, showInternal, settings)
// Used for mixed cluster version, where we need to use the persisted view with _v22_2.
tableSuffix := ""
if !settings.Version.IsActive(ctx, clusterversion.V23_1AddSQLStatsComputedIndexes) {
tableSuffix = "_v22_2"
}
// Check if the activity tables contains all the data required for the selected period from the request.
activityHasAllData := false
reqStartTime := getTimeFromSeconds(req.Start)
if settings.Version.IsActive(ctx, clusterversion.V23_1AddSystemActivityTables) {
sort := serverpb.StatsSortOptions_SERVICE_LAT
if req.FetchMode != nil {
sort = req.FetchMode.Sort
}
activityHasAllData, err = activityTablesHaveFullData(
ctx,
ie,
settings,
testingKnobs,
reqStartTime,
req.Limit,
sort,
)
if err != nil {
log.Errorf(ctx, "Error on activityTablesHaveFullData: %s", err)
}
}
var statements []serverpb.StatementsResponse_CollectedStatementStatistics
var transactions []serverpb.StatementsResponse_ExtendedCollectedTransactionStatistics
if req.FetchMode == nil || req.FetchMode.StatsType == serverpb.CombinedStatementsStatsRequest_TxnStatsOnly {
transactions, err = collectCombinedTransactions(
ctx,
ie,
whereClause,
args,
orderAndLimit,
testingKnobs,
activityHasAllData,
tableSuffix)
if err != nil {
return nil, srverrors.ServerError(ctx, err)
}
}
if req.FetchMode != nil && req.FetchMode.StatsType == serverpb.CombinedStatementsStatsRequest_TxnStatsOnly {
// If we're fetching for txns, the client still expects statement stats for
// stmts in the txns response.
statements, err = collectStmtsForTxns(
ctx,
ie,
req,
transactions,
testingKnobs,
activityHasAllData,
tableSuffix)
} else {
statements, err = collectCombinedStatements(
ctx,
ie,
whereClause,
args,
orderAndLimit,
testingKnobs,
activityHasAllData,
tableSuffix)
}
if err != nil {
return nil, srverrors.ServerError(ctx, err)
}
stmtsRunTime, txnsRunTime, oldestDate, stmtSourceTable, txnSourceTable, err := getSourceStatsInfo(
ctx,
req,
ie,
testingKnobs,
activityHasAllData,
tableSuffix,
showInternal)
if err != nil {
return nil, srverrors.ServerError(ctx, err)
}
response := &serverpb.StatementsResponse{
Statements: statements,
Transactions: transactions,
LastReset: statsProvider.GetLastReset(),
InternalAppNamePrefix: catconstants.InternalAppNamePrefix,
StmtsTotalRuntimeSecs: stmtsRunTime,
TxnsTotalRuntimeSecs: txnsRunTime,
OldestAggregatedTsReturned: oldestDate,
StmtsSourceTable: stmtSourceTable,
TxnsSourceTable: txnSourceTable,
}
return response, nil
}
func activityTablesHaveFullData(
ctx context.Context,
ie *sql.InternalExecutor,
settings *cluster.Settings,
testingKnobs *sqlstats.TestingKnobs,
reqStartTime *time.Time,
limit int64,
order serverpb.StatsSortOptions,
) (result bool, err error) {
if !StatsActivityUIEnabled.Get(&settings.SV) {
return false, nil
}
if (limit > 0 && !isLimitOnActivityTable(limit)) || !isSortOptionOnActivityTable(order) {
return false, nil
}
if reqStartTime == nil {
return false, nil
}
// Used to verify the table contained data.
zeroDate := time.Time{}
const queryWithPlaceholders = `
SELECT
COALESCE(min(aggregated_ts), '%s')
FROM crdb_internal.statement_activity
%s
`
// Format string "2006-01-02 15:04:05.00" is a golang-specific string
it, err := ie.QueryIteratorEx(
ctx,
"console-combined-stmts-activity-min-ts",
nil,
sessiondata.NodeUserSessionDataOverride,
fmt.Sprintf(queryWithPlaceholders, zeroDate.Format("2006-01-02 15:04:05.00"), testingKnobs.GetAOSTClause()))
if err != nil {
return false, err
}
ok, err := it.Next(ctx)
if err != nil {
return false, err
}
if !ok {
return false, errors.New("expected one row but got none on activityTablesHaveFullData")
}
var row tree.Datums
if row = it.Cur(); row == nil {
return false, errors.New("unexpected null row on activityTablesHaveFullData")
}
defer func() {
err = closeIterator(it, err)
}()
minAggregatedTs := tree.MustBeDTimestampTZ(row[0]).Time
hasData := !minAggregatedTs.IsZero() && (reqStartTime.After(minAggregatedTs) || reqStartTime.Equal(minAggregatedTs))
return hasData, nil
}
// getSourceStatsInfo returns information about the stats returned:
// - the total runtime (in seconds) on the selected period for
// statement and transactions
// - the oldest aggregated_ts we have data for on the
// selected period
// - which table the data was retrieve from
func getSourceStatsInfo(
ctx context.Context,
req *serverpb.CombinedStatementsStatsRequest,
ie *sql.InternalExecutor,
testingKnobs *sqlstats.TestingKnobs,
activityTableHasAllData bool,
tableSuffix string,
showInternal bool,
) (
stmtsRuntime float32,
txnsRuntime float32,
oldestDate *time.Time,
stmtSourceTable string,
txnSourceTable string,
err error,
) {
var buffer strings.Builder
buffer.WriteString(testingKnobs.GetAOSTClause())
var args []interface{}
startTime := getTimeFromSeconds(req.Start)
endTime := getTimeFromSeconds(req.End)
buffer.WriteString(" WHERE true")
if startTime != nil {
args = append(args, *startTime)
buffer.WriteString(fmt.Sprintf(" AND aggregated_ts >= $%d", len(args)))
}
if endTime != nil {
args = append(args, *endTime)
buffer.WriteString(fmt.Sprintf(" AND aggregated_ts <= $%d", len(args)))
}
whereClause := buffer.String()
if !showInternal {
// Filter out internal statements by app name.
buffer.WriteString(fmt.Sprintf(
" AND app_name NOT LIKE '%s%%' AND app_name NOT LIKE '%s%%'",
catconstants.InternalAppNamePrefix,
catconstants.DelegatedAppNamePrefix))
}
whereClauseOldestDate := buffer.String()
getRuntime := func(table string) (float32, error) {
it, err := ie.QueryIteratorEx(
ctx,
fmt.Sprintf(`console-combined-stmts-%s-total-runtime`, table),
nil,
sessiondata.NodeUserSessionDataOverride,
fmt.Sprintf(`
SELECT COALESCE(
sum(
(statistics -> 'statistics' -> 'svcLat' ->> 'mean')::FLOAT *
(statistics -> 'statistics' ->> 'cnt')::FLOAT
),
0)
FROM %s %s`, table, whereClause), args...)
if err != nil {
return 0, err
}
ok, err := it.Next(ctx)
if err != nil {
return 0, err
}
if !ok {
return 0, errors.New("expected one row but got none on getSourceStatsInfo.getRuntime")
}
var row tree.Datums
if row = it.Cur(); row == nil {
return 0, errors.New("unexpected null row on getSourceStatsInfo.getRuntime")
}
defer func() {
err = closeIterator(it, err)
}()
return float32(tree.MustBeDFloat(row[0])), nil
}
getOldestDate := func(table string) (*time.Time, error) {
it, err := ie.QueryIteratorEx(
ctx,
fmt.Sprintf(`console-combined-stmts-%s-oldest_date`, table),
nil,
sessiondata.NodeUserSessionDataOverride,
fmt.Sprintf(`
SELECT min(aggregated_ts)
FROM %s %s`, table, whereClauseOldestDate), args...)
if err != nil {
return nil, err
}
ok, err := it.Next(ctx)
if err != nil {
return nil, err
}
if !ok {
return nil, errors.New("expected one row but got none on getSourceStatsInfo.getOldestDate")
}
var row tree.Datums
if row = it.Cur(); row == nil {
return nil, nil
}
defer func() {
err = closeIterator(it, err)
}()
if row[0] == tree.DNull {
return nil, nil
}
oldestTs := tree.MustBeDTimestampTZ(row[0]).Time
return &oldestTs, nil
}
// We return statement info for both req modes (statements only and transactions only),
// since statements are also returned for transactions only mode.
stmtsRuntime = 0
if activityTableHasAllData {
stmtSourceTable = "crdb_internal.statement_activity"
stmtsRuntime, err = getRuntime(stmtSourceTable)
if err != nil {
return 0, 0, nil, stmtSourceTable, "", err
}
oldestDate, err = getOldestDate(stmtSourceTable)
if err != nil {
return stmtsRuntime, 0, nil, stmtSourceTable, "", err
}
}
// If there are no results from the activity table, retrieve the data from the persisted table.
if stmtsRuntime == 0 {
stmtSourceTable = "crdb_internal.statement_statistics_persisted" + tableSuffix
stmtsRuntime, err = getRuntime(stmtSourceTable)
if err != nil {
return 0, 0, nil, stmtSourceTable, "", err
}
oldestDate, err = getOldestDate(stmtSourceTable)
if err != nil {
return stmtsRuntime, 0, nil, stmtSourceTable, "", err
}
}
// If there are no results from the persisted table, retrieve the data from the combined view
// with data in-memory.
if stmtsRuntime == 0 {
stmtSourceTable = "crdb_internal.statement_statistics"
stmtsRuntime, err = getRuntime(stmtSourceTable)
if err != nil {
return 0, 0, nil, stmtSourceTable, "", err
}
oldestDate, err = getOldestDate(stmtSourceTable)
if err != nil {
return stmtsRuntime, 0, nil, stmtSourceTable, "", err
}
}
txnsRuntime = 0
if req.FetchMode == nil || req.FetchMode.StatsType != serverpb.CombinedStatementsStatsRequest_StmtStatsOnly {
if activityTableHasAllData {
txnSourceTable = "crdb_internal.transaction_activity"
txnsRuntime, err = getRuntime(txnSourceTable)
if err != nil {
return 0, 0, nil, stmtSourceTable, txnSourceTable, err
}
}
// If there are no results from the activity table, retrieve the data from the persisted table.
if txnsRuntime == 0 {
txnSourceTable = "crdb_internal.transaction_statistics_persisted" + tableSuffix
txnsRuntime, err = getRuntime(txnSourceTable)
if err != nil {
return 0, 0, nil, stmtSourceTable, txnSourceTable, err
}
}
// If there are no results from the persisted table, retrieve the data from the combined view
// with data in-memory.
if txnsRuntime == 0 {
txnSourceTable = "crdb_internal.transaction_statistics"
txnsRuntime, err = getRuntime(txnSourceTable)
if err != nil {
return 0, 0, nil, stmtSourceTable, txnSourceTable, err
}
}
}
return stmtsRuntime, txnsRuntime, oldestDate, stmtSourceTable, txnSourceTable, err
}
// Return true is the limit request is within the limit
// on the Activity tables (500)
func isLimitOnActivityTable(limit int64) bool {
return limit <= 500
}
func isSortOptionOnActivityTable(sort serverpb.StatsSortOptions) bool {
switch sort {
case serverpb.StatsSortOptions_SERVICE_LAT,
serverpb.StatsSortOptions_CPU_TIME,
serverpb.StatsSortOptions_EXECUTION_COUNT,
serverpb.StatsSortOptions_P99_STMTS_ONLY,
serverpb.StatsSortOptions_CONTENTION_TIME,
serverpb.StatsSortOptions_PCT_RUNTIME:
return true
}
return false
}
const (
sortSvcLatDesc = `(statistics -> 'statistics' -> 'svcLat' ->> 'mean')::FLOAT DESC`
sortCPUTimeDesc = `(statistics -> 'execution_statistics' -> 'cpuSQLNanos' ->> 'mean')::FLOAT DESC`
sortExecCountDesc = `(statistics -> 'statistics' ->> 'cnt')::INT DESC`
sortContentionTimeDesc = `(statistics -> 'execution_statistics' -> 'contentionTime' ->> 'mean')::FLOAT DESC`
sortPCTRuntimeDesc = `((statistics -> 'statistics' -> 'svcLat' ->> 'mean')::FLOAT *
(statistics -> 'statistics' ->> 'cnt')::FLOAT) DESC`
sortLatencyInfoP50Desc = `(statistics -> 'statistics' -> 'latencyInfo' ->> 'p50')::FLOAT DESC`
sortLatencyInfoP90Desc = `(statistics -> 'statistics' -> 'latencyInfo' ->> 'p90')::FLOAT DESC`
sortLatencyInfoP99Desc = `(statistics -> 'statistics' -> 'latencyInfo' ->> 'p99')::FLOAT DESC`
sortLatencyInfoMinDesc = `(statistics -> 'statistics' -> 'latencyInfo' ->> 'min')::FLOAT DESC`
sortLatencyInfoMaxDesc = `(statistics -> 'statistics' -> 'latencyInfo' ->> 'max')::FLOAT DESC`
sortRowsProcessedDesc = `((statistics -> 'statistics' -> 'rowsRead' ->> 'mean')::FLOAT +
(statistics -> 'statistics' -> 'rowsWritten' ->> 'mean')::FLOAT) DESC`
sortMaxMemoryDesc = `(statistics -> 'execution_statistics' -> 'maxMemUsage' ->> 'mean')::FLOAT DESC`
sortNetworkDesc = `(statistics -> 'execution_statistics' -> 'networkBytes' ->> 'mean')::FLOAT DESC`
sortRetriesDesc = `(statistics -> 'statistics' ->> 'maxRetries')::INT DESC`
sortLastExecDesc = `(statistics -> 'statistics' ->> 'lastExecAt') DESC`
)
func getStmtColumnFromSortOption(sort serverpb.StatsSortOptions) string {
switch sort {
case serverpb.StatsSortOptions_SERVICE_LAT:
return sortSvcLatDesc
case serverpb.StatsSortOptions_CPU_TIME:
return sortCPUTimeDesc
case serverpb.StatsSortOptions_EXECUTION_COUNT:
return sortExecCountDesc
case serverpb.StatsSortOptions_P99_STMTS_ONLY:
return sortLatencyInfoP99Desc
case serverpb.StatsSortOptions_CONTENTION_TIME:
return sortContentionTimeDesc
case serverpb.StatsSortOptions_LATENCY_INFO_P50:
return sortLatencyInfoP50Desc
case serverpb.StatsSortOptions_LATENCY_INFO_P90:
return sortLatencyInfoP90Desc
case serverpb.StatsSortOptions_LATENCY_INFO_MIN:
return sortLatencyInfoMinDesc
case serverpb.StatsSortOptions_LATENCY_INFO_MAX:
return sortLatencyInfoMaxDesc
case serverpb.StatsSortOptions_ROWS_PROCESSED:
return sortRowsProcessedDesc
case serverpb.StatsSortOptions_MAX_MEMORY:
return sortMaxMemoryDesc
case serverpb.StatsSortOptions_NETWORK:
return sortNetworkDesc
case serverpb.StatsSortOptions_RETRIES:
return sortRetriesDesc
case serverpb.StatsSortOptions_LAST_EXEC:
return sortLastExecDesc
default:
return sortSvcLatDesc
}
}
func getTxnColumnFromSortOption(sort serverpb.StatsSortOptions) string {
switch sort {
case serverpb.StatsSortOptions_SERVICE_LAT:
return sortSvcLatDesc
case serverpb.StatsSortOptions_CPU_TIME:
return sortCPUTimeDesc
case serverpb.StatsSortOptions_EXECUTION_COUNT:
return sortExecCountDesc
case serverpb.StatsSortOptions_CONTENTION_TIME:
return sortContentionTimeDesc
case serverpb.StatsSortOptions_PCT_RUNTIME:
return sortPCTRuntimeDesc
default:
return sortSvcLatDesc
}
}
// buildWhereClauseForStmtsByTxn builds the where clause to get the statement
// stats based on a list of transactions. The list of transactions provided must
// contain no duplicate transaction fingerprint ids.
func buildWhereClauseForStmtsByTxn(
req *serverpb.CombinedStatementsStatsRequest,
transactions []serverpb.StatementsResponse_ExtendedCollectedTransactionStatistics,
testingKnobs *sqlstats.TestingKnobs,
) (whereClause string, args []interface{}) {
var buffer strings.Builder
buffer.WriteString(testingKnobs.GetAOSTClause())
buffer.WriteString(" WHERE true")
// Add start and end filters from request.
startTime := getTimeFromSeconds(req.Start)
endTime := getTimeFromSeconds(req.End)
if startTime != nil {
args = append(args, *startTime)
buffer.WriteString(fmt.Sprintf(" AND aggregated_ts >= $%d", len(args)))
}
if endTime != nil {
args = append(args, *endTime)
buffer.WriteString(fmt.Sprintf(" AND aggregated_ts <= $%d", len(args)))
}
txnFingerprints := make([]string, 0, len(transactions))
for i := range transactions {
fingerprint := uint64(transactions[i].StatsData.TransactionFingerprintID)
txnFingerprints = append(txnFingerprints, fmt.Sprintf("\\x%016x", fingerprint))
}
args = append(args, txnFingerprints)
buffer.WriteString(fmt.Sprintf(" AND transaction_fingerprint_id = any $%d", len(args)))
return buffer.String(), args
}
// getCombinedStatementsQueryClausesAndArgs returns:
// - where clause (filtering by name and aggregates_ts when defined)
// - order and limit clause
// - args that will replace the clauses above
// The whereClause will be in the format `WHERE A = $1 AND B = $2` and
// args will return the list of arguments in order that will replace the actual values.
func getCombinedStatementsQueryClausesAndArgs(
req *serverpb.CombinedStatementsStatsRequest,
testingKnobs *sqlstats.TestingKnobs,
showInternal bool,
settings *cluster.Settings,
) (whereClause string, orderAndLimitClause string, args []interface{}) {
var buffer strings.Builder
buffer.WriteString(testingKnobs.GetAOSTClause())
if showInternal {
buffer.WriteString(" WHERE true")
} else {
// Filter out internal statements by app name.
buffer.WriteString(fmt.Sprintf(
" WHERE app_name NOT LIKE '%s%%' AND app_name NOT LIKE '%s%%'",
catconstants.InternalAppNamePrefix,
catconstants.DelegatedAppNamePrefix))
}
// Add start and end filters from request.
startTime := getTimeFromSeconds(req.Start)
endTime := getTimeFromSeconds(req.End)
if startTime != nil {
buffer.WriteString(" AND aggregated_ts >= $1")
args = append(args, *startTime)
}
if endTime != nil {
args = append(args, *endTime)
buffer.WriteString(fmt.Sprintf(" AND aggregated_ts <= $%d", len(args)))
}
// Add LIMIT from request.
limit := req.Limit
if limit == 0 {
limit = SQLStatsResponseMax.Get(&settings.SV)
}
args = append(args, limit)
// Determine sort column.
var col string
if req.FetchMode == nil {
col = "fingerprint_id"
} else if req.FetchMode.StatsType == serverpb.CombinedStatementsStatsRequest_StmtStatsOnly {
col = getStmtColumnFromSortOption(req.FetchMode.Sort)
} else if req.FetchMode.StatsType == serverpb.CombinedStatementsStatsRequest_TxnStatsOnly {
col = getTxnColumnFromSortOption(req.FetchMode.Sort)
}
orderAndLimitClause = fmt.Sprintf(` ORDER BY %s LIMIT $%d`, col, len(args))
return buffer.String(), orderAndLimitClause, args
}
func collectCombinedStatements(
ctx context.Context,
ie *sql.InternalExecutor,
whereClause string,
args []interface{},
orderAndLimit string,
testingKnobs *sqlstats.TestingKnobs,
activityTableHasAllData bool,
tableSuffix string,
) ([]serverpb.StatementsResponse_CollectedStatementStatistics, error) {
aostClause := testingKnobs.GetAOSTClause()
const expectedNumDatums = 11
const queryFormat = `
SELECT
fingerprint_id,
txn_fingerprints,
app_name,
aggregated_ts,
COALESCE(CAST(metadata -> 'distSQLCount' AS INT), 0) AS distSQLCount,
COALESCE(CAST(metadata -> 'fullScanCount' AS INT), 0) AS fullScanCount,
COALESCE(CAST(metadata -> 'failedCount' AS INT), 0) AS failedCount,
metadata ->> 'query' AS query,
metadata ->> 'querySummary' AS querySummary,
metadata ->> 'db' AS databases,
statistics
FROM (SELECT fingerprint_id,
array_agg(distinct transaction_fingerprint_id) AS txn_fingerprints,
app_name,
max(aggregated_ts) AS aggregated_ts,
crdb_internal.merge_stats_metadata(array_agg(metadata)) AS metadata,
crdb_internal.merge_statement_stats(array_agg(statistics)) AS statistics
FROM %s %s
GROUP BY
fingerprint_id,
app_name) %s
%s`
var it isql.Rows
var err error
defer func() {
err = closeIterator(it, err)
}()
if activityTableHasAllData {
it, err = getIterator(
ctx,
ie,
// The statement activity table has aggregated metadata.
`
SELECT
fingerprint_id,
txn_fingerprints,
app_name,
aggregated_ts,
COALESCE(CAST(metadata -> 'distSQLCount' AS INT), 0) AS distSQLCount,
COALESCE(CAST(metadata -> 'fullScanCount' AS INT), 0) AS fullScanCount,
COALESCE(CAST(metadata -> 'failedCount' AS INT), 0) AS failedCount,
metadata ->> 'query' AS query,
metadata ->> 'querySummary' AS querySummary,
metadata ->> 'db' AS databases,
statistics
FROM (SELECT fingerprint_id,
array_agg(distinct transaction_fingerprint_id) AS txn_fingerprints,
app_name,
max(aggregated_ts) AS aggregated_ts,
crdb_internal.merge_aggregated_stmt_metadata(array_agg(metadata)) AS metadata,
crdb_internal.merge_statement_stats(array_agg(statistics)) AS statistics
FROM %s %s
GROUP BY
fingerprint_id,
app_name) %s
%s`,
"crdb_internal.statement_activity",
"combined-stmts-activity-by-interval",
whereClause,
args,
aostClause,
orderAndLimit)
if err != nil {
return nil, srverrors.ServerError(ctx, err)
}
}
// If there are no results from the activity table, retrieve the data from the persisted table.
if it == nil || !it.HasResults() {
if it != nil {
err = closeIterator(it, err)
}
it, err = getIterator(
ctx,
ie,
queryFormat,
"crdb_internal.statement_statistics_persisted"+tableSuffix,
"combined-stmts-persisted-by-interval",
whereClause,
args,
aostClause,
orderAndLimit)
if err != nil {
return nil, srverrors.ServerError(ctx, err)
}
}
// If there are no results from the persisted table, retrieve the data from the combined view
// with data in-memory.
if !it.HasResults() {
err = closeIterator(it, err)
it, err = getIterator(
ctx,
ie,
queryFormat,
"crdb_internal.statement_statistics",
"combined-stmts-with-memory-by-interval",
whereClause,
args,
aostClause,
orderAndLimit)
if err != nil {
return nil, srverrors.ServerError(ctx, err)
}
}
var statements []serverpb.StatementsResponse_CollectedStatementStatistics
var ok bool
for ok, err = it.Next(ctx); ok; ok, err = it.Next(ctx) {
var row tree.Datums
if row = it.Cur(); row == nil {
return nil, errors.New("unexpected null row on collectCombinedStatements")
}
if row.Len() != expectedNumDatums {
return nil, errors.Newf("expected %d columns on collectCombinedStatements, received %d", expectedNumDatums)
}
var statementFingerprintID uint64
if statementFingerprintID, err = sqlstatsutil.DatumToUint64(row[0]); err != nil {
return nil, srverrors.ServerError(ctx, err)
}
var txnFingerprintID uint64
txnFingerprintDatums := tree.MustBeDArray(row[1])
txnFingerprintIDs := make([]appstatspb.TransactionFingerprintID, 0, txnFingerprintDatums.Array.Len())
for _, idDatum := range txnFingerprintDatums.Array {
if txnFingerprintID, err = sqlstatsutil.DatumToUint64(idDatum); err != nil {
return nil, srverrors.ServerError(ctx, err)
}
txnFingerprintIDs = append(txnFingerprintIDs, appstatspb.TransactionFingerprintID(txnFingerprintID))
}
app := string(tree.MustBeDString(row[2]))
aggregatedTs := tree.MustBeDTimestampTZ(row[3]).Time
distSQLCount := int64(*row[4].(*tree.DInt))
fullScanCount := int64(*row[5].(*tree.DInt))
failedCount := int64(*row[6].(*tree.DInt))
query := string(tree.MustBeDString(row[7]))
querySummary := string(tree.MustBeDString(row[8]))
databases := string(tree.MustBeDString(row[9]))
metadata := appstatspb.CollectedStatementStatistics{
Key: appstatspb.StatementStatisticsKey{
App: app,
DistSQL: distSQLCount > 0,
FullScan: fullScanCount > 0,
Failed: failedCount > 0,
Query: query,
QuerySummary: querySummary,
Database: databases,
},
}
var stats appstatspb.StatementStatistics
statsJSON := tree.MustBeDJSON(row[10]).JSON
if err = sqlstatsutil.DecodeStmtStatsStatisticsJSON(statsJSON, &stats); err != nil {
return nil, srverrors.ServerError(ctx, err)
}
stmt := serverpb.StatementsResponse_CollectedStatementStatistics{
Key: serverpb.StatementsResponse_ExtendedStatementStatisticsKey{
KeyData: metadata.Key,
AggregatedTs: aggregatedTs,
},
ID: appstatspb.StmtFingerprintID(statementFingerprintID),
Stats: stats,
TxnFingerprintIDs: txnFingerprintIDs,
}
statements = append(statements, stmt)
}
if err != nil {
return nil, srverrors.ServerError(ctx, err)
}
return statements, nil
}
func getIterator(
ctx context.Context,
ie *sql.InternalExecutor,
queryFormat string,
table string,
queryInfo string,
whereClause string,
args []interface{},
aostClause string,
orderAndLimit string,
) (isql.Rows, error) {
query := fmt.Sprintf(
queryFormat,
table,
whereClause,
aostClause,
orderAndLimit)
opName := fmt.Sprintf(`console-combined-stmts-%s`, queryInfo)
it, err := ie.QueryIteratorEx(ctx, opName, nil,
sessiondata.NodeUserSessionDataOverride, query, args...)
if err != nil {
return it, srverrors.ServerError(ctx, err)
}
return it, nil
}
func collectCombinedTransactions(
ctx context.Context,
ie *sql.InternalExecutor,
whereClause string,
args []interface{},
orderAndLimit string,
testingKnobs *sqlstats.TestingKnobs,
activityTableHasAllData bool,
tableSuffix string,
) ([]serverpb.StatementsResponse_ExtendedCollectedTransactionStatistics, error) {
aostClause := testingKnobs.GetAOSTClause()
const expectedNumDatums = 5
const queryFormat = `
SELECT *
FROM (SELECT app_name,
max(aggregated_ts) AS aggregated_ts,
fingerprint_id,
max(metadata),
crdb_internal.merge_transaction_stats(array_agg(statistics)) AS statistics
FROM %s %s
GROUP BY
app_name,
fingerprint_id) %s
%s`
var it isql.Rows
var err error
if activityTableHasAllData {
it, err = getIterator(
ctx,
ie,
queryFormat,
"crdb_internal.transaction_activity",
"combined-txns-activity-by-interval",
whereClause,
args,
aostClause,
orderAndLimit)
if err != nil {
return nil, srverrors.ServerError(ctx, err)
}
}
defer func() {
err = closeIterator(it, err)
}()
// If there are no results from the activity table, retrieve the data from the persisted table.
if it == nil || !it.HasResults() {
if it != nil {
err = closeIterator(it, err)
}
it, err = getIterator(
ctx,
ie,
queryFormat,
"crdb_internal.transaction_statistics_persisted"+tableSuffix,
"combined-txns-persisted-by-interval",
whereClause,
args,
aostClause,
orderAndLimit)
if err != nil {
return nil, srverrors.ServerError(ctx, err)
}
}
// If there are no results from the persisted table, retrieve the data from the combined view
// with data in-memory.
if !it.HasResults() {
err = closeIterator(it, err)
it, err = getIterator(
ctx,
ie,
queryFormat,
"crdb_internal.transaction_statistics",
"combined-txns-with-memory-by-interval",
whereClause,
args,
aostClause,
orderAndLimit)
if err != nil {
return nil, srverrors.ServerError(ctx, err)
}
}
var transactions []serverpb.StatementsResponse_ExtendedCollectedTransactionStatistics
var ok bool
for ok, err = it.Next(ctx); ok; ok, err = it.Next(ctx) {
var row tree.Datums
if row = it.Cur(); row == nil {
return nil, errors.New("unexpected null row on collectCombinedTransactions")
}
if row.Len() != expectedNumDatums {
return nil, errors.Newf("expected %d columns on collectCombinedTransactions, received %d", expectedNumDatums, row.Len())
}
app := string(tree.MustBeDString(row[0]))
aggregatedTs := tree.MustBeDTimestampTZ(row[1]).Time
fingerprintID, err := sqlstatsutil.DatumToUint64(row[2])
if err != nil {
return nil, srverrors.ServerError(ctx, err)
}
var metadata appstatspb.CollectedTransactionStatistics
metadataJSON := tree.MustBeDJSON(row[3]).JSON
if err = sqlstatsutil.DecodeTxnStatsMetadataJSON(metadataJSON, &metadata); err != nil {
return nil, srverrors.ServerError(ctx, err)
}
statsJSON := tree.MustBeDJSON(row[4]).JSON
if err = sqlstatsutil.DecodeTxnStatsStatisticsJSON(statsJSON, &metadata.Stats); err != nil {
return nil, srverrors.ServerError(ctx, err)
}
txnStats := serverpb.StatementsResponse_ExtendedCollectedTransactionStatistics{
StatsData: appstatspb.CollectedTransactionStatistics{
StatementFingerprintIDs: metadata.StatementFingerprintIDs,
App: app,
Stats: metadata.Stats,
AggregatedTs: aggregatedTs,
TransactionFingerprintID: appstatspb.TransactionFingerprintID(fingerprintID),
},
}
transactions = append(transactions, txnStats)
}
if err != nil {
return nil, srverrors.ServerError(ctx, err)
}
return transactions, nil