-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
status_test.go
2203 lines (1943 loc) · 69.9 KB
/
status_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 2015 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"
gosql "database/sql"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"testing"
"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/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/security/securitytest"
"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/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catconstants"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/storage/enginepb"
"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/ts"
"github.com/cockroachdb/cockroach/pkg/ts/catalog"
"github.com/cockroachdb/cockroach/pkg/util/httputil"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"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/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"github.com/kr/pretty"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func getStatusJSONProto(
ts serverutils.TestServerInterface, path string, response protoutil.Message,
) error {
return serverutils.GetJSONProto(ts, statusPrefix+path, response)
}
func postStatusJSONProto(
ts serverutils.TestServerInterface, path string, request, response protoutil.Message,
) error {
return serverutils.PostJSONProto(ts, statusPrefix+path, request, response)
}
func getStatusJSONProtoWithAdminOption(
ts serverutils.TestServerInterface, path string, response protoutil.Message, isAdmin bool,
) error {
return serverutils.GetJSONProtoWithAdminOption(ts, statusPrefix+path, response, isAdmin)
}
// TestStatusLocalStacks verifies that goroutine stack traces are available
// via the /_status/stacks/local endpoint.
func TestStatusLocalStacks(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{})
defer s.Stopper().Stop(context.Background())
// Verify match with at least two goroutine stacks.
re := regexp.MustCompile("(?s)goroutine [0-9]+.*goroutine [0-9]+.*")
var stacks serverpb.JSONResponse
for _, nodeID := range []string{"local", "1"} {
if err := getStatusJSONProto(s, "stacks/"+nodeID, &stacks); err != nil {
t.Fatal(err)
}
if !re.Match(stacks.Data) {
t.Errorf("expected %s to match %s", stacks.Data, re)
}
}
}
// TestStatusJson verifies that status endpoints return expected Json results.
// The content type of the responses is always httputil.JSONContentType.
func TestStatusJson(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{})
defer s.Stopper().Stop(context.Background())
ts := s.(*TestServer)
nodeID := ts.Gossip().NodeID.Get()
addr, err := ts.Gossip().GetNodeIDAddress(nodeID)
if err != nil {
t.Fatal(err)
}
sqlAddr, err := ts.Gossip().GetNodeIDSQLAddress(nodeID)
if err != nil {
t.Fatal(err)
}
var nodes serverpb.NodesResponse
testutils.SucceedsSoon(t, func() error {
if err := getStatusJSONProto(s, "nodes", &nodes); err != nil {
t.Fatal(err)
}
if len(nodes.Nodes) == 0 {
return errors.Errorf("expected non-empty node list, got: %v", nodes)
}
return nil
})
for _, path := range []string{
statusPrefix + "details/local",
statusPrefix + "details/" + strconv.FormatUint(uint64(nodeID), 10),
} {
var details serverpb.DetailsResponse
if err := serverutils.GetJSONProto(s, path, &details); err != nil {
t.Fatal(err)
}
if a, e := details.NodeID, nodeID; a != e {
t.Errorf("expected: %d, got: %d", e, a)
}
if a, e := details.Address, *addr; a != e {
t.Errorf("expected: %v, got: %v", e, a)
}
if a, e := details.SQLAddress, *sqlAddr; a != e {
t.Errorf("expected: %v, got: %v", e, a)
}
if a, e := details.BuildInfo, build.GetInfo(); a != e {
t.Errorf("expected: %v, got: %v", e, a)
}
}
}
// TestHealthTelemetry confirms that hits on some status endpoints increment
// feature telemetry counters.
func TestHealthTelemetry(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, db, _ := serverutils.StartServer(t, base.TestServerArgs{})
defer s.Stopper().Stop(context.Background())
rows, err := db.Query("SELECT * FROM crdb_internal.feature_usage WHERE feature_name LIKE 'monitoring%' AND usage_count > 0;")
defer func() {
if err := rows.Close(); err != nil {
t.Fatal(err)
}
}()
if err != nil {
t.Fatal(err)
}
initialCounts := make(map[string]int)
for rows.Next() {
var featureName string
var usageCount int
if err := rows.Scan(&featureName, &usageCount); err != nil {
t.Fatal(err)
}
initialCounts[featureName] = usageCount
}
var details serverpb.DetailsResponse
if err := serverutils.GetJSONProto(s, "/health", &details); err != nil {
t.Fatal(err)
}
if _, err := getText(s, s.AdminURL()+statusPrefix+"vars"); err != nil {
t.Fatal(err)
}
expectedCounts := map[string]int{
"monitoring.prometheus.vars": 1,
"monitoring.health.details": 1,
}
rows2, err := db.Query("SELECT feature_name, usage_count FROM crdb_internal.feature_usage WHERE feature_name LIKE 'monitoring%' AND usage_count > 0;")
defer func() {
if err := rows2.Close(); err != nil {
t.Fatal(err)
}
}()
if err != nil {
t.Fatal(err)
}
for rows2.Next() {
var featureName string
var usageCount int
if err := rows2.Scan(&featureName, &usageCount); err != nil {
t.Fatal(err)
}
usageCount -= initialCounts[featureName]
if count, ok := expectedCounts[featureName]; ok {
if count != usageCount {
t.Fatalf("expected %d count for feature %s, got %d", count, featureName, usageCount)
}
delete(expectedCounts, featureName)
}
}
if len(expectedCounts) > 0 {
t.Fatalf("%d expected telemetry counters not emitted", len(expectedCounts))
}
}
// TestStatusGossipJson ensures that the output response for the full gossip
// info contains the required fields.
func TestStatusGossipJson(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{})
defer s.Stopper().Stop(context.Background())
var data gossip.InfoStatus
if err := getStatusJSONProto(s, "gossip/local", &data); err != nil {
t.Fatal(err)
}
if _, ok := data.Infos["first-range"]; !ok {
t.Errorf("no first-range info returned: %v", data)
}
if _, ok := data.Infos["cluster-id"]; !ok {
t.Errorf("no clusterID info returned: %v", data)
}
if _, ok := data.Infos["node:1"]; !ok {
t.Errorf("no node 1 info returned: %v", data)
}
if _, ok := data.Infos["system-db"]; !ok {
t.Errorf("no system config info returned: %v", data)
}
}
// TestStatusEngineStatsJson ensures that the output response for the engine
// stats contains the required fields.
func TestStatusEngineStatsJson(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
dir, cleanupFn := testutils.TempDir(t)
defer cleanupFn()
s, err := serverutils.StartServerRaw(base.TestServerArgs{
StoreSpecs: []base.StoreSpec{{
Path: dir,
}},
})
if err != nil {
t.Fatal(err)
}
defer s.Stopper().Stop(context.Background())
var engineStats serverpb.EngineStatsResponse
if err := getStatusJSONProto(s, "enginestats/local", &engineStats); err != nil {
t.Fatal(err)
}
if len(engineStats.Stats) != 1 {
t.Fatal(errors.Errorf("expected one engine stats, got: %v", engineStats))
}
if engineStats.Stats[0].EngineType == enginepb.EngineTypePebble ||
engineStats.Stats[0].EngineType == enginepb.EngineTypeDefault {
// Pebble does not have RocksDB style TickersAnd Histogram.
return
}
tickers := engineStats.Stats[0].TickersAndHistograms.Tickers
if len(tickers) == 0 {
t.Fatal(errors.Errorf("expected non-empty tickers list, got: %v", tickers))
}
allTickersZero := true
for _, ticker := range tickers {
if ticker != 0 {
allTickersZero = false
}
}
if allTickersZero {
t.Fatal(errors.Errorf("expected some tickers nonzero, got: %v", tickers))
}
histograms := engineStats.Stats[0].TickersAndHistograms.Histograms
if len(histograms) == 0 {
t.Fatal(errors.Errorf("expected non-empty histograms list, got: %v", histograms))
}
allHistogramsZero := true
for _, histogram := range histograms {
if histogram.Max == 0 {
allHistogramsZero = false
}
}
if allHistogramsZero {
t.Fatal(errors.Errorf("expected some histograms nonzero, got: %v", histograms))
}
}
// startServer will start a server with a short scan interval, wait for
// the scan to complete, and return the server. The caller is
// responsible for stopping the server.
func startServer(t *testing.T) *TestServer {
tsI, _, kvDB := serverutils.StartServer(t, base.TestServerArgs{
StoreSpecs: []base.StoreSpec{
base.DefaultTestStoreSpec,
base.DefaultTestStoreSpec,
base.DefaultTestStoreSpec,
},
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
// Now that we allow same node rebalances, disable it in these tests,
// as they dont expect replicas to move.
DisableReplicaRebalancing: true,
},
},
})
ts := tsI.(*TestServer)
// Make sure the range is spun up with an arbitrary read command. We do not
// expect a specific response.
if _, err := kvDB.Get(context.Background(), "a"); err != nil {
t.Fatal(err)
}
// Make sure the node status is available. This is done by forcing stores to
// publish their status, synchronizing to the event feed with a canary
// event, and then forcing the server to write summaries immediately.
if err := ts.node.computePeriodicMetrics(context.Background(), 0); err != nil {
t.Fatalf("error publishing store statuses: %s", err)
}
if err := ts.WriteSummaries(); err != nil {
t.Fatalf("error writing summaries: %s", err)
}
return ts
}
func newRPCTestContext(ts *TestServer, cfg *base.Config) *rpc.Context {
rpcContext := rpc.NewContext(rpc.ContextOptions{
TenantID: roachpb.SystemTenantID,
AmbientCtx: log.AmbientContext{Tracer: ts.ClusterSettings().Tracer},
Config: cfg,
Clock: ts.Clock(),
Stopper: ts.Stopper(),
Settings: ts.ClusterSettings(),
})
// Ensure that the RPC client context validates the server cluster ID.
// This ensures that a test where the server is restarted will not let
// its test RPC client talk to a server started by an unrelated concurrent test.
rpcContext.ClusterID.Set(context.Background(), ts.ClusterID())
return rpcContext
}
// TestStatusGetFiles tests the GetFiles endpoint.
func TestStatusGetFiles(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
tempDir, cleanupFn := testutils.TempDir(t)
defer cleanupFn()
storeSpec := base.StoreSpec{Path: tempDir}
tsI, _, _ := serverutils.StartServer(t, base.TestServerArgs{
StoreSpecs: []base.StoreSpec{
storeSpec,
},
})
ts := tsI.(*TestServer)
defer ts.Stopper().Stop(context.Background())
rootConfig := testutils.NewTestBaseContext(security.RootUserName())
rpcContext := newRPCTestContext(ts, rootConfig)
url := ts.ServingRPCAddr()
nodeID := ts.NodeID()
conn, err := rpcContext.GRPCDialNode(url, nodeID, rpc.DefaultClass).Connect(context.Background())
if err != nil {
t.Fatal(err)
}
client := serverpb.NewStatusClient(conn)
// Test fetching heap files.
t.Run("heap", func(t *testing.T) {
const testFilesNo = 3
for i := 0; i < testFilesNo; i++ {
testHeapDir := filepath.Join(storeSpec.Path, "logs", base.HeapProfileDir)
testHeapFile := filepath.Join(testHeapDir, fmt.Sprintf("heap%d.pprof", i))
if err := os.MkdirAll(testHeapDir, os.ModePerm); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(testHeapFile, []byte(fmt.Sprintf("I'm heap file %d", i)), 0644); err != nil {
t.Fatal(err)
}
}
request := serverpb.GetFilesRequest{
NodeId: "local", Type: serverpb.FileType_HEAP, Patterns: []string{"*"}}
response, err := client.GetFiles(context.Background(), &request)
if err != nil {
t.Fatal(err)
}
if a, e := len(response.Files), testFilesNo; a != e {
t.Errorf("expected %d files(s), found %d", e, a)
}
for i, file := range response.Files {
expectedFileName := fmt.Sprintf("heap%d.pprof", i)
if file.Name != expectedFileName {
t.Fatalf("expected file name %s, found %s", expectedFileName, file.Name)
}
expectedFileContents := []byte(fmt.Sprintf("I'm heap file %d", i))
if !bytes.Equal(file.Contents, expectedFileContents) {
t.Fatalf("expected file contents %s, found %s", expectedFileContents, file.Contents)
}
}
})
// Test fetching goroutine files.
t.Run("goroutines", func(t *testing.T) {
const testFilesNo = 3
for i := 0; i < testFilesNo; i++ {
testGoroutineDir := filepath.Join(storeSpec.Path, "logs", base.GoroutineDumpDir)
testGoroutineFile := filepath.Join(testGoroutineDir, fmt.Sprintf("goroutine_dump%d.txt.gz", i))
if err := os.MkdirAll(testGoroutineDir, os.ModePerm); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(testGoroutineFile, []byte(fmt.Sprintf("Goroutine dump %d", i)), 0644); err != nil {
t.Fatal(err)
}
}
request := serverpb.GetFilesRequest{
NodeId: "local", Type: serverpb.FileType_GOROUTINES, Patterns: []string{"*"}}
response, err := client.GetFiles(context.Background(), &request)
if err != nil {
t.Fatal(err)
}
if a, e := len(response.Files), testFilesNo; a != e {
t.Errorf("expected %d files(s), found %d", e, a)
}
for i, file := range response.Files {
expectedFileName := fmt.Sprintf("goroutine_dump%d.txt.gz", i)
if file.Name != expectedFileName {
t.Fatalf("expected file name %s, found %s", expectedFileName, file.Name)
}
expectedFileContents := []byte(fmt.Sprintf("Goroutine dump %d", i))
if !bytes.Equal(file.Contents, expectedFileContents) {
t.Fatalf("expected file contents %s, found %s", expectedFileContents, file.Contents)
}
}
})
// Testing path separators in pattern.
t.Run("path separators", func(t *testing.T) {
request := serverpb.GetFilesRequest{NodeId: "local", ListOnly: true,
Type: serverpb.FileType_HEAP, Patterns: []string{"pattern/with/separators"}}
_, err = client.GetFiles(context.Background(), &request)
if !testutils.IsError(err, "invalid pattern: cannot have path seperators") {
t.Errorf("GetFiles: path separators allowed in pattern")
}
})
// Testing invalid filetypes.
t.Run("filetypes", func(t *testing.T) {
request := serverpb.GetFilesRequest{NodeId: "local", ListOnly: true,
Type: -1, Patterns: []string{"*"}}
_, err = client.GetFiles(context.Background(), &request)
if !testutils.IsError(err, "unknown file type: -1") {
t.Errorf("GetFiles: invalid file type allowed")
}
})
}
// TestStatusLocalLogs checks to ensure that local/logfiles,
// local/logfiles/{filename} and local/log function
// correctly.
func TestStatusLocalLogs(t *testing.T) {
defer leaktest.AfterTest(t)()
if log.V(3) {
skip.IgnoreLint(t, "Test only works with low verbosity levels")
}
s := log.ScopeWithoutShowLogs(t)
defer s.Close(t)
ts := startServer(t)
defer ts.Stopper().Stop(context.Background())
// Log an error of each main type which we expect to be able to retrieve.
// The resolution of our log timestamps is such that it's possible to get
// two subsequent log messages with the same timestamp. This test will fail
// when that occurs. By adding a small sleep in here after each timestamp to
// ensures this isn't the case and that the log filtering doesn't filter out
// the log entires we're looking for. The value of 20 μs was chosen because
// the log timestamps have a fidelity of 10 μs and thus doubling that should
// be a sufficient buffer.
// See util/log/clog.go formatHeader() for more details.
const sleepBuffer = time.Microsecond * 20
timestamp := timeutil.Now().UnixNano()
time.Sleep(sleepBuffer)
log.Errorf(context.Background(), "TestStatusLocalLogFile test message-Error")
time.Sleep(sleepBuffer)
timestampE := timeutil.Now().UnixNano()
time.Sleep(sleepBuffer)
log.Warningf(context.Background(), "TestStatusLocalLogFile test message-Warning")
time.Sleep(sleepBuffer)
timestampEW := timeutil.Now().UnixNano()
time.Sleep(sleepBuffer)
log.Infof(context.Background(), "TestStatusLocalLogFile test message-Info")
time.Sleep(sleepBuffer)
timestampEWI := timeutil.Now().UnixNano()
var wrapper serverpb.LogFilesListResponse
if err := getStatusJSONProto(ts, "logfiles/local", &wrapper); err != nil {
t.Fatal(err)
}
if a, e := len(wrapper.Files), 1; a != e {
t.Fatalf("expected %d log files; got %d", e, a)
}
// Check each individual log can be fetched and is non-empty.
var foundInfo, foundWarning, foundError bool
for _, file := range wrapper.Files {
var wrapper serverpb.LogEntriesResponse
if err := getStatusJSONProto(ts, "logfiles/local/"+file.Name, &wrapper); err != nil {
t.Fatal(err)
}
for _, entry := range wrapper.Entries {
switch strings.TrimSpace(entry.Message) {
case "TestStatusLocalLogFile test message-Error":
foundError = true
case "TestStatusLocalLogFile test message-Warning":
foundWarning = true
case "TestStatusLocalLogFile test message-Info":
foundInfo = true
}
}
}
if !(foundInfo && foundWarning && foundError) {
t.Errorf("expected to find test messages in %v", wrapper.Files)
}
type levelPresence struct {
Error, Warning, Info bool
}
testCases := []struct {
MaxEntities int
StartTimestamp int64
EndTimestamp int64
Pattern string
levelPresence
}{
// Test filtering by log severity.
// // Test entry limit. Ignore Info/Warning/Error filters.
{1, timestamp, timestampEWI, "", levelPresence{false, false, false}},
{2, timestamp, timestampEWI, "", levelPresence{false, false, false}},
{3, timestamp, timestampEWI, "", levelPresence{false, false, false}},
// Test filtering in different timestamp windows.
{0, timestamp, timestamp, "", levelPresence{false, false, false}},
{0, timestamp, timestampE, "", levelPresence{true, false, false}},
{0, timestampE, timestampEW, "", levelPresence{false, true, false}},
{0, timestampEW, timestampEWI, "", levelPresence{false, false, true}},
{0, timestamp, timestampEW, "", levelPresence{true, true, false}},
{0, timestampE, timestampEWI, "", levelPresence{false, true, true}},
{0, timestamp, timestampEWI, "", levelPresence{true, true, true}},
// Test filtering by regexp pattern.
{0, 0, 0, "Info", levelPresence{false, false, true}},
{0, 0, 0, "Warning", levelPresence{false, true, false}},
{0, 0, 0, "Error", levelPresence{true, false, false}},
{0, 0, 0, "Info|Error|Warning", levelPresence{true, true, true}},
{0, 0, 0, "Nothing", levelPresence{false, false, false}},
}
for i, testCase := range testCases {
var url bytes.Buffer
fmt.Fprintf(&url, "logs/local?level=")
if testCase.MaxEntities > 0 {
fmt.Fprintf(&url, "&max=%d", testCase.MaxEntities)
}
if testCase.StartTimestamp > 0 {
fmt.Fprintf(&url, "&start_time=%d", testCase.StartTimestamp)
}
if testCase.StartTimestamp > 0 {
fmt.Fprintf(&url, "&end_time=%d", testCase.EndTimestamp)
}
if len(testCase.Pattern) > 0 {
fmt.Fprintf(&url, "&pattern=%s", testCase.Pattern)
}
var wrapper serverpb.LogEntriesResponse
path := url.String()
if err := getStatusJSONProto(ts, path, &wrapper); err != nil {
t.Fatal(err)
}
if testCase.MaxEntities > 0 {
if a, e := len(wrapper.Entries), testCase.MaxEntities; a != e {
t.Errorf("%d expected %d entries, got %d: \n%+v", i, e, a, wrapper.Entries)
}
} else {
var actual levelPresence
var logsBuf bytes.Buffer
for _, entry := range wrapper.Entries {
fmt.Fprintln(&logsBuf, entry.Message)
switch strings.TrimSpace(entry.Message) {
case "TestStatusLocalLogFile test message-Error":
actual.Error = true
case "TestStatusLocalLogFile test message-Warning":
actual.Warning = true
case "TestStatusLocalLogFile test message-Info":
actual.Info = true
}
}
if testCase.levelPresence != actual {
t.Errorf("%d: expected %+v at %s, got:\n%s", i, testCase, path, logsBuf.String())
}
}
}
}
// TestStatusLogRedaction checks that the log file retrieval RPCs
// honor the redaction flags.
func TestStatusLogRedaction(t *testing.T) {
defer leaktest.AfterTest(t)()
testData := []struct {
redactableLogs bool // logging flag
redact bool // RPC request flag
expectedMessage string
expectedRedactable bool // redactable bit in result entries
}{
// Note: all combinations of (redactableLogs, redact) must be tested below.
// If there were no markers to start with (redactableLogs=false), we
// introduce markers around the entire message to indicate it's not known to
// be safe.
{false, false, `‹ THISISSAFE THISISUNSAFE›`, true},
// redact=true must be conservative and redact everything out if
// there were no markers to start with (redactableLogs=false).
{false, true, `‹×›`, false},
// redact=false keeps whatever was in the log file.
{true, false, ` THISISSAFE ‹THISISUNSAFE›`, true},
// Whether or not to keep the redactable markers has no influence
// on the output of redaction, just on the presence of the
// "redactable" marker. In any case no information is leaked.
{true, true, ` THISISSAFE ‹×›`, true},
}
testutils.RunTrueAndFalse(t, "redactableLogs",
func(t *testing.T, redactableLogs bool) {
s := log.ScopeWithoutShowLogs(t)
defer s.Close(t)
// Apply the redactable log boolean for this test.
defer log.TestingSetRedactable(redactableLogs)()
ts := startServer(t)
defer ts.Stopper().Stop(context.Background())
// Log something.
log.Infof(context.Background(), "THISISSAFE %s", "THISISUNSAFE")
// Determine the log file name.
var wrapper serverpb.LogFilesListResponse
if err := getStatusJSONProto(ts, "logfiles/local", &wrapper); err != nil {
t.Fatal(err)
}
// We expect only the main log.
if a, e := len(wrapper.Files), 1; a != e {
t.Fatalf("expected %d log files; got %d: %+v", e, a, wrapper.Files)
}
file := wrapper.Files[0]
// Assert that the log that's present is not a stderr log.
if strings.Contains("stderr", file.Name) {
t.Fatalf("expected main log, found %v", file.Name)
}
for _, tc := range testData {
if tc.redactableLogs != redactableLogs {
continue
}
t.Run(fmt.Sprintf("redact=%v", tc.redact),
func(t *testing.T) {
// checkEntries asserts that the redaction results are
// those expected in tc.
checkEntries := func(entries []logpb.Entry) {
foundMessage := false
for _, entry := range entries {
if !strings.HasSuffix(entry.File, "status_test.go") {
continue
}
foundMessage = true
assert.Equal(t, tc.expectedMessage, entry.Message)
}
if !foundMessage {
t.Fatalf("did not find expected message from test in log")
}
}
// Retrieve the log entries with the configured flags using
// the LogFiles() RPC.
logFilesURL := fmt.Sprintf("logfiles/local/%s?redact=%v", file.Name, tc.redact)
var wrapper serverpb.LogEntriesResponse
if err := getStatusJSONProto(ts, logFilesURL, &wrapper); err != nil {
t.Fatal(err)
}
checkEntries(wrapper.Entries)
// If the test specifies redact=false, check that a non-admin
// user gets a privilege error.
if !tc.redact {
err := getStatusJSONProtoWithAdminOption(ts, logFilesURL, &wrapper, false /* isAdmin */)
if !testutils.IsError(err, "status: 403") {
t.Fatalf("expected privilege error, got %v", err)
}
}
// Retrieve the log entries using the Logs() RPC.
logsURL := fmt.Sprintf("logs/local?redact=%v", tc.redact)
var wrapper2 serverpb.LogEntriesResponse
if err := getStatusJSONProto(ts, logsURL, &wrapper2); err != nil {
t.Fatal(err)
}
checkEntries(wrapper2.Entries)
// If the test specifies redact=false, check that a non-admin
// user gets a privilege error.
if !tc.redact {
err := getStatusJSONProtoWithAdminOption(ts, logsURL, &wrapper2, false /* isAdmin */)
if !testutils.IsError(err, "status: 403") {
t.Fatalf("expected privilege error, got %v", err)
}
}
})
}
})
}
// TestNodeStatusResponse verifies that node status returns the expected
// results.
func TestNodeStatusResponse(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := startServer(t)
defer s.Stopper().Stop(context.Background())
// First fetch all the node statuses.
wrapper := serverpb.NodesResponse{}
if err := getStatusJSONProto(s, "nodes", &wrapper); err != nil {
t.Fatal(err)
}
nodeStatuses := wrapper.Nodes
if len(nodeStatuses) != 1 {
t.Errorf("too many node statuses returned - expected:1 actual:%d", len(nodeStatuses))
}
if !s.node.Descriptor.Equal(&nodeStatuses[0].Desc) {
t.Errorf("node status descriptors are not equal\nexpected:%+v\nactual:%+v\n", s.node.Descriptor, nodeStatuses[0].Desc)
}
// Now fetch each one individually. Loop through the nodeStatuses to use the
// ids only.
for _, oldNodeStatus := range nodeStatuses {
nodeStatus := statuspb.NodeStatus{}
if err := getStatusJSONProto(s, "nodes/"+oldNodeStatus.Desc.NodeID.String(), &nodeStatus); err != nil {
t.Fatal(err)
}
if !s.node.Descriptor.Equal(&nodeStatus.Desc) {
t.Errorf("node status descriptors are not equal\nexpected:%+v\nactual:%+v\n", s.node.Descriptor, nodeStatus.Desc)
}
}
}
// TestMetricsRecording verifies that Node statistics are periodically recorded
// as time series data.
func TestMetricsRecording(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
s, _, kvDB := serverutils.StartServer(t, base.TestServerArgs{})
defer s.Stopper().Stop(ctx)
// Verify that metrics for the current timestamp are recorded. This should
// be true very quickly even though DefaultMetricsSampleInterval is large,
// because the server writes an entry eagerly on startup.
testutils.SucceedsSoon(t, func() error {
now := s.Clock().PhysicalNow()
var data roachpb.InternalTimeSeriesData
for _, keyName := range []string{
"cr.store.livebytes.1",
"cr.node.sys.go.allocbytes.1",
} {
key := ts.MakeDataKey(keyName, "", ts.Resolution10s, now)
if err := kvDB.GetProto(ctx, key, &data); err != nil {
return err
}
}
return nil
})
}
// TestMetricsEndpoint retrieves the metrics endpoint, which is currently only
// used for development purposes. The metrics within the response are verified
// in other tests.
func TestMetricsEndpoint(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := startServer(t)
defer s.Stopper().Stop(context.Background())
if _, err := getText(s, s.AdminURL()+statusPrefix+"metrics/"+s.Gossip().NodeID.String()); err != nil {
t.Fatal(err)
}
}
// TestMetricsMetadata ensures that the server's recorder return metrics and
// that each metric has a Name, Help, Unit, and DisplayUnit defined.
func TestMetricsMetadata(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := startServer(t)
defer s.Stopper().Stop(context.Background())
metricsMetadata := s.recorder.GetMetricsMetadata()
if len(metricsMetadata) < 200 {
t.Fatal("s.recorder.GetMetricsMetadata() failed sanity check; didn't return enough metrics.")
}
for _, v := range metricsMetadata {
if v.Name == "" {
t.Fatal("metric missing name.")
}
if v.Help == "" {
t.Fatalf("%s missing Help.", v.Name)
}
if v.Measurement == "" {
t.Fatalf("%s missing Measurement.", v.Name)
}
if v.Unit == 0 {
t.Fatalf("%s missing Unit.", v.Name)
}
}
}
// TestChartCatalog ensures that the server successfully generates the chart catalog.
func TestChartCatalogGen(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := startServer(t)
defer s.Stopper().Stop(context.Background())
metricsMetadata := s.recorder.GetMetricsMetadata()
chartCatalog, err := catalog.GenerateCatalog(metricsMetadata)
if err != nil {
t.Fatal(err)
}
// Ensure each of the 8 constant sections of the chart catalog exist.
if len(chartCatalog) != 8 {
t.Fatal("Chart catalog failed to generate.")
}
for _, section := range chartCatalog {
// Ensure that one of the chartSections has defined Subsections.
if len(section.Subsections) == 0 {
t.Fatalf(`Chart catalog has missing subsections in %v`, section)
}
}
}
// findUndefinedMetrics finds metrics listed in pkg/ts/catalog/chart_catalog.go
// that are not defined. This is most likely caused by a metric being removed.
func findUndefinedMetrics(c *catalog.ChartSection, metadata map[string]metric.Metadata) []string {
var undefinedMetrics []string
for _, ic := range c.Charts {
for _, metric := range ic.Metrics {
_, ok := metadata[metric.Name]
if !ok {
undefinedMetrics = append(undefinedMetrics, metric.Name)
}
}
}
for _, x := range c.Subsections {
undefinedMetrics = append(undefinedMetrics, findUndefinedMetrics(x, metadata)...)
}
return undefinedMetrics
}
// deleteSeenMetrics removes all metrics in a section from the metricMetadata map.
func deleteSeenMetrics(c *catalog.ChartSection, metadata map[string]metric.Metadata, t *testing.T) {
// if c.Title == "SQL" {
// t.Log(c)
// }
for _, x := range c.Charts {
if x.Title == "Connections" || x.Title == "Byte I/O" {
t.Log(x)
}
for _, metric := range x.Metrics {
if metric.Name == "sql.new_conns" || metric.Name == "sql.bytesin" {
t.Logf("found %v\n", metric.Name)
}
_, ok := metadata[metric.Name]
if ok {
delete(metadata, metric.Name)
}
}
}
for _, x := range c.Subsections {
deleteSeenMetrics(x, metadata, t)
}
}
// TestChartCatalogMetric ensures that all metrics are included in at least one
// chart, and that every metric included in a chart is still part of the metrics
// registry.
func TestChartCatalogMetrics(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := startServer(t)
defer s.Stopper().Stop(context.Background())
metricsMetadata := s.recorder.GetMetricsMetadata()
chartCatalog, err := catalog.GenerateCatalog(metricsMetadata)
if err != nil {
t.Fatal(err)
}
// Each metric referenced in the chartCatalog must have a definition in metricsMetadata
var undefinedMetrics []string
for _, cs := range chartCatalog {
undefinedMetrics = append(undefinedMetrics, findUndefinedMetrics(&cs, metricsMetadata)...)
}
if len(undefinedMetrics) > 0 {
t.Fatalf(`The following metrics need are no longer present and need to be removed
from the chart catalog (pkg/ts/catalog/chart_catalog.go):%v`, undefinedMetrics)
}
// Each metric in metricsMetadata should have at least one entry in
// chartCatalog, which we track by deleting the metric from metricsMetadata.
for _, v := range chartCatalog {
deleteSeenMetrics(&v, metricsMetadata, t)
}
if len(metricsMetadata) > 0 {
var metricNames []string
for metricName := range metricsMetadata {