-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
sql_stats_test.go
1116 lines (985 loc) · 40.3 KB
/
sql_stats_test.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 2023 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 application_api_test
import (
"context"
gosql "database/sql"
"fmt"
"net/url"
"reflect"
"sort"
"strings"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/server/apiconstants"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/server/srvtestutils"
"github.com/cockroachdb/cockroach/pkg/spanconfig"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/appstatspb"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catconstants"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlstats"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/skip"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/kr/pretty"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestStatusAPICombinedTransactions(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// Increase the timeout for the http client if under stress.
additionalTimeout := 0 * time.Second
if skip.Stress() {
additionalTimeout = 20 * time.Second
}
var params base.TestServerArgs
params.Knobs.SpanConfig = &spanconfig.TestingKnobs{ManagerDisableJobCreation: true} // TODO(irfansharif): #74919.
testCluster := serverutils.StartCluster(t, 3, base.TestClusterArgs{
ServerArgs: params,
})
ctx := context.Background()
defer testCluster.Stopper().Stop(ctx)
thirdServer := testCluster.Server(2)
pgURL, cleanupGoDB := sqlutils.PGUrl(
t, thirdServer.AdvSQLAddr(), "CreateConnections" /* prefix */, url.User(username.RootUser))
defer cleanupGoDB()
firstServerProto := testCluster.Server(0)
type testCase struct {
query string
fingerprinted string
count int
shouldRetry bool
numRows int
}
testCases := []testCase{
{query: `CREATE DATABASE roachblog`, count: 1, numRows: 0},
{query: `SET database = roachblog`, count: 1, numRows: 0},
{query: `CREATE TABLE posts (id INT8 PRIMARY KEY, body STRING)`, count: 1, numRows: 0},
{
query: `INSERT INTO posts VALUES (1, 'foo')`,
fingerprinted: `INSERT INTO posts VALUES (_, '_')`,
count: 1,
numRows: 1,
},
{query: `SELECT * FROM posts`, count: 2, numRows: 1},
{query: `BEGIN; SELECT * FROM posts; SELECT * FROM posts; COMMIT`, count: 3, numRows: 2},
{
query: `BEGIN; SELECT crdb_internal.force_retry('2s'); SELECT * FROM posts; COMMIT;`,
fingerprinted: `BEGIN; SELECT crdb_internal.force_retry(_); SELECT * FROM posts; COMMIT;`,
shouldRetry: true,
count: 1,
numRows: 2,
},
{
query: `BEGIN; SELECT crdb_internal.force_retry('5s'); SELECT * FROM posts; COMMIT;`,
fingerprinted: `BEGIN; SELECT crdb_internal.force_retry(_); SELECT * FROM posts; COMMIT;`,
shouldRetry: true,
count: 1,
numRows: 2,
},
}
appNameToTestCase := make(map[string]testCase)
for i, tc := range testCases {
appName := fmt.Sprintf("app%d", i)
appNameToTestCase[appName] = tc
// Create a brand new connection for each app, so that we don't pollute
// transaction stats collection with `SET application_name` queries.
sqlDB, err := gosql.Open("postgres", pgURL.String())
if err != nil {
t.Fatal(err)
}
if _, err := sqlDB.Exec(fmt.Sprintf(`SET application_name = "%s"`, appName)); err != nil {
t.Fatal(err)
}
for c := 0; c < tc.count; c++ {
if _, err := sqlDB.Exec(tc.query); err != nil {
t.Fatal(err)
}
}
if err := sqlDB.Close(); err != nil {
t.Fatal(err)
}
}
// Hit query endpoint.
var resp serverpb.StatementsResponse
if err := srvtestutils.GetStatusJSONProtoWithAdminAndTimeoutOption(firstServerProto, "combinedstmts", &resp, true, additionalTimeout); err != nil {
t.Fatal(err)
}
// Construct a map of all the statement fingerprint IDs.
statementFingerprintIDs := make(map[appstatspb.StmtFingerprintID]bool, len(resp.Statements))
for _, respStatement := range resp.Statements {
statementFingerprintIDs[respStatement.ID] = true
}
respAppNames := make(map[string]bool)
for _, respTransaction := range resp.Transactions {
appName := respTransaction.StatsData.App
tc, found := appNameToTestCase[appName]
if !found {
// Ignore internal queries, they aren't relevant to this test.
continue
}
respAppNames[appName] = true
// Ensure all statementFingerprintIDs comprised by the Transaction Response can be
// linked to StatementFingerprintIDs for statements in the response.
for _, stmtFingerprintID := range respTransaction.StatsData.StatementFingerprintIDs {
if _, found := statementFingerprintIDs[stmtFingerprintID]; !found {
t.Fatalf("app: %s, expected stmtFingerprintID: %d not found in StatementResponse.", appName, stmtFingerprintID)
}
}
stats := respTransaction.StatsData.Stats
if tc.count != int(stats.Count) {
t.Fatalf("app: %s, expected count %d, got %d", appName, tc.count, stats.Count)
}
if tc.shouldRetry && respTransaction.StatsData.Stats.MaxRetries == 0 {
t.Fatalf("app: %s, expected retries, got none\n", appName)
}
// Sanity check numeric stat values
if respTransaction.StatsData.Stats.CommitLat.Mean <= 0 {
t.Fatalf("app: %s, unexpected mean for commit latency\n", appName)
}
if respTransaction.StatsData.Stats.RetryLat.Mean <= 0 && tc.shouldRetry {
t.Fatalf("app: %s, expected retry latency mean to be non-zero as retries were involved\n", appName)
}
if respTransaction.StatsData.Stats.ServiceLat.Mean <= 0 {
t.Fatalf("app: %s, unexpected mean for service latency\n", appName)
}
if respTransaction.StatsData.Stats.NumRows.Mean != float64(tc.numRows) {
t.Fatalf("app: %s, unexpected number of rows observed. expected: %d, got %d\n",
appName, tc.numRows, int(respTransaction.StatsData.Stats.NumRows.Mean))
}
}
// Ensure we got transaction statistics for all the queries we sent.
for appName := range appNameToTestCase {
if _, found := respAppNames[appName]; !found {
t.Fatalf("app: %s did not appear in the response\n", appName)
}
}
}
func TestStatusAPITransactions(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// Increase the timeout for the http client if under stress.
additionalTimeout := 0 * time.Second
if skip.Stress() {
additionalTimeout = 20 * time.Second
}
testCluster := serverutils.StartCluster(t, 3, base.TestClusterArgs{})
ctx := context.Background()
defer testCluster.Stopper().Stop(ctx)
thirdServer := testCluster.Server(2)
pgURL, cleanupGoDB := sqlutils.PGUrl(
t, thirdServer.AdvSQLAddr(), "CreateConnections" /* prefix */, url.User(username.RootUser))
defer cleanupGoDB()
firstServerProto := testCluster.Server(0)
type testCase struct {
query string
fingerprinted string
count int
shouldRetry bool
numRows int
}
testCases := []testCase{
{query: `CREATE DATABASE roachblog`, count: 1, numRows: 0},
{query: `SET database = roachblog`, count: 1, numRows: 0},
{query: `CREATE TABLE posts (id INT8 PRIMARY KEY, body STRING)`, count: 1, numRows: 0},
{
query: `INSERT INTO posts VALUES (1, 'foo')`,
fingerprinted: `INSERT INTO posts VALUES (_, _)`,
count: 1,
numRows: 1,
},
{query: `SELECT * FROM posts`, count: 2, numRows: 1},
{query: `BEGIN; SELECT * FROM posts; SELECT * FROM posts; COMMIT`, count: 3, numRows: 2},
{
query: `BEGIN; SELECT crdb_internal.force_retry('2s'); SELECT * FROM posts; COMMIT;`,
fingerprinted: `BEGIN; SELECT crdb_internal.force_retry(_); SELECT * FROM posts; COMMIT;`,
shouldRetry: true,
count: 1,
numRows: 2,
},
{
query: `BEGIN; SELECT crdb_internal.force_retry('5s'); SELECT * FROM posts; COMMIT;`,
fingerprinted: `BEGIN; SELECT crdb_internal.force_retry(_); SELECT * FROM posts; COMMIT;`,
shouldRetry: true,
count: 1,
numRows: 2,
},
}
appNameToTestCase := make(map[string]testCase)
for i, tc := range testCases {
appName := fmt.Sprintf("app%d", i)
appNameToTestCase[appName] = tc
// Create a brand new connection for each app, so that we don't pollute
// transaction stats collection with `SET application_name` queries.
sqlDB, err := gosql.Open("postgres", pgURL.String())
if err != nil {
t.Fatal(err)
}
if _, err := sqlDB.Exec(fmt.Sprintf(`SET application_name = "%s"`, appName)); err != nil {
t.Fatal(err)
}
for c := 0; c < tc.count; c++ {
if _, err := sqlDB.Exec(tc.query); err != nil {
t.Fatal(err)
}
}
if err := sqlDB.Close(); err != nil {
t.Fatal(err)
}
}
// Hit query endpoint.
var resp serverpb.StatementsResponse
if err := srvtestutils.GetStatusJSONProtoWithAdminAndTimeoutOption(firstServerProto, "statements", &resp, true, additionalTimeout); err != nil {
t.Fatal(err)
}
// Construct a map of all the statement fingerprint IDs.
statementFingerprintIDs := make(map[appstatspb.StmtFingerprintID]bool, len(resp.Statements))
for _, respStatement := range resp.Statements {
statementFingerprintIDs[respStatement.ID] = true
}
respAppNames := make(map[string]bool)
for _, respTransaction := range resp.Transactions {
appName := respTransaction.StatsData.App
tc, found := appNameToTestCase[appName]
if !found {
// Ignore internal queries, they aren't relevant to this test.
continue
}
respAppNames[appName] = true
// Ensure all statementFingerprintIDs comprised by the Transaction Response can be
// linked to StatementFingerprintIDs for statements in the response.
for _, stmtFingerprintID := range respTransaction.StatsData.StatementFingerprintIDs {
if _, found := statementFingerprintIDs[stmtFingerprintID]; !found {
t.Fatalf("app: %s, expected stmtFingerprintID: %d not found in StatementResponse.", appName, stmtFingerprintID)
}
}
stats := respTransaction.StatsData.Stats
if tc.count != int(stats.Count) {
t.Fatalf("app: %s, expected count %d, got %d", appName, tc.count, stats.Count)
}
if tc.shouldRetry && respTransaction.StatsData.Stats.MaxRetries == 0 {
t.Fatalf("app: %s, expected retries, got none\n", appName)
}
// Sanity check numeric stat values
if respTransaction.StatsData.Stats.CommitLat.Mean <= 0 {
t.Fatalf("app: %s, unexpected mean for commit latency\n", appName)
}
if respTransaction.StatsData.Stats.RetryLat.Mean <= 0 && tc.shouldRetry {
t.Fatalf("app: %s, expected retry latency mean to be non-zero as retries were involved\n", appName)
}
if respTransaction.StatsData.Stats.ServiceLat.Mean <= 0 {
t.Fatalf("app: %s, unexpected mean for service latency\n", appName)
}
if respTransaction.StatsData.Stats.NumRows.Mean != float64(tc.numRows) {
t.Fatalf("app: %s, unexpected number of rows observed. expected: %d, got %d\n",
appName, tc.numRows, int(respTransaction.StatsData.Stats.NumRows.Mean))
}
}
// Ensure we got transaction statistics for all the queries we sent.
for appName := range appNameToTestCase {
if _, found := respAppNames[appName]; !found {
t.Fatalf("app: %s did not appear in the response\n", appName)
}
}
}
func TestStatusAPITransactionStatementFingerprintIDsTruncation(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testCluster := serverutils.StartCluster(t, 3, base.TestClusterArgs{})
defer testCluster.Stopper().Stop(context.Background())
firstServerProto := testCluster.Server(0)
thirdServerSQL := sqlutils.MakeSQLRunner(testCluster.ServerConn(2))
testingApp := "testing"
thirdServerSQL.Exec(t, `CREATE DATABASE db; CREATE TABLE db.t();`)
thirdServerSQL.Exec(t, fmt.Sprintf(`SET application_name = "%s"`, testingApp))
maxStmtFingerprintIDsLen := int(sqlstats.TxnStatsNumStmtFingerprintIDsToRecord.Get(
&firstServerProto.ExecutorConfig().(sql.ExecutorConfig).Settings.SV))
// Construct 2 transaction queries that include an absurd number of statements.
// These two queries have the same first 1000 statements, but should still have
// different fingerprints, as fingerprints take into account all
// statementFingerprintIDs (unlike the statementFingerprintIDs stored on the
// proto response, which are capped).
testQuery1 := "BEGIN;"
for i := 0; i < maxStmtFingerprintIDsLen+1; i++ {
testQuery1 += "SELECT * FROM db.t;"
}
testQuery2 := testQuery1 + "SELECT * FROM db.t; COMMIT;"
testQuery1 += "COMMIT;"
thirdServerSQL.Exec(t, testQuery1)
thirdServerSQL.Exec(t, testQuery2)
// Hit query endpoint.
var resp serverpb.StatementsResponse
if err := srvtestutils.GetStatusJSONProto(firstServerProto, "statements", &resp); err != nil {
t.Fatal(err)
}
txnsFound := 0
for _, respTransaction := range resp.Transactions {
appName := respTransaction.StatsData.App
if appName != testingApp {
// Only testQuery1 and testQuery2 are relevant to this test.
continue
}
txnsFound++
if len(respTransaction.StatsData.StatementFingerprintIDs) != maxStmtFingerprintIDsLen {
t.Fatalf("unexpected length of StatementFingerprintIDs. expected:%d, got:%d",
maxStmtFingerprintIDsLen, len(respTransaction.StatsData.StatementFingerprintIDs))
}
}
if txnsFound != 2 {
t.Fatalf("transactions were not disambiguated as expected. expected %d txns, got: %d",
2, txnsFound)
}
}
func TestStatusAPIStatements(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// Increase the timeout for the http client if under stress.
additionalTimeout := 0 * time.Second
if skip.Stress() {
additionalTimeout = 20 * time.Second
}
// Aug 30 2021 19:50:00 GMT+0000
aggregatedTs := int64(1630353000)
statsKnobs := sqlstats.CreateTestingKnobs()
statsKnobs.StubTimeNow = func() time.Time { return timeutil.Unix(aggregatedTs, 0) }
testCluster := serverutils.StartCluster(t, 3, base.TestClusterArgs{
ServerArgs: base.TestServerArgs{
Knobs: base.TestingKnobs{
SQLStatsKnobs: statsKnobs,
SpanConfig: &spanconfig.TestingKnobs{
ManagerDisableJobCreation: true, // TODO(irfansharif): #74919.
},
},
},
})
defer testCluster.Stopper().Stop(context.Background())
firstServerProto := testCluster.Server(0)
thirdServerSQL := sqlutils.MakeSQLRunner(testCluster.ServerConn(2))
statements := []struct {
stmt string
fingerprinted string
}{
{stmt: `CREATE DATABASE roachblog`},
{stmt: `SET database = roachblog`},
{stmt: `CREATE TABLE posts (id INT8 PRIMARY KEY, body STRING)`},
{
stmt: `INSERT INTO posts VALUES (1, 'foo')`,
fingerprinted: `INSERT INTO posts VALUES (_, '_')`,
},
{stmt: `SELECT * FROM posts`},
}
for _, stmt := range statements {
thirdServerSQL.Exec(t, stmt.stmt)
}
// Test that non-admin without VIEWACTIVITY privileges cannot access.
var resp serverpb.StatementsResponse
err := srvtestutils.GetStatusJSONProtoWithAdminOption(firstServerProto, "statements", &resp, false)
if !testutils.IsError(err, "status: 403") {
t.Fatalf("expected privilege error, got %v", err)
}
testPath := func(path string, expectedStmts []string) {
// Hit query endpoint.
if err := srvtestutils.GetStatusJSONProtoWithAdminAndTimeoutOption(firstServerProto, path, &resp, false, additionalTimeout); err != nil {
t.Fatal(err)
}
// See if the statements returned are what we executed.
var statementsInResponse []string
for _, respStatement := range resp.Statements {
if respStatement.Key.KeyData.Failed {
// We ignore failed statements here as the INSERT statement can fail and
// be automatically retried, confusing the test success check.
continue
}
if strings.HasPrefix(respStatement.Key.KeyData.App, catconstants.InternalAppNamePrefix) {
// We ignore internal queries, these are not relevant for the
// validity of this test.
continue
}
if strings.HasPrefix(respStatement.Key.KeyData.Query, "ALTER USER") {
// Ignore the ALTER USER ... VIEWACTIVITY statement.
continue
}
statementsInResponse = append(statementsInResponse, respStatement.Key.KeyData.Query)
}
sort.Strings(expectedStmts)
sort.Strings(statementsInResponse)
if !reflect.DeepEqual(expectedStmts, statementsInResponse) {
t.Fatalf("expected queries\n\n%v\n\ngot queries\n\n%v\n%s",
expectedStmts, statementsInResponse, pretty.Sprint(resp))
}
}
var expectedStatements []string
for _, stmt := range statements {
var expectedStmt = stmt.stmt
if stmt.fingerprinted != "" {
expectedStmt = stmt.fingerprinted
}
expectedStatements = append(expectedStatements, expectedStmt)
}
// Grant VIEWACTIVITY.
thirdServerSQL.Exec(t, fmt.Sprintf("ALTER USER %s VIEWACTIVITY", apiconstants.TestingUserNameNoAdmin().Normalized()))
// Test no params.
testPath("statements", expectedStatements)
// Test combined=true forwards to CombinedStatements
testPath(fmt.Sprintf("statements?combined=true&start=%d", aggregatedTs+60), nil)
// Remove VIEWACTIVITY so we can test with just the VIEWACTIVITYREDACTED role.
thirdServerSQL.Exec(t, fmt.Sprintf("ALTER USER %s NOVIEWACTIVITY", apiconstants.TestingUserNameNoAdmin().Normalized()))
// Grant VIEWACTIVITYREDACTED.
thirdServerSQL.Exec(t, fmt.Sprintf("ALTER USER %s VIEWACTIVITYREDACTED", apiconstants.TestingUserNameNoAdmin().Normalized()))
// Test no params.
testPath("statements", expectedStatements)
// Test combined=true forwards to CombinedStatements
testPath(fmt.Sprintf("statements?combined=true&start=%d", aggregatedTs+60), nil)
}
func TestStatusAPICombinedStatementsWithFullScans(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// Increase the timeout for the http client if under stress.
additionalTimeout := 0 * time.Second
if skip.Stress() {
additionalTimeout = 20 * time.Second
}
// Aug 30 2021 19:50:00 GMT+0000
aggregatedTs := int64(1630353000)
oneMinAfterAggregatedTs := aggregatedTs + 60
statsKnobs := sqlstats.CreateTestingKnobs()
statsKnobs.StubTimeNow = func() time.Time { return timeutil.Unix(aggregatedTs, 0) }
testCluster := serverutils.StartCluster(t, 3, base.TestClusterArgs{
ServerArgs: base.TestServerArgs{
Knobs: base.TestingKnobs{
SQLStatsKnobs: statsKnobs,
SpanConfig: &spanconfig.TestingKnobs{
ManagerDisableJobCreation: true,
},
},
},
})
defer testCluster.Stopper().Stop(context.Background())
endpoint := fmt.Sprintf("combinedstmts?start=%d&end=%d", aggregatedTs-3600, oneMinAfterAggregatedTs)
findJobQuery := "SELECT status FROM [SHOW JOBS] WHERE statement = 'CREATE INDEX idx_age ON football.public.players (age) STORING (name)';"
firstServerProto := testCluster.Server(0)
sqlSB := testCluster.ServerConn(0)
thirdServerSQL := sqlutils.MakeSQLRunner(testCluster.ServerConn(2))
var resp serverpb.StatementsResponse
// Test that non-admin without VIEWACTIVITY privileges cannot access.
err := srvtestutils.GetStatusJSONProtoWithAdminOption(firstServerProto, endpoint, &resp, false)
if !testutils.IsError(err, "status: 403") {
t.Fatalf("expected privilege error, got %v", err)
}
thirdServerSQL.Exec(t, fmt.Sprintf("GRANT SYSTEM VIEWACTIVITY TO %s", apiconstants.TestingUserNameNoAdmin().Normalized()))
type TestCases struct {
stmt string
respQuery string
fullScan bool
distSQL bool
failed bool
count int
}
// These test statements are executed before any indexes are introduced.
statementsBeforeIndex := []TestCases{
{stmt: `CREATE DATABASE football`, respQuery: `CREATE DATABASE football`, fullScan: false, distSQL: false, failed: false, count: 1},
{stmt: `SET database = football`, respQuery: `SET database = football`, fullScan: false, distSQL: false, failed: false, count: 1},
{stmt: `CREATE TABLE players (id INT PRIMARY KEY, name TEXT, position TEXT, age INT,goals INT)`, respQuery: `CREATE TABLE players (id INT8 PRIMARY KEY, name STRING, "position" STRING, age INT8, goals INT8)`, fullScan: false, distSQL: false, failed: false, count: 1},
{stmt: `INSERT INTO players (id, name, position, age, goals) VALUES (1, 'Lionel Messi', 'Forward', 34, 672), (2, 'Cristiano Ronaldo', 'Forward', 36, 674)`, respQuery: `INSERT INTO players(id, name, "position", age, goals) VALUES (_, '_', __more1_10__), (__more1_10__)`, fullScan: false, distSQL: false, failed: false, count: 1},
{stmt: `SELECT avg(goals) FROM players`, respQuery: `SELECT avg(goals) FROM players`, fullScan: true, distSQL: true, failed: false, count: 1},
{stmt: `SELECT name FROM players WHERE age >= 32`, respQuery: `SELECT name FROM players WHERE age >= _`, fullScan: true, distSQL: true, failed: false, count: 1},
}
statementsCreateIndex := []TestCases{
// Drop the index, if it exists. Then, create the index.
{stmt: `DROP INDEX IF EXISTS idx_age`, respQuery: `DROP INDEX IF EXISTS idx_age`, fullScan: false, distSQL: false, failed: false, count: 1},
{stmt: `CREATE INDEX idx_age ON players (age) STORING (name)`, respQuery: `CREATE INDEX idx_age ON players (age) STORING (name)`, fullScan: false, distSQL: false, failed: false, count: 1},
}
// These test statements are executed after an index is created on the players table.
statementsAfterIndex := []TestCases{
// Since the index is created, the fullScan value should be false.
{stmt: `SELECT name FROM players WHERE age < 32`, respQuery: `SELECT name FROM players WHERE age < _`, fullScan: false, distSQL: false, failed: false, count: 1},
// Although the index is created, the fullScan value should be true because the previous query was not using the index. Its count should also be 2.
{stmt: `SELECT name FROM players WHERE age >= 32`, respQuery: `SELECT name FROM players WHERE age >= _`, fullScan: true, distSQL: true, failed: false, count: 2},
}
type StatementData struct {
count int
fullScan bool
distSQL bool
failed bool
}
// Declare the map outside of the executeStatements function.
statementDataMap := make(map[string]StatementData)
executeStatements := func(statements []TestCases) {
// For each statement in the test case, execute the statement and store the
// expected statement data in a map.
for _, stmt := range statements {
thirdServerSQL.Exec(t, stmt.stmt)
statementDataMap[stmt.respQuery] = StatementData{
fullScan: stmt.fullScan,
distSQL: stmt.distSQL,
failed: stmt.failed,
count: stmt.count,
}
}
}
verifyCombinedStmtStats := func() {
err := srvtestutils.GetStatusJSONProtoWithAdminAndTimeoutOption(firstServerProto, endpoint, &resp, false, additionalTimeout)
require.NoError(t, err)
for _, respStatement := range resp.Statements {
respQuery := respStatement.Key.KeyData.Query
actualCount := respStatement.Stats.Count
actualFullScan := respStatement.Key.KeyData.FullScan
actualDistSQL := respStatement.Key.KeyData.DistSQL
actualFailed := respStatement.Key.KeyData.Failed
// If the response has a query that isn't in our map, it means that it's
// not part of our test, so we ignore it.
expectedData, ok := statementDataMap[respQuery]
if !ok {
continue
}
require.Equal(t, expectedData.fullScan, actualFullScan)
require.Equal(t, expectedData.distSQL, actualDistSQL)
require.Equal(t, expectedData.failed, actualFailed)
require.Equal(t, expectedData.count, int(actualCount))
}
}
// Execute the queries that will be executed before the index is created.
executeStatements(statementsBeforeIndex)
// Test the statements that will be executed before the index is created.
verifyCombinedStmtStats()
// Execute the queries that will create the index.
executeStatements(statementsCreateIndex)
// Wait for the job which creates the index to complete.
testutils.SucceedsWithin(t, func() error {
var status string
for {
row := sqlSB.QueryRow(findJobQuery)
err = row.Scan(&status)
if err != nil {
return err
}
if status == "succeeded" {
break
}
// sleep for a fraction of a second
time.Sleep(100 * time.Millisecond)
}
return nil
}, 3*time.Second)
// Execute the queries that will be executed after the index is created.
executeStatements(statementsAfterIndex)
// Test the statements that will be executed after the index is created.
verifyCombinedStmtStats()
}
func TestStatusAPICombinedStatements(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// Skip under stress until we extend the timeout for the http client.
skip.UnderStressWithIssue(t, 109184)
// Aug 30 2021 19:50:00 GMT+0000
aggregatedTs := int64(1630353000)
statsKnobs := sqlstats.CreateTestingKnobs()
statsKnobs.StubTimeNow = func() time.Time { return timeutil.Unix(aggregatedTs, 0) }
testCluster := serverutils.StartCluster(t, 3, base.TestClusterArgs{
ServerArgs: base.TestServerArgs{
Knobs: base.TestingKnobs{
SQLStatsKnobs: statsKnobs,
SpanConfig: &spanconfig.TestingKnobs{
ManagerDisableJobCreation: true, // TODO(irfansharif): #74919.
},
},
},
})
defer testCluster.Stopper().Stop(context.Background())
firstServerProto := testCluster.Server(0)
thirdServerSQL := sqlutils.MakeSQLRunner(testCluster.ServerConn(2))
statements := []struct {
stmt string
fingerprinted string
}{
{stmt: `CREATE DATABASE roachblog`},
{stmt: `SET database = roachblog`},
{stmt: `CREATE TABLE posts (id INT8 PRIMARY KEY, body STRING)`},
{
stmt: `INSERT INTO posts VALUES (1, 'foo')`,
fingerprinted: `INSERT INTO posts VALUES (_, '_')`,
},
{stmt: `SELECT * FROM posts`},
}
for _, stmt := range statements {
thirdServerSQL.Exec(t, stmt.stmt)
}
var resp serverpb.StatementsResponse
// Test that non-admin without VIEWACTIVITY privileges cannot access.
err := srvtestutils.GetStatusJSONProtoWithAdminOption(firstServerProto, "combinedstmts", &resp, false)
if !testutils.IsError(err, "status: 403") {
t.Fatalf("expected privilege error, got %v", err)
}
verifyStmts := func(path string, expectedStmts []string, hasTxns bool, t *testing.T) {
// Hit query endpoint.
if err := srvtestutils.GetStatusJSONProtoWithAdminOption(firstServerProto, path, &resp, false); err != nil {
t.Fatal(err)
}
// See if the statements returned are what we executed.
var statementsInResponse []string
expectedTxnFingerprints := map[appstatspb.TransactionFingerprintID]struct{}{}
for _, respStatement := range resp.Statements {
if respStatement.Key.KeyData.Failed {
// We ignore failed statements here as the INSERT statement can fail and
// be automatically retried, confusing the test success check.
continue
}
if strings.HasPrefix(respStatement.Key.KeyData.App, catconstants.InternalAppNamePrefix) {
// CombinedStatementStats should filter out internal queries.
t.Fatalf("unexpected internal query: %s", respStatement.Key.KeyData.Query)
}
if strings.HasPrefix(respStatement.Key.KeyData.Query, "ALTER USER") {
// Ignore the ALTER USER ... VIEWACTIVITY statement.
continue
}
statementsInResponse = append(statementsInResponse, respStatement.Key.KeyData.Query)
for _, txnFingerprintID := range respStatement.TxnFingerprintIDs {
expectedTxnFingerprints[txnFingerprintID] = struct{}{}
}
}
for _, respTxn := range resp.Transactions {
delete(expectedTxnFingerprints, respTxn.StatsData.TransactionFingerprintID)
}
sort.Strings(expectedStmts)
sort.Strings(statementsInResponse)
if !reflect.DeepEqual(expectedStmts, statementsInResponse) {
t.Fatalf("expected queries\n\n%v\n\ngot queries\n\n%v\n%s\n path: %s",
expectedStmts, statementsInResponse, pretty.Sprint(resp), path)
}
if hasTxns {
// We expect that expectedTxnFingerprints is now empty since
// we should have removed them all.
assert.Empty(t, expectedTxnFingerprints)
} else {
assert.Empty(t, resp.Transactions)
}
}
var expectedStatements []string
for _, stmt := range statements {
var expectedStmt = stmt.stmt
if stmt.fingerprinted != "" {
expectedStmt = stmt.fingerprinted
}
expectedStatements = append(expectedStatements, expectedStmt)
}
oneMinAfterAggregatedTs := aggregatedTs + 60
t.Run("fetch_mode=combined, VIEWACTIVITY", func(t *testing.T) {
// Grant VIEWACTIVITY.
thirdServerSQL.Exec(t, fmt.Sprintf("ALTER USER %s VIEWACTIVITY", apiconstants.TestingUserNameNoAdmin().Normalized()))
// Test with no query params.
verifyStmts("combinedstmts", expectedStatements, true, t)
// Test with end = 1 min after aggregatedTs; should give the same results as get all.
verifyStmts(fmt.Sprintf("combinedstmts?end=%d", oneMinAfterAggregatedTs), expectedStatements, true, t)
// Test with start = 1 hour before aggregatedTs end = 1 min after aggregatedTs; should give same results as get all.
verifyStmts(fmt.Sprintf("combinedstmts?start=%d&end=%d", aggregatedTs-3600, oneMinAfterAggregatedTs),
expectedStatements, true, t)
// Test with start = 1 min after aggregatedTs; should give no results
verifyStmts(fmt.Sprintf("combinedstmts?start=%d", oneMinAfterAggregatedTs), nil, true, t)
})
t.Run("fetch_mode=combined, VIEWACTIVITYREDACTED", func(t *testing.T) {
// Remove VIEWACTIVITY so we can test with just the VIEWACTIVITYREDACTED role.
thirdServerSQL.Exec(t, fmt.Sprintf("ALTER USER %s NOVIEWACTIVITY", apiconstants.TestingUserNameNoAdmin().Normalized()))
// Grant VIEWACTIVITYREDACTED.
thirdServerSQL.Exec(t, fmt.Sprintf("ALTER USER %s VIEWACTIVITYREDACTED", apiconstants.TestingUserNameNoAdmin().Normalized()))
// Test with no query params.
verifyStmts("combinedstmts", expectedStatements, true, t)
// Test with end = 1 min after aggregatedTs; should give the same results as get all.
verifyStmts(fmt.Sprintf("combinedstmts?end=%d", oneMinAfterAggregatedTs), expectedStatements, true, t)
// Test with start = 1 hour before aggregatedTs end = 1 min after aggregatedTs; should give same results as get all.
verifyStmts(fmt.Sprintf("combinedstmts?start=%d&end=%d", aggregatedTs-3600, oneMinAfterAggregatedTs), expectedStatements, true, t)
// Test with start = 1 min after aggregatedTs; should give no results
verifyStmts(fmt.Sprintf("combinedstmts?start=%d", oneMinAfterAggregatedTs), nil, true, t)
})
t.Run("fetch_mode=StmtsOnly", func(t *testing.T) {
verifyStmts("combinedstmts?fetch_mode.stats_type=0", expectedStatements, false, t)
})
t.Run("fetch_mode=TxnsOnly with limit", func(t *testing.T) {
// Verify that we only return stmts for the txns in the response.
// We'll add a limit in a later commit to help verify this behaviour.
if err := srvtestutils.GetStatusJSONProtoWithAdminOption(firstServerProto, "combinedstmts?fetch_mode.stats_type=1&limit=2",
&resp, false); err != nil {
t.Fatal(err)
}
assert.Equal(t, 2, len(resp.Transactions))
stmtFingerprintIDs := map[appstatspb.StmtFingerprintID]struct{}{}
for _, txn := range resp.Transactions {
for _, stmtFingerprint := range txn.StatsData.StatementFingerprintIDs {
stmtFingerprintIDs[stmtFingerprint] = struct{}{}
}
}
for _, stmt := range resp.Statements {
if _, ok := stmtFingerprintIDs[stmt.ID]; !ok {
t.Fatalf("unexpected stmt; stmt unrelated to a txn int he response: %s", stmt.Key.KeyData.Query)
}
}
})
}
func TestStatusAPIStatementDetails(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// Increase the timeout for the http client if under stress.
additionalTimeout := 0 * time.Second
if skip.Stress() {
additionalTimeout = 20 * time.Second
}
// Aug 30 2021 19:50:00 GMT+0000
aggregatedTs := int64(1630353000)
statsKnobs := sqlstats.CreateTestingKnobs()
statsKnobs.StubTimeNow = func() time.Time { return timeutil.Unix(aggregatedTs, 0) }
testCluster := serverutils.StartCluster(t, 3, base.TestClusterArgs{
ServerArgs: base.TestServerArgs{
Knobs: base.TestingKnobs{
SQLStatsKnobs: statsKnobs,
SpanConfig: &spanconfig.TestingKnobs{
ManagerDisableJobCreation: true,
},
},
},
})
defer testCluster.Stopper().Stop(context.Background())
firstServerProto := testCluster.Server(0)
thirdServerSQL := sqlutils.MakeSQLRunner(testCluster.ServerConn(2))
statements := []string{
`set application_name = 'first-app'`,
`CREATE DATABASE roachblog`,
`SET database = roachblog`,
`CREATE TABLE posts (id INT8 PRIMARY KEY, body STRING)`,
`INSERT INTO posts VALUES (1, 'foo')`,
`INSERT INTO posts VALUES (2, 'foo')`,
`INSERT INTO posts VALUES (3, 'foo')`,
`SELECT * FROM posts`,
}
for _, stmt := range statements {
thirdServerSQL.Exec(t, stmt)
}
query := `INSERT INTO posts VALUES (_, '_')`
fingerprintID := appstatspb.ConstructStatementFingerprintID(query,
false, true, `roachblog`)
path := fmt.Sprintf(`stmtdetails/%v`, fingerprintID)
var resp serverpb.StatementDetailsResponse
// Test that non-admin without VIEWACTIVITY or VIEWACTIVITYREDACTED privileges cannot access.
err := srvtestutils.GetStatusJSONProtoWithAdminOption(firstServerProto, path, &resp, false)
if !testutils.IsError(err, "status: 403") {
t.Fatalf("expected privilege error, got %v", err)
}
type resultValues struct {
query string
totalCount int
aggregatedTsCount int
planHashCount int
fullScanCount int
appNames []string
databases []string
}
testPath := func(path string, expected resultValues) {
err := srvtestutils.GetStatusJSONProtoWithAdminAndTimeoutOption(firstServerProto, path, &resp, false, additionalTimeout)
require.NoError(t, err)
require.Equal(t, int64(expected.totalCount), resp.Statement.Stats.Count)
require.Equal(t, expected.aggregatedTsCount, len(resp.StatementStatisticsPerAggregatedTs))
require.Equal(t, expected.planHashCount, len(resp.StatementStatisticsPerPlanHash))
require.Equal(t, expected.query, resp.Statement.Metadata.Query)
require.Equal(t, expected.appNames, resp.Statement.Metadata.AppNames)
require.Equal(t, int64(expected.totalCount), resp.Statement.Metadata.TotalCount)
require.Equal(t, expected.databases, resp.Statement.Metadata.Databases)
require.Equal(t, int64(expected.fullScanCount), resp.Statement.Metadata.FullScanCount)
}
// Grant VIEWACTIVITY.
thirdServerSQL.Exec(t, fmt.Sprintf("ALTER USER %s VIEWACTIVITY", apiconstants.TestingUserNameNoAdmin().Normalized()))
// Test with no query params.
testPath(
path,
resultValues{
query: query,
totalCount: 3,
aggregatedTsCount: 1,
planHashCount: 1,
appNames: []string{"first-app"},
fullScanCount: 0,
databases: []string{"roachblog"},
})
// Execute same fingerprint id statement on a different application
statements = []string{
`set application_name = 'second-app'`,
`INSERT INTO posts VALUES (4, 'foo')`,
`INSERT INTO posts VALUES (5, 'foo')`,
}
for _, stmt := range statements {
thirdServerSQL.Exec(t, stmt)
}
oneMinAfterAggregatedTs := aggregatedTs + 60
testData := []struct {
path string
expectedResult resultValues
}{
{ // Test with no query params.
path: path,
expectedResult: resultValues{
query: query,
totalCount: 5,
aggregatedTsCount: 1,
planHashCount: 1,
appNames: []string{"first-app", "second-app"},
fullScanCount: 0,
databases: []string{"roachblog"}},
},
{ // Test with end = 1 min after aggregatedTs; should give the same results as get all.
path: fmt.Sprintf("%v?end=%d", path, oneMinAfterAggregatedTs),
expectedResult: resultValues{
query: query,
totalCount: 5,
aggregatedTsCount: 1,
planHashCount: 1,
appNames: []string{"first-app", "second-app"},
fullScanCount: 0,
databases: []string{"roachblog"}},
},
{ // Test with start = 1 hour before aggregatedTs end = 1 min after aggregatedTs; should give same results as get all.
path: fmt.Sprintf("%v?start=%d&end=%d", path, aggregatedTs-3600, oneMinAfterAggregatedTs),
expectedResult: resultValues{
query: query,
totalCount: 5,
aggregatedTsCount: 1,
planHashCount: 1,
appNames: []string{"first-app", "second-app"},
fullScanCount: 0,
databases: []string{"roachblog"}},
},
{ // Test with start = 1 min after aggregatedTs; should give no results.
path: fmt.Sprintf("%v?start=%d", path, oneMinAfterAggregatedTs),
expectedResult: resultValues{
query: "",
totalCount: 0,
aggregatedTsCount: 0,
planHashCount: 0,
appNames: []string{},
fullScanCount: 0,
databases: []string{}},
},
{ // Test with one app_name.
path: fmt.Sprintf("%v?app_names=first-app", path),
expectedResult: resultValues{
query: query,
totalCount: 3,
aggregatedTsCount: 1,
planHashCount: 1,
appNames: []string{"first-app"},
fullScanCount: 0,
databases: []string{"roachblog"}},