-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
flush.go
643 lines (556 loc) · 19.2 KB
/
flush.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
// 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 persistedsqlstats
import (
"context"
"time"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security/username"
"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/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
)
// Flush flushes in-memory sql stats into system table. Any errors encountered
// during the flush will be logged as warning.
func (s *PersistedSQLStats) Flush(ctx context.Context) {
now := s.getTimeNow()
allowDiscardWhenDisabled := DiscardInMemoryStatsWhenFlushDisabled.Get(&s.cfg.Settings.SV)
minimumFlushInterval := MinimumInterval.Get(&s.cfg.Settings.SV)
enabled := SQLStatsFlushEnabled.Get(&s.cfg.Settings.SV)
flushingTooSoon := now.Before(s.lastFlushStarted.Add(minimumFlushInterval))
// Handle wiping in-memory stats here, we only wipe in-memory stats under 2
// circumstances:
// 1. flush is enabled, and we are not early aborting the flush due to flushing
// too frequently.
// 2. flush is disabled, but we allow discard in-memory stats when disabled.
shouldWipeInMemoryStats := enabled && !flushingTooSoon
shouldWipeInMemoryStats = shouldWipeInMemoryStats || (!enabled && allowDiscardWhenDisabled)
if shouldWipeInMemoryStats {
defer func() {
if err := s.SQLStats.Reset(ctx); err != nil {
log.Warningf(ctx, "fail to reset in-memory SQL Stats: %s", err)
}
}()
}
// Handle early abortion of the flush.
if !enabled {
return
}
if flushingTooSoon {
log.Infof(ctx, "flush aborted due to high flush frequency. "+
"The minimum interval between flushes is %s", minimumFlushInterval.String())
return
}
s.lastFlushStarted = now
log.Infof(ctx, "flushing %d stmt/txn fingerprints (%d bytes) after %s",
s.SQLStats.GetTotalFingerprintCount(), s.SQLStats.GetTotalFingerprintBytes(), timeutil.Since(s.lastFlushStarted))
aggregatedTs := s.ComputeAggregatedTs()
s.flushStmtStats(ctx, aggregatedTs)
s.flushTxnStats(ctx, aggregatedTs)
}
func (s *PersistedSQLStats) flushStmtStats(ctx context.Context, aggregatedTs time.Time) {
// s.doFlush directly logs errors if they are encountered. Therefore,
// no error is returned here.
_ = s.SQLStats.IterateStatementStats(ctx, &sqlstats.IteratorOptions{},
func(ctx context.Context, statistics *roachpb.CollectedStatementStatistics) error {
s.doFlush(ctx, func() error {
return s.doFlushSingleStmtStats(ctx, statistics, aggregatedTs)
}, "failed to flush statement statistics" /* errMsg */)
return nil
})
if s.cfg.Knobs != nil && s.cfg.Knobs.OnStmtStatsFlushFinished != nil {
s.cfg.Knobs.OnStmtStatsFlushFinished()
}
}
func (s *PersistedSQLStats) flushTxnStats(ctx context.Context, aggregatedTs time.Time) {
_ = s.SQLStats.IterateTransactionStats(ctx, &sqlstats.IteratorOptions{},
func(ctx context.Context, statistics *roachpb.CollectedTransactionStatistics) error {
s.doFlush(ctx, func() error {
return s.doFlushSingleTxnStats(ctx, statistics, aggregatedTs)
}, "failed to flush transaction statistics" /* errMsg */)
return nil
})
if s.cfg.Knobs != nil && s.cfg.Knobs.OnTxnStatsFlushFinished != nil {
s.cfg.Knobs.OnTxnStatsFlushFinished()
}
}
func (s *PersistedSQLStats) doFlush(ctx context.Context, workFn func() error, errMsg string) {
var err error
flushBegin := s.getTimeNow()
defer func() {
if err != nil {
s.cfg.FailureCounter.Inc(1)
log.Warningf(ctx, "%s: %s", errMsg, err)
}
flushDuration := s.getTimeNow().Sub(flushBegin)
s.cfg.FlushDuration.RecordValue(flushDuration.Nanoseconds())
s.cfg.FlushCounter.Inc(1)
}()
err = workFn()
}
func (s *PersistedSQLStats) doFlushSingleTxnStats(
ctx context.Context, stats *roachpb.CollectedTransactionStatistics, aggregatedTs time.Time,
) error {
return s.cfg.KvDB.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
// Explicitly copy the stats variable so the txn closure is retryable.
scopedStats := *stats
serializedFingerprintID := sqlstatsutil.EncodeUint64ToBytes(uint64(stats.TransactionFingerprintID))
insertFn := func(ctx context.Context, txn *kv.Txn) (alreadyExists bool, err error) {
rowsAffected, err := s.insertTransactionStats(ctx, txn, aggregatedTs, serializedFingerprintID, &scopedStats)
if err != nil {
return false /* alreadyExists */, err
}
if rowsAffected == 0 {
return true /* alreadyExists */, nil /* err */
}
return false /* alreadyExists */, nil /* err */
}
readFn := func(ctx context.Context, txn *kv.Txn) error {
persistedData := roachpb.TransactionStatistics{}
err := s.fetchPersistedTransactionStats(ctx, txn, aggregatedTs, serializedFingerprintID, scopedStats.App, &persistedData)
if err != nil {
return err
}
scopedStats.Stats.Add(&persistedData)
return nil
}
updateFn := func(ctx context.Context, txn *kv.Txn) error {
return s.updateTransactionStats(ctx, txn, aggregatedTs, serializedFingerprintID, &scopedStats)
}
err := s.doInsertElseDoUpdate(ctx, txn, insertFn, readFn, updateFn)
if err != nil {
return errors.Wrapf(err, "flushing transaction %d's statistics", stats.TransactionFingerprintID)
}
return nil
})
}
func (s *PersistedSQLStats) doFlushSingleStmtStats(
ctx context.Context, stats *roachpb.CollectedStatementStatistics, aggregatedTs time.Time,
) error {
return s.cfg.KvDB.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
// Explicitly copy the stats so that this closure is retryable.
scopedStats := *stats
serializedFingerprintID := sqlstatsutil.EncodeUint64ToBytes(uint64(scopedStats.ID))
serializedTransactionFingerprintID := sqlstatsutil.EncodeUint64ToBytes(uint64(scopedStats.Key.TransactionFingerprintID))
serializedPlanHash := sqlstatsutil.EncodeUint64ToBytes(scopedStats.Key.PlanHash)
insertFn := func(ctx context.Context, txn *kv.Txn) (alreadyExists bool, err error) {
rowsAffected, err := s.insertStatementStats(
ctx,
txn,
aggregatedTs,
serializedFingerprintID,
serializedTransactionFingerprintID,
serializedPlanHash,
&scopedStats,
)
if err != nil {
return false /* alreadyExists */, err
}
if rowsAffected == 0 {
return true /* alreadyExists */, nil /* err */
}
return false /* alreadyExists */, nil /* err */
}
readFn := func(ctx context.Context, txn *kv.Txn) error {
persistedData := roachpb.StatementStatistics{}
err := s.fetchPersistedStatementStats(
ctx,
txn,
aggregatedTs,
serializedFingerprintID,
serializedTransactionFingerprintID,
serializedPlanHash,
&scopedStats.Key,
&persistedData,
)
if err != nil {
return err
}
scopedStats.Stats.Add(&persistedData)
return nil
}
updateFn := func(ctx context.Context, txn *kv.Txn) error {
return s.updateStatementStats(
ctx,
txn,
aggregatedTs,
serializedFingerprintID,
serializedTransactionFingerprintID,
serializedPlanHash,
&scopedStats,
)
}
err := s.doInsertElseDoUpdate(ctx, txn, insertFn, readFn, updateFn)
if err != nil {
return errors.Wrapf(err, "flush statement %d's statistics", scopedStats.ID)
}
return nil
})
}
func (s *PersistedSQLStats) doInsertElseDoUpdate(
ctx context.Context,
txn *kv.Txn,
insertFn func(context.Context, *kv.Txn) (alreadyExists bool, err error),
readFn func(context.Context, *kv.Txn) error,
updateFn func(context.Context, *kv.Txn) error,
) error {
alreadyExists, err := insertFn(ctx, txn)
if err != nil {
return err
}
if alreadyExists {
err = readFn(ctx, txn)
if err != nil {
return err
}
err = updateFn(ctx, txn)
if err != nil {
return err
}
}
return nil
}
// ComputeAggregatedTs returns the aggregation timestamp to assign
// in-memory SQL stats during storage or aggregation.
func (s *PersistedSQLStats) ComputeAggregatedTs() time.Time {
interval := SQLStatsAggregationInterval.Get(&s.cfg.Settings.SV)
now := s.getTimeNow()
aggTs := now.Truncate(interval)
return aggTs
}
// GetAggregationInterval returns the current aggregation interval
// used by PersistedSQLStats.
func (s *PersistedSQLStats) GetAggregationInterval() time.Duration {
return SQLStatsAggregationInterval.Get(&s.cfg.Settings.SV)
}
func (s *PersistedSQLStats) getTimeNow() time.Time {
if s.cfg.Knobs != nil && s.cfg.Knobs.StubTimeNow != nil {
return s.cfg.Knobs.StubTimeNow()
}
return timeutil.Now()
}
func (s *PersistedSQLStats) insertTransactionStats(
ctx context.Context,
txn *kv.Txn,
aggregatedTs time.Time,
serializedFingerprintID []byte,
stats *roachpb.CollectedTransactionStatistics,
) (rowsAffected int, err error) {
insertStmt := `
INSERT INTO system.transaction_statistics
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (crdb_internal_aggregated_ts_app_name_fingerprint_id_node_id_shard_8, aggregated_ts, fingerprint_id, app_name, node_id)
DO NOTHING
`
aggInterval := s.GetAggregationInterval()
// Prepare data for insertion.
metadataJSON, err := sqlstatsutil.BuildTxnMetadataJSON(stats)
if err != nil {
return 0 /* rowsAffected */, err
}
metadata := tree.NewDJSON(metadataJSON)
statisticsJSON, err := sqlstatsutil.BuildTxnStatisticsJSON(stats)
if err != nil {
return 0 /* rowsAffected */, err
}
statistics := tree.NewDJSON(statisticsJSON)
rowsAffected, err = s.cfg.InternalExecutor.ExecEx(
ctx,
"insert-txn-stats",
txn, /* txn */
sessiondata.InternalExecutorOverride{
User: username.NodeUserName(),
},
insertStmt,
aggregatedTs, // aggregated_ts
serializedFingerprintID, // fingerprint_id
stats.App, // app_name
s.cfg.SQLIDContainer.SQLInstanceID(), // node_id
aggInterval, // agg_interval
metadata, // metadata
statistics, // statistics
)
return rowsAffected, err
}
func (s *PersistedSQLStats) updateTransactionStats(
ctx context.Context,
txn *kv.Txn,
aggregatedTs time.Time,
serializedFingerprintID []byte,
stats *roachpb.CollectedTransactionStatistics,
) error {
updateStmt := `
UPDATE system.transaction_statistics
SET statistics = $1
WHERE fingerprint_id = $2
AND aggregated_ts = $3
AND app_name = $4
AND node_id = $5
`
statisticsJSON, err := sqlstatsutil.BuildTxnStatisticsJSON(stats)
if err != nil {
return err
}
statistics := tree.NewDJSON(statisticsJSON)
rowsAffected, err := s.cfg.InternalExecutor.ExecEx(
ctx,
"update-stmt-stats",
txn, /* txn */
sessiondata.InternalExecutorOverride{
User: username.NodeUserName(),
},
updateStmt,
statistics, // statistics
serializedFingerprintID, // fingerprint_id
aggregatedTs, // aggregated_ts
stats.App, // app_name
s.cfg.SQLIDContainer.SQLInstanceID(), // node_id
)
if err != nil {
return err
}
if rowsAffected == 0 {
return errors.AssertionFailedf("failed to update transaction statistics for fingerprint_id: %s, app: %s, aggregated_ts: %s, node_id: %d",
serializedFingerprintID, stats.App, aggregatedTs,
s.cfg.SQLIDContainer.SQLInstanceID())
}
return nil
}
func (s *PersistedSQLStats) updateStatementStats(
ctx context.Context,
txn *kv.Txn,
aggregatedTs time.Time,
serializedFingerprintID []byte,
serializedTransactionFingerprintID []byte,
serializedPlanHash []byte,
stats *roachpb.CollectedStatementStatistics,
) error {
updateStmt := `
UPDATE system.statement_statistics
SET statistics = $1,
index_recommendations = $2
WHERE fingerprint_id = $3
AND transaction_fingerprint_id = $4
AND aggregated_ts = $5
AND app_name = $6
AND plan_hash = $7
AND node_id = $8
`
statisticsJSON, err := sqlstatsutil.BuildStmtStatisticsJSON(&stats.Stats)
if err != nil {
return err
}
statistics := tree.NewDJSON(statisticsJSON)
indexRecommendations := tree.NewDArray(types.String)
for _, recommendation := range stats.Stats.IndexRecommendations {
if err := indexRecommendations.Append(tree.NewDString(recommendation)); err != nil {
return err
}
}
rowsAffected, err := s.cfg.InternalExecutor.ExecEx(
ctx,
"update-stmt-stats",
txn, /* txn */
sessiondata.InternalExecutorOverride{
User: username.NodeUserName(),
},
updateStmt,
statistics, // statistics
indexRecommendations, // index_recommendations
serializedFingerprintID, // fingerprint_id
serializedTransactionFingerprintID, // transaction_fingerprint_id
aggregatedTs, // aggregated_ts
stats.Key.App, // app_name
serializedPlanHash, // plan_hash
s.cfg.SQLIDContainer.SQLInstanceID(), // node_id
)
if err != nil {
return err
}
if rowsAffected == 0 {
return errors.AssertionFailedf("failed to update statement statistics "+
"for fingerprint_id: %s, "+
"transaction_fingerprint_id: %s, "+
"app: %s, "+
"aggregated_ts: %s, "+
"plan_hash: %d, "+
"node_id: %d",
serializedFingerprintID, serializedTransactionFingerprintID, stats.Key.App,
aggregatedTs, serializedPlanHash, s.cfg.SQLIDContainer.SQLInstanceID())
}
return nil
}
func (s *PersistedSQLStats) insertStatementStats(
ctx context.Context,
txn *kv.Txn,
aggregatedTs time.Time,
serializedFingerprintID []byte,
serializedTransactionFingerprintID []byte,
serializedPlanHash []byte,
stats *roachpb.CollectedStatementStatistics,
) (rowsAffected int, err error) {
insertStmt := `
INSERT INTO system.statement_statistics
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
ON CONFLICT (crdb_internal_aggregated_ts_app_name_fingerprint_id_node_id_plan_hash_transaction_fingerprint_id_shard_8,
aggregated_ts, fingerprint_id, transaction_fingerprint_id, app_name, plan_hash, node_id)
DO NOTHING
`
aggInterval := s.GetAggregationInterval()
// Prepare data for insertion.
metadataJSON, err := sqlstatsutil.BuildStmtMetadataJSON(stats)
if err != nil {
return 0 /* rowsAffected */, err
}
metadata := tree.NewDJSON(metadataJSON)
statisticsJSON, err := sqlstatsutil.BuildStmtStatisticsJSON(&stats.Stats)
if err != nil {
return 0 /* rowsAffected */, err
}
statistics := tree.NewDJSON(statisticsJSON)
plan := tree.NewDJSON(sqlstatsutil.ExplainTreePlanNodeToJSON(&stats.Stats.SensitiveInfo.MostRecentPlanDescription))
indexRecommendations := tree.NewDArray(types.String)
for _, recommendation := range stats.Stats.IndexRecommendations {
if err := indexRecommendations.Append(tree.NewDString(recommendation)); err != nil {
return 0, err
}
}
rowsAffected, err = s.cfg.InternalExecutor.ExecEx(
ctx,
"insert-stmt-stats",
txn, /* txn */
sessiondata.InternalExecutorOverride{
User: username.NodeUserName(),
},
insertStmt,
aggregatedTs, // aggregated_ts
serializedFingerprintID, // fingerprint_id
serializedTransactionFingerprintID, // transaction_fingerprint_id
serializedPlanHash, // plan_hash
stats.Key.App, // app_name
s.cfg.SQLIDContainer.SQLInstanceID(), // node_id
aggInterval, // agg_interval
metadata, // metadata
statistics, // statistics
plan, // plan
indexRecommendations, // index_recommendations
)
return rowsAffected, err
}
func (s *PersistedSQLStats) fetchPersistedTransactionStats(
ctx context.Context,
txn *kv.Txn,
aggregatedTs time.Time,
serializedFingerprintID []byte,
appName string,
result *roachpb.TransactionStatistics,
) error {
// We use `SELECT ... FOR UPDATE` statement because we are going to perform
// and `UPDATE` on the stats for the given fingerprint later.
readStmt := `
SELECT
statistics
FROM
system.transaction_statistics
WHERE fingerprint_id = $1
AND app_name = $2
AND aggregated_ts = $3
AND node_id = $4
FOR UPDATE
`
row, err := s.cfg.InternalExecutor.QueryRowEx(
ctx,
"fetch-txn-stats",
txn, /* txn */
sessiondata.InternalExecutorOverride{
User: username.NodeUserName(),
},
readStmt, // stmt
serializedFingerprintID, // fingerprint_id
appName, // app_name
aggregatedTs, // aggregated_ts
s.cfg.SQLIDContainer.SQLInstanceID(), // node_id
)
if err != nil {
return err
}
if row == nil {
return errors.AssertionFailedf("transaction statistics not found for fingerprint_id: %s, app: %s, aggregated_ts: %s, node_id: %d",
serializedFingerprintID, appName, aggregatedTs,
s.cfg.SQLIDContainer.SQLInstanceID())
}
if len(row) != 1 {
return errors.AssertionFailedf("unexpectedly found %d returning columns for fingerprint_id: %s, app: %s, aggregated_ts: %s, node_id: %d",
len(row), serializedFingerprintID, appName, aggregatedTs,
s.cfg.SQLIDContainer.SQLInstanceID())
}
statistics := tree.MustBeDJSON(row[0])
return sqlstatsutil.DecodeTxnStatsStatisticsJSON(statistics.JSON, result)
}
func (s *PersistedSQLStats) fetchPersistedStatementStats(
ctx context.Context,
txn *kv.Txn,
aggregatedTs time.Time,
serializedFingerprintID []byte,
serializedTransactionFingerprintID []byte,
serializedPlanHash []byte,
key *roachpb.StatementStatisticsKey,
result *roachpb.StatementStatistics,
) error {
readStmt := `
SELECT
statistics
FROM
system.statement_statistics
WHERE fingerprint_id = $1
AND transaction_fingerprint_id = $2
AND app_name = $3
AND aggregated_ts = $4
AND plan_hash = $5
AND node_id = $6
FOR UPDATE
`
row, err := s.cfg.InternalExecutor.QueryRowEx(
ctx,
"fetch-stmt-stats",
txn, /* txn */
sessiondata.InternalExecutorOverride{
User: username.NodeUserName(),
},
readStmt, // stmt
serializedFingerprintID, // fingerprint_id
serializedTransactionFingerprintID, // transaction_fingerprint_id
key.App, // app_name
aggregatedTs, // aggregated_ts
serializedPlanHash, // plan_hash
s.cfg.SQLIDContainer.SQLInstanceID(), // node_id
)
if err != nil {
return err
}
if row == nil {
return errors.AssertionFailedf(
"statement statistics not found fingerprint_id: %s, app: %s, aggregated_ts: %s, plan_hash: %d, node_id: %d",
serializedFingerprintID, key.App, aggregatedTs, serializedPlanHash, s.cfg.SQLIDContainer.SQLInstanceID())
}
if len(row) != 1 {
return errors.AssertionFailedf("unexpectedly found %d returning columns for fingerprint_id: %s, app: %s, aggregated_ts: %s, plan_hash %d, node_id: %d",
len(row), serializedFingerprintID, key.App, aggregatedTs, serializedPlanHash,
s.cfg.SQLIDContainer.SQLInstanceID())
}
statistics := tree.MustBeDJSON(row[0])
return sqlstatsutil.DecodeStmtStatsStatisticsJSON(statistics.JSON, result)
}