-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
statement_diagnostics_test.go
286 lines (256 loc) · 9.87 KB
/
statement_diagnostics_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
// Copyright 2020 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 stmtdiagnostics_test
import (
"context"
gosql "database/sql"
"fmt"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/systemschema"
"github.com/cockroachdb/cockroach/pkg/sql/stmtdiagnostics"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/stretchr/testify/require"
)
func TestDiagnosticsRequest(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, db, _ := serverutils.StartServer(t, base.TestServerArgs{})
ctx := context.Background()
defer s.Stopper().Stop(ctx)
_, err := db.Exec("CREATE TABLE test (x int PRIMARY KEY)")
require.NoError(t, err)
completedQuery := "SELECT completed, statement_diagnostics_id FROM system.statement_diagnostics_requests WHERE ID = $1"
checkNotCompleted := func(reqID int64) {
reqRow := db.QueryRow(completedQuery, reqID)
var completed bool
var traceID gosql.NullInt64
require.NoError(t, reqRow.Scan(&completed, &traceID))
require.False(t, completed)
require.False(t, traceID.Valid) // traceID should be NULL
}
checkCompleted := func(reqID int64) {
var completed bool
var traceID gosql.NullInt64
traceRow := db.QueryRow(completedQuery, reqID)
require.NoError(t, traceRow.Scan(&completed, &traceID))
require.True(t, completed)
require.True(t, traceID.Valid)
}
registry := s.ExecutorConfig().(sql.ExecutorConfig).StmtDiagnosticsRecorder
var minExecutionLatencyMilliseconds int64
var expiresAfter time.Duration
// Ask to trace a particular query.
t.Run("basic", func(t *testing.T) {
reqID, err := registry.InsertRequestInternal(ctx, "INSERT INTO test VALUES (_)", minExecutionLatencyMilliseconds, expiresAfter)
require.NoError(t, err)
checkNotCompleted(reqID)
// Run the query.
_, err = db.Exec("INSERT INTO test VALUES (1)")
require.NoError(t, err)
// Check that the row from statement_diagnostics_request was marked as
// completed.
checkCompleted(reqID)
})
// Verify that we can handle multiple requests at the same time.
t.Run("multiple", func(t *testing.T) {
id1, err := registry.InsertRequestInternal(ctx, "INSERT INTO test VALUES (_)", minExecutionLatencyMilliseconds, expiresAfter)
require.NoError(t, err)
id2, err := registry.InsertRequestInternal(ctx, "SELECT x FROM test", minExecutionLatencyMilliseconds, expiresAfter)
require.NoError(t, err)
id3, err := registry.InsertRequestInternal(ctx, "SELECT x FROM test WHERE x > _", minExecutionLatencyMilliseconds, expiresAfter)
require.NoError(t, err)
// Run the queries in a different order.
_, err = db.Exec("SELECT x FROM test")
require.NoError(t, err)
checkCompleted(id2)
_, err = db.Exec("SELECT x FROM test WHERE x > 1")
require.NoError(t, err)
checkCompleted(id3)
_, err = db.Exec("INSERT INTO test VALUES (2)")
require.NoError(t, err)
checkCompleted(id1)
})
// Verify that EXECUTE triggers diagnostics collection (#66048).
t.Run("execute", func(t *testing.T) {
id, err := registry.InsertRequestInternal(ctx, "SELECT x + $1 FROM test", minExecutionLatencyMilliseconds, expiresAfter)
require.NoError(t, err)
_, err = db.Exec("PREPARE stmt AS SELECT x + $1 FROM test")
require.NoError(t, err)
_, err = db.Exec("EXECUTE stmt(1)")
require.NoError(t, err)
checkCompleted(id)
})
t.Run("conditional", func(t *testing.T) {
minExecutionLatencyMilliseconds := int64(100)
reqID, err := registry.InsertRequestInternal(ctx, "SELECT pg_sleep(_)", minExecutionLatencyMilliseconds, expiresAfter)
require.NoError(t, err)
checkNotCompleted(reqID)
// Run the fast query.
_, err = db.Exec("SELECT pg_sleep(0)")
require.NoError(t, err)
checkNotCompleted(reqID)
// Run the slow query.
_, err = db.Exec("SELECT pg_sleep(0.2)")
require.NoError(t, err)
checkCompleted(reqID)
})
t.Run("conditional expired", func(t *testing.T) {
minExecutionLatencyMilliseconds := int64(100)
expiresAfter := time.Nanosecond
reqID, err := registry.InsertRequestInternal(ctx, "SELECT pg_sleep(_)", minExecutionLatencyMilliseconds, expiresAfter)
require.NoError(t, err)
checkNotCompleted(reqID)
// Sleep for a bit and then run the slow query.
time.Sleep(100 * time.Millisecond)
_, err = db.Exec("SELECT pg_sleep(0.2)")
require.NoError(t, err)
// The request must have expired by now.
checkNotCompleted(reqID)
})
}
// Test that a different node can service a diagnostics request.
func TestDiagnosticsRequestDifferentNode(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
tc := serverutils.StartNewTestCluster(t, 2, base.TestClusterArgs{})
ctx := context.Background()
defer tc.Stopper().Stop(ctx)
db0 := tc.ServerConn(0)
db1 := tc.ServerConn(1)
_, err := db0.Exec("CREATE TABLE test (x int PRIMARY KEY)")
require.NoError(t, err)
var minExecutionLatencyMilliseconds int64
var expiresAfter time.Duration
// Ask to trace a particular query using node 0.
registry := tc.Server(0).ExecutorConfig().(sql.ExecutorConfig).StmtDiagnosticsRecorder
reqID, err := registry.InsertRequestInternal(ctx, "INSERT INTO test VALUES (_)", minExecutionLatencyMilliseconds, expiresAfter)
require.NoError(t, err)
reqRow := db0.QueryRow(
`SELECT completed, statement_diagnostics_id FROM system.statement_diagnostics_requests
WHERE ID = $1`, reqID)
var completed bool
var traceID gosql.NullInt64
require.NoError(t, reqRow.Scan(&completed, &traceID))
require.False(t, completed)
require.False(t, traceID.Valid) // traceID should be NULL
// Repeatedly run the query through node 1 until we get a trace.
runUntilTraced := func(query string, reqID int64) {
testutils.SucceedsSoon(t, func() error {
// Run the query using node 1.
_, err = db1.Exec(query)
require.NoError(t, err)
// Check that the row from statement_diagnostics_request was marked as completed.
traceRow := db0.QueryRow(
`SELECT completed, statement_diagnostics_id FROM system.statement_diagnostics_requests
WHERE ID = $1`, reqID)
require.NoError(t, traceRow.Scan(&completed, &traceID))
if !completed {
_, err := db0.Exec("DELETE FROM test")
require.NoError(t, err)
return fmt.Errorf("not completed yet")
}
return nil
})
require.True(t, traceID.Valid)
}
runUntilTraced("INSERT INTO test VALUES (1)", reqID)
// Verify that we can handle multiple requests at the same time.
id1, err := registry.InsertRequestInternal(ctx, "INSERT INTO test VALUES (_)", minExecutionLatencyMilliseconds, expiresAfter)
require.NoError(t, err)
id2, err := registry.InsertRequestInternal(ctx, "SELECT x FROM test", minExecutionLatencyMilliseconds, expiresAfter)
require.NoError(t, err)
id3, err := registry.InsertRequestInternal(ctx, "SELECT x FROM test WHERE x > _", minExecutionLatencyMilliseconds, expiresAfter)
require.NoError(t, err)
// Run the queries in a different order.
runUntilTraced("SELECT x FROM test", id2)
runUntilTraced("SELECT x FROM test WHERE x > 1", id3)
runUntilTraced("INSERT INTO test VALUES (2)", id1)
}
// TestChangePollInterval ensures that changing the polling interval takes effect.
func TestChangePollInterval(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
// We'll inject a request filter to detect scans due to the polling.
tableStart := keys.SystemSQLCodec.TablePrefix(uint32(systemschema.StatementDiagnosticsRequestsTable.GetID()))
tableSpan := roachpb.Span{
Key: tableStart,
EndKey: tableStart.PrefixEnd(),
}
var scanState = struct {
syncutil.Mutex
m map[uuid.UUID]struct{}
}{
m: map[uuid.UUID]struct{}{},
}
recordScan := func(id uuid.UUID) {
scanState.Lock()
defer scanState.Unlock()
scanState.m[id] = struct{}{}
}
numScans := func() int {
scanState.Lock()
defer scanState.Unlock()
return len(scanState.m)
}
waitForScans := func(atLeast int) (seen int) {
testutils.SucceedsSoon(t, func() error {
if seen = numScans(); seen < atLeast {
return errors.Errorf("expected at least %d scans, saw %d", atLeast, seen)
}
return nil
})
return seen
}
settings := cluster.MakeTestingClusterSettings()
// Set an extremely long initial polling interval to not hit flakes due to
// server startup taking more than 10s.
stmtdiagnostics.PollingInterval.Override(ctx, &settings.SV, time.Hour)
args := base.TestServerArgs{
Settings: settings,
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
TestingRequestFilter: func(ctx context.Context, request roachpb.BatchRequest) *roachpb.Error {
if request.Txn == nil {
return nil
}
for _, req := range request.Requests {
if scan := req.GetScan(); scan != nil && scan.Span().Overlaps(tableSpan) {
recordScan(request.Txn.ID)
return nil
}
}
return nil
},
},
},
}
s, db, _ := serverutils.StartServer(t, args)
defer s.Stopper().Stop(ctx)
require.Equal(t, 1, waitForScans(1))
time.Sleep(time.Millisecond) // ensure no unexpected scan occur
require.Equal(t, 1, waitForScans(1))
_, err := db.Exec("SET CLUSTER SETTING sql.stmt_diagnostics.poll_interval = '200us'")
require.NoError(t, err)
waitForScans(10) // ensure several scans occur
}