-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
replica_command.go
3718 lines (3413 loc) · 140 KB
/
replica_command.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 2014 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// Author: Spencer Kimball (spencer.kimball@gmail.com)
// Author: Jiang-Ming Yang (jiangming.yang@gmail.com)
// Author: Tobias Schottdorf (tobias.schottdorf@gmail.com)
// Author: Bram Gruneir (bram+code@cockroachlabs.com)
package storage
import (
"bytes"
"crypto/sha512"
"encoding/binary"
"fmt"
"io"
"math"
"reflect"
"sync"
"sync/atomic"
"time"
"github.com/coreos/etcd/raft/raftpb"
"github.com/pkg/errors"
"golang.org/x/net/context"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/storage/engine"
"github.com/cockroachdb/cockroach/pkg/storage/engine/enginepb"
"github.com/cockroachdb/cockroach/pkg/storage/storagebase"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
)
var errTransactionUnsupported = errors.New("not supported within a transaction")
const (
// collectChecksumTimeout controls how long we'll wait to collect a checksum
// for a CheckConsistency request. We need to bound the time that we wait
// because the checksum might never be computed for a replica if that replica
// is caught up via a snapshot and never performs the ComputeChecksum
// operation.
collectChecksumTimeout = 5 * time.Second
)
// CommandArgs contains all the arguments to a command.
// TODO(bdarnell): consider merging with storagebase.FilterArgs (which
// would probably require removing the EvalCtx field due to import order
// constraints).
type CommandArgs struct {
EvalCtx ReplicaEvalContext
Header roachpb.Header
Args roachpb.Request
// If MaxKeys is non-zero, span requests should limit themselves to
// that many keys. Commands using this feature should also set
// NumKeys and ResumeSpan in their responses.
MaxKeys int64
// *Stats should be mutated to reflect any writes made by the command.
Stats *enginepb.MVCCStats
}
// A Command is the implementation of a single request within a BatchRequest.
type Command struct {
// DeclareKeys adds all keys this command touches to the given spanSet.
DeclareKeys func(roachpb.RangeDescriptor, roachpb.Header, roachpb.Request, *SpanSet)
// Eval evaluates a command on the given engine. It should populate
// the supplied response (always a non-nil pointer to the correct
// type) and return special side effects (if any) in the EvalResult.
// If it writes to the engine it should also update
// *CommandArgs.Stats.
Eval func(context.Context, engine.ReadWriter, CommandArgs, roachpb.Response) (EvalResult, error)
}
// DefaultDeclareKeys is the default implementation of Command.DeclareKeys
func DefaultDeclareKeys(
desc roachpb.RangeDescriptor, header roachpb.Header, req roachpb.Request, spans *SpanSet,
) {
if roachpb.IsReadOnly(req) {
spans.Add(SpanReadOnly, req.Header())
} else {
spans.Add(SpanReadWrite, req.Header())
}
if header.Txn != nil && header.Txn.ID != nil {
spans.Add(SpanReadOnly, roachpb.Span{
Key: keys.AbortCacheKey(header.RangeID, *header.Txn.ID),
})
}
if header.ReturnRangeInfo {
spans.Add(SpanReadOnly, roachpb.Span{Key: keys.RangeLeaseKey(header.RangeID)})
spans.Add(SpanReadOnly, roachpb.Span{Key: keys.RangeDescriptorKey(desc.StartKey)})
}
}
var commands = map[roachpb.Method]Command{
roachpb.Get: {DeclareKeys: DefaultDeclareKeys, Eval: evalGet},
roachpb.Put: {DeclareKeys: DefaultDeclareKeys, Eval: evalPut},
roachpb.ConditionalPut: {DeclareKeys: DefaultDeclareKeys, Eval: evalConditionalPut},
roachpb.InitPut: {DeclareKeys: DefaultDeclareKeys, Eval: evalInitPut},
roachpb.Increment: {DeclareKeys: DefaultDeclareKeys, Eval: evalIncrement},
roachpb.Delete: {DeclareKeys: DefaultDeclareKeys, Eval: evalDelete},
roachpb.DeleteRange: {DeclareKeys: DefaultDeclareKeys, Eval: evalDeleteRange},
roachpb.Scan: {DeclareKeys: DefaultDeclareKeys, Eval: evalScan},
roachpb.ReverseScan: {DeclareKeys: DefaultDeclareKeys, Eval: evalReverseScan},
roachpb.BeginTransaction: {DeclareKeys: declareKeysBeginTransaction, Eval: evalBeginTransaction},
roachpb.EndTransaction: {DeclareKeys: declareKeysEndTransaction, Eval: evalEndTransaction},
roachpb.RangeLookup: {DeclareKeys: DefaultDeclareKeys, Eval: evalRangeLookup},
roachpb.HeartbeatTxn: {DeclareKeys: declareKeysHeartbeatTransaction, Eval: evalHeartbeatTxn},
roachpb.GC: {DeclareKeys: declareKeysGC, Eval: evalGC},
roachpb.PushTxn: {DeclareKeys: declareKeysPushTransaction, Eval: evalPushTxn},
roachpb.QueryTxn: {DeclareKeys: DefaultDeclareKeys, Eval: evalQueryTxn},
roachpb.ResolveIntent: {DeclareKeys: declareKeysResolveIntent, Eval: evalResolveIntent},
roachpb.ResolveIntentRange: {DeclareKeys: declareKeysResolveIntentRange, Eval: evalResolveIntentRange},
roachpb.Merge: {DeclareKeys: DefaultDeclareKeys, Eval: evalMerge},
roachpb.TruncateLog: {DeclareKeys: declareKeysTruncateLog, Eval: evalTruncateLog},
roachpb.RequestLease: {DeclareKeys: declareKeysRequestLease, Eval: evalRequestLease},
roachpb.TransferLease: {DeclareKeys: declareKeysRequestLease, Eval: evalTransferLease},
roachpb.LeaseInfo: {DeclareKeys: declareKeysLeaseInfo, Eval: evalLeaseInfo},
roachpb.ComputeChecksum: {DeclareKeys: DefaultDeclareKeys, Eval: evalComputeChecksum},
roachpb.WriteBatch: writeBatchCmd,
roachpb.Export: exportCmd,
roachpb.DeprecatedVerifyChecksum: {
DeclareKeys: DefaultDeclareKeys,
Eval: func(context.Context, engine.ReadWriter, CommandArgs, roachpb.Response) (EvalResult, error) {
return EvalResult{}, nil
}},
}
// evaluateCommand delegates to the eval method for the given
// roachpb.Request. The returned EvalResult may be partially valid
// even if an error is returned. maxKeys is the number of scan results
// remaining for this batch (MaxInt64 for no limit).
func evaluateCommand(
ctx context.Context,
raftCmdID storagebase.CmdIDKey,
index int,
batch engine.ReadWriter,
rec ReplicaEvalContext,
ms *enginepb.MVCCStats,
h roachpb.Header,
maxKeys int64,
args roachpb.Request,
reply roachpb.Response,
) (EvalResult, *roachpb.Error) {
if _, ok := args.(*roachpb.NoopRequest); ok {
return EvalResult{}, nil
}
// If a unittest filter was installed, check for an injected error; otherwise, continue.
if filter := rec.StoreTestingKnobs().TestingEvalFilter; filter != nil {
filterArgs := storagebase.FilterArgs{Ctx: ctx, CmdID: raftCmdID, Index: index,
Sid: rec.StoreID(), Req: args, Hdr: h}
if pErr := filter(filterArgs); pErr != nil {
log.Infof(ctx, "test injecting error: %s", pErr)
return EvalResult{}, pErr
}
}
var err error
var pd EvalResult
if cmd, ok := commands[args.Method()]; ok {
cArgs := CommandArgs{
EvalCtx: rec,
Header: h,
// Some commands mutate their arguments, so give each invocation
// its own copy (shallow to mimic earlier versions of this code
// in which args were passed by value instead of pointer).
Args: args.ShallowCopy(),
MaxKeys: maxKeys,
Stats: ms,
}
pd, err = cmd.Eval(ctx, batch, cArgs, reply)
} else {
err = errors.Errorf("unrecognized command %s", args.Method())
}
if h.ReturnRangeInfo {
header := reply.Header()
lease, _, err := rec.GetLease()
if err != nil {
return EvalResult{}, roachpb.NewError(err)
}
desc, err := rec.Desc()
if err != nil {
return EvalResult{}, roachpb.NewError(err)
}
header.RangeInfos = []roachpb.RangeInfo{
{
Desc: *desc,
Lease: *lease,
},
}
reply.SetHeader(header)
}
// TODO(peter): We'd like to assert that the hlc clock is always updated
// correctly, but various tests insert versioned data without going through
// the proper channels. See TestPushTxnUpgradeExistingTxn for an example.
//
// if header.Txn != nil && !header.Txn.Timestamp.Less(h.Timestamp) {
// if now := r.store.Clock().Now(); now.Less(header.Txn.Timestamp) {
// log.Fatalf(ctx, "hlc clock not updated: %s < %s", now, header.Txn.Timestamp)
// }
// }
if log.V(2) {
log.Infof(ctx, "executed %s command %+v: %+v, err=%v", args.Method(), args, reply, err)
}
// Create a roachpb.Error by initializing txn from the request/response header.
var pErr *roachpb.Error
if err != nil {
txn := reply.Header().Txn
if txn == nil {
txn = h.Txn
}
pErr = roachpb.NewErrorWithTxn(err, txn)
}
return pd, pErr
}
func intentsToEvalResult(intents []roachpb.Intent, args roachpb.Request) EvalResult {
var pd EvalResult
if len(intents) > 0 {
pd.Local.intents = &[]intentsWithArg{{args: args, intents: intents}}
}
return pd
}
// evalGet returns the value for a specified key.
func evalGet(
ctx context.Context, batch engine.ReadWriter, cArgs CommandArgs, resp roachpb.Response,
) (EvalResult, error) {
args := cArgs.Args.(*roachpb.GetRequest)
h := cArgs.Header
reply := resp.(*roachpb.GetResponse)
val, intents, err := engine.MVCCGet(ctx, batch, args.Key, h.Timestamp, h.ReadConsistency == roachpb.CONSISTENT, h.Txn)
reply.Value = val
return intentsToEvalResult(intents, args), err
}
// evalPut sets the value for a specified key.
func evalPut(
ctx context.Context, batch engine.ReadWriter, cArgs CommandArgs, resp roachpb.Response,
) (EvalResult, error) {
args := cArgs.Args.(*roachpb.PutRequest)
h := cArgs.Header
ms := cArgs.Stats
var ts hlc.Timestamp
if !args.Inline {
ts = h.Timestamp
}
if h.DistinctSpans {
if b, ok := batch.(engine.Batch); ok {
// Use the distinct batch for both blind and normal ops so that we don't
// accidentally flush mutations to make them visible to the distinct
// batch.
batch = b.Distinct()
defer batch.Close()
}
}
if args.Blind {
return EvalResult{}, engine.MVCCBlindPut(ctx, batch, ms, args.Key, ts, args.Value, h.Txn)
}
return EvalResult{}, engine.MVCCPut(ctx, batch, ms, args.Key, ts, args.Value, h.Txn)
}
// evalConditionalPut sets the value for a specified key only if
// the expected value matches. If not, the return value contains
// the actual value.
func evalConditionalPut(
ctx context.Context, batch engine.ReadWriter, cArgs CommandArgs, resp roachpb.Response,
) (EvalResult, error) {
args := cArgs.Args.(*roachpb.ConditionalPutRequest)
h := cArgs.Header
if h.DistinctSpans {
if b, ok := batch.(engine.Batch); ok {
// Use the distinct batch for both blind and normal ops so that we don't
// accidentally flush mutations to make them visible to the distinct
// batch.
batch = b.Distinct()
defer batch.Close()
}
}
if args.Blind {
return EvalResult{}, engine.MVCCBlindConditionalPut(ctx, batch, cArgs.Stats, args.Key, h.Timestamp, args.Value, args.ExpValue, h.Txn)
}
return EvalResult{}, engine.MVCCConditionalPut(ctx, batch, cArgs.Stats, args.Key, h.Timestamp, args.Value, args.ExpValue, h.Txn)
}
// evalInitPut sets the value for a specified key only if it doesn't exist. It
// returns an error if the key exists with an existing value that is different
// from the value provided.
func evalInitPut(
ctx context.Context, batch engine.ReadWriter, cArgs CommandArgs, resp roachpb.Response,
) (EvalResult, error) {
args := cArgs.Args.(*roachpb.InitPutRequest)
h := cArgs.Header
return EvalResult{}, engine.MVCCInitPut(ctx, batch, cArgs.Stats, args.Key, h.Timestamp, args.Value, h.Txn)
}
// evalIncrement increments the value (interpreted as varint64 encoded) and
// returns the newly incremented value (encoded as varint64). If no value
// exists for the key, zero is incremented.
func evalIncrement(
ctx context.Context, batch engine.ReadWriter, cArgs CommandArgs, resp roachpb.Response,
) (EvalResult, error) {
args := cArgs.Args.(*roachpb.IncrementRequest)
h := cArgs.Header
reply := resp.(*roachpb.IncrementResponse)
newVal, err := engine.MVCCIncrement(ctx, batch, cArgs.Stats, args.Key, h.Timestamp, h.Txn, args.Increment)
reply.NewValue = newVal
return EvalResult{}, err
}
// evalDelete deletes the key and value specified by key.
func evalDelete(
ctx context.Context, batch engine.ReadWriter, cArgs CommandArgs, resp roachpb.Response,
) (EvalResult, error) {
args := cArgs.Args.(*roachpb.DeleteRequest)
h := cArgs.Header
return EvalResult{}, engine.MVCCDelete(ctx, batch, cArgs.Stats, args.Key, h.Timestamp, h.Txn)
}
// evalDeleteRange deletes the range of key/value pairs specified by
// start and end keys.
func evalDeleteRange(
ctx context.Context, batch engine.ReadWriter, cArgs CommandArgs, resp roachpb.Response,
) (EvalResult, error) {
args := cArgs.Args.(*roachpb.DeleteRangeRequest)
h := cArgs.Header
reply := resp.(*roachpb.DeleteRangeResponse)
var timestamp hlc.Timestamp
if !args.Inline {
timestamp = h.Timestamp
}
deleted, resumeSpan, num, err := engine.MVCCDeleteRange(
ctx, batch, cArgs.Stats, args.Key, args.EndKey, cArgs.MaxKeys, timestamp, h.Txn, args.ReturnKeys,
)
if err == nil {
reply.Keys = deleted
// DeleteRange requires that we retry on push to avoid the lost delete range anomaly.
if h.Txn != nil {
clonedTxn := h.Txn.Clone()
clonedTxn.RetryOnPush = true
reply.Txn = &clonedTxn
}
}
reply.NumKeys = num
reply.ResumeSpan = resumeSpan
return EvalResult{}, err
}
// evalScan scans the key range specified by start key through end key
// in ascending order up to some maximum number of results. maxKeys
// stores the number of scan results remaining for this batch
// (MaxInt64 for no limit).
func evalScan(
ctx context.Context, batch engine.ReadWriter, cArgs CommandArgs, resp roachpb.Response,
) (EvalResult, error) {
args := cArgs.Args.(*roachpb.ScanRequest)
h := cArgs.Header
reply := resp.(*roachpb.ScanResponse)
rows, resumeSpan, intents, err := engine.MVCCScan(ctx, batch, args.Key, args.EndKey,
cArgs.MaxKeys, h.Timestamp, h.ReadConsistency == roachpb.CONSISTENT, h.Txn)
reply.NumKeys = int64(len(rows))
reply.ResumeSpan = resumeSpan
reply.Rows = rows
return intentsToEvalResult(intents, args), err
}
// evalReverseScan scans the key range specified by start key through
// end key in descending order up to some maximum number of results.
// maxKeys stores the number of scan results remaining for this batch
// (MaxInt64 for no limit).
func evalReverseScan(
ctx context.Context, batch engine.ReadWriter, cArgs CommandArgs, resp roachpb.Response,
) (EvalResult, error) {
args := cArgs.Args.(*roachpb.ReverseScanRequest)
h := cArgs.Header
reply := resp.(*roachpb.ReverseScanResponse)
rows, resumeSpan, intents, err := engine.MVCCReverseScan(ctx, batch, args.Key, args.EndKey,
cArgs.MaxKeys, h.Timestamp, h.ReadConsistency == roachpb.CONSISTENT, h.Txn)
reply.NumKeys = int64(len(rows))
reply.ResumeSpan = resumeSpan
reply.Rows = rows
return intentsToEvalResult(intents, args), err
}
func verifyTransaction(h roachpb.Header, args roachpb.Request) error {
if h.Txn == nil {
return errors.Errorf("no transaction specified to %s", args.Method())
}
if !bytes.Equal(args.Header().Key, h.Txn.Key) {
return errors.Errorf("request key %s should match txn key %s", args.Header().Key, h.Txn.Key)
}
return nil
}
// declareKeysWriteTransaction is the shared portion of
// declareKeys{Begin,End,Heartbeat}Transaction
func declareKeysWriteTransaction(
_ roachpb.RangeDescriptor, header roachpb.Header, req roachpb.Request, spans *SpanSet,
) {
if header.Txn != nil && header.Txn.ID != nil {
spans.Add(SpanReadWrite, roachpb.Span{
Key: keys.TransactionKey(req.Header().Key, *header.Txn.ID),
})
}
}
func declareKeysBeginTransaction(
desc roachpb.RangeDescriptor, header roachpb.Header, req roachpb.Request, spans *SpanSet,
) {
declareKeysWriteTransaction(desc, header, req, spans)
spans.Add(SpanReadOnly, roachpb.Span{Key: keys.RangeTxnSpanGCThresholdKey(header.RangeID)})
}
// evalBeginTransaction writes the initial transaction record. Fails in
// the event that a transaction record is already written. This may
// occur if a transaction is started with a batch containing writes
// to different ranges, and the range containing the txn record fails
// to receive the write batch before a heartbeat or txn push is
// performed first and aborts the transaction.
func evalBeginTransaction(
ctx context.Context, batch engine.ReadWriter, cArgs CommandArgs, resp roachpb.Response,
) (EvalResult, error) {
args := cArgs.Args.(*roachpb.BeginTransactionRequest)
h := cArgs.Header
reply := resp.(*roachpb.BeginTransactionResponse)
if err := verifyTransaction(h, args); err != nil {
return EvalResult{}, err
}
key := keys.TransactionKey(h.Txn.Key, *h.Txn.ID)
clonedTxn := h.Txn.Clone()
reply.Txn = &clonedTxn
// Verify transaction does not already exist.
tmpTxn := roachpb.Transaction{}
ok, err := engine.MVCCGetProto(ctx, batch, key, hlc.Timestamp{}, true, nil, &tmpTxn)
if err != nil {
return EvalResult{}, err
}
if ok {
switch tmpTxn.Status {
case roachpb.ABORTED:
// Check whether someone has come in ahead and already aborted the
// txn.
return EvalResult{}, roachpb.NewTransactionAbortedError()
case roachpb.PENDING:
if h.Txn.Epoch > tmpTxn.Epoch {
// On a transaction retry there will be an extant txn record
// but this run should have an upgraded epoch. The extant txn
// record may have been pushed or otherwise updated, so update
// this command's txn and rewrite the record.
reply.Txn.Update(&tmpTxn)
} else {
// Our txn record already exists. This is either a client error, sending
// a duplicate BeginTransaction, or it's an artefact of DistSender
// re-sending a batch. Assume the latter and ask the client to restart.
return EvalResult{}, roachpb.NewTransactionRetryError()
}
case roachpb.COMMITTED:
return EvalResult{}, roachpb.NewTransactionStatusError(
fmt.Sprintf("BeginTransaction can't overwrite %s", tmpTxn),
)
default:
return EvalResult{}, roachpb.NewTransactionStatusError(
fmt.Sprintf("bad txn state: %s", tmpTxn),
)
}
}
threshold, err := cArgs.EvalCtx.TxnSpanGCThreshold()
if err != nil {
return EvalResult{}, err
}
// Disallow creation of a transaction record if it's at a timestamp before
// the TxnSpanGCThreshold, as in that case our transaction may already have
// been aborted by a concurrent actor which encountered one of our intents
// (which may have been written before this entry).
//
// See #9265.
if reply.Txn.LastActive().Less(threshold) {
return EvalResult{}, roachpb.NewTransactionAbortedError()
}
// Write the txn record.
reply.Txn.Writing = true
return EvalResult{}, engine.MVCCPutProto(ctx, batch, cArgs.Stats, key, hlc.Timestamp{}, nil, reply.Txn)
}
func declareKeysEndTransaction(
desc roachpb.RangeDescriptor, header roachpb.Header, req roachpb.Request, spans *SpanSet,
) {
declareKeysWriteTransaction(desc, header, req, spans)
et := req.(*roachpb.EndTransactionRequest)
// The spans may extend beyond this Range, but it's ok for the
// purpose of the command queue. The parts in our Range will
// be resolved eagerly.
for _, span := range et.IntentSpans {
spans.Add(SpanReadWrite, span)
}
if header.Txn != nil && header.Txn.ID != nil {
spans.Add(SpanReadWrite, roachpb.Span{Key: keys.AbortCacheKey(header.RangeID, *header.Txn.ID)})
}
// All transactions depend on the range descriptor because they need
// to determine which intents are within the local range.
spans.Add(SpanReadOnly, roachpb.Span{Key: keys.RangeDescriptorKey(desc.StartKey)})
if et.InternalCommitTrigger != nil {
if st := et.InternalCommitTrigger.SplitTrigger; st != nil {
// Splits may read from the entire pre-split range and write to
// the right side's RangeID spans and abort cache.
// TODO(bdarnell): the only time we read from the right-hand
// side is when the existing stats contain estimates. We might
// be able to be smarter here and avoid declaring reads on RHS
// in most cases.
spans.Add(SpanReadOnly, roachpb.Span{
Key: st.LeftDesc.StartKey.AsRawKey(),
EndKey: st.RightDesc.EndKey.AsRawKey(),
})
spans.Add(SpanReadOnly, roachpb.Span{
Key: keys.MakeRangeKeyPrefix(st.LeftDesc.StartKey),
EndKey: keys.MakeRangeKeyPrefix(st.RightDesc.EndKey).PrefixEnd(),
})
leftRangeIDPrefix := keys.MakeRangeIDReplicatedPrefix(header.RangeID)
spans.Add(SpanReadOnly, roachpb.Span{
Key: leftRangeIDPrefix,
EndKey: leftRangeIDPrefix.PrefixEnd(),
})
rightRangeIDPrefix := keys.MakeRangeIDReplicatedPrefix(st.RightDesc.RangeID)
spans.Add(SpanReadWrite, roachpb.Span{
Key: rightRangeIDPrefix,
EndKey: rightRangeIDPrefix.PrefixEnd(),
})
rightRangeIDUnreplicatedPrefix := keys.MakeRangeIDUnreplicatedPrefix(st.RightDesc.RangeID)
spans.Add(SpanReadWrite, roachpb.Span{
Key: rightRangeIDUnreplicatedPrefix,
EndKey: rightRangeIDUnreplicatedPrefix.PrefixEnd(),
})
leftStateLoader := makeReplicaStateLoader(st.LeftDesc.RangeID)
spans.Add(SpanReadOnly, roachpb.Span{
Key: leftStateLoader.RangeLastReplicaGCTimestampKey(),
})
rightStateLoader := makeReplicaStateLoader(st.RightDesc.RangeID)
spans.Add(SpanReadWrite, roachpb.Span{
Key: rightStateLoader.RangeLastReplicaGCTimestampKey(),
})
spans.Add(SpanReadOnly, roachpb.Span{
Key: abortCacheMinKey(header.RangeID),
EndKey: abortCacheMaxKey(header.RangeID)})
}
if mt := et.InternalCommitTrigger.MergeTrigger; mt != nil {
// Merges write to the left side and delete and read from the right.
leftRangeIDPrefix := keys.MakeRangeIDReplicatedPrefix(header.RangeID)
spans.Add(SpanReadWrite, roachpb.Span{
Key: leftRangeIDPrefix,
EndKey: leftRangeIDPrefix.PrefixEnd(),
})
rightRangeIDPrefix := keys.MakeRangeIDPrefix(mt.RightDesc.RangeID)
spans.Add(SpanReadWrite, roachpb.Span{
Key: rightRangeIDPrefix,
EndKey: rightRangeIDPrefix.PrefixEnd(),
})
spans.Add(SpanReadOnly, roachpb.Span{
Key: keys.MakeRangeKeyPrefix(mt.RightDesc.StartKey),
EndKey: keys.MakeRangeKeyPrefix(mt.RightDesc.EndKey).PrefixEnd(),
})
}
}
}
// evalEndTransaction either commits or aborts (rolls back) an extant
// transaction according to the args.Commit parameter. Rolling back
// an already rolled-back txn is ok.
func evalEndTransaction(
ctx context.Context, batch engine.ReadWriter, cArgs CommandArgs, resp roachpb.Response,
) (EvalResult, error) {
args := cArgs.Args.(*roachpb.EndTransactionRequest)
h := cArgs.Header
ms := cArgs.Stats
reply := resp.(*roachpb.EndTransactionResponse)
if err := verifyTransaction(h, args); err != nil {
return EvalResult{}, err
}
// If a 1PC txn was required and we're in EndTransaction, something went wrong.
if args.Require1PC {
return EvalResult{}, roachpb.NewTransactionStatusError("could not commit in one phase as requested")
}
key := keys.TransactionKey(h.Txn.Key, *h.Txn.ID)
// Fetch existing transaction.
var existingTxn roachpb.Transaction
if ok, err := engine.MVCCGetProto(
ctx, batch, key, hlc.Timestamp{}, true, nil, &existingTxn,
); err != nil {
return EvalResult{}, err
} else if !ok {
return EvalResult{}, roachpb.NewTransactionStatusError("does not exist")
}
reply.Txn = &existingTxn
// Verify that we can either commit it or abort it (according
// to args.Commit), and also that the Timestamp and Epoch have
// not suffered regression.
switch reply.Txn.Status {
case roachpb.COMMITTED:
return EvalResult{}, roachpb.NewTransactionStatusError("already committed")
case roachpb.ABORTED:
if !args.Commit {
// The transaction has already been aborted by other.
// Do not return TransactionAbortedError since the client anyway
// wanted to abort the transaction.
desc, err := cArgs.EvalCtx.Desc()
if err != nil {
return EvalResult{}, err
}
externalIntents := resolveLocalIntents(ctx, desc,
batch, ms, *args, reply.Txn, cArgs.EvalCtx.StoreTestingKnobs())
if err := updateTxnWithExternalIntents(
ctx, batch, ms, *args, reply.Txn, externalIntents,
); err != nil {
return EvalResult{}, err
}
return intentsToEvalResult(externalIntents, args), nil
}
// If the transaction was previously aborted by a concurrent
// writer's push, any intents written are still open. It's only now
// that we know them, so we return them all for asynchronous
// resolution (we're currently not able to write on error, but
// see #1989).
return intentsToEvalResult(roachpb.AsIntents(args.IntentSpans, reply.Txn), args),
roachpb.NewTransactionAbortedError()
case roachpb.PENDING:
if h.Txn.Epoch < reply.Txn.Epoch {
// TODO(tschottdorf): this leaves the Txn record (and more
// importantly, intents) dangling; we can't currently write on
// error. Would panic, but that makes TestEndTransactionWithErrors
// awkward.
return EvalResult{}, roachpb.NewTransactionStatusError(
fmt.Sprintf("epoch regression: %d", h.Txn.Epoch),
)
} else if h.Txn.Epoch == reply.Txn.Epoch && reply.Txn.Timestamp.Less(h.Txn.OrigTimestamp) {
// The transaction record can only ever be pushed forward, so it's an
// error if somehow the transaction record has an earlier timestamp
// than the original transaction timestamp.
// TODO(tschottdorf): see above comment on epoch regression.
return EvalResult{}, roachpb.NewTransactionStatusError(
fmt.Sprintf("timestamp regression: %s", h.Txn.OrigTimestamp),
)
}
default:
return EvalResult{}, roachpb.NewTransactionStatusError(
fmt.Sprintf("bad txn status: %s", reply.Txn),
)
}
// Take max of requested epoch and existing epoch. The requester
// may have incremented the epoch on retries.
if reply.Txn.Epoch < h.Txn.Epoch {
reply.Txn.Epoch = h.Txn.Epoch
}
// Take max of requested priority and existing priority. This isn't
// terribly useful, but we do it for completeness.
if reply.Txn.Priority < h.Txn.Priority {
reply.Txn.Priority = h.Txn.Priority
}
// Take max of supplied txn's timestamp and persisted txn's
// timestamp. It may have been pushed by another transaction.
// Note that we do not use the batch request timestamp, which for
// a transaction is always set to the txn's original timestamp.
reply.Txn.Timestamp.Forward(h.Txn.Timestamp)
if isEndTransactionExceedingDeadline(reply.Txn.Timestamp, *args) {
// If the deadline has lapsed return an error and rely on the client
// issuing a Rollback() that aborts the transaction and cleans up
// intents. Unfortunately, we're returning an error and unable to
// write on error (see #1989): we can't write ABORTED into the master
// transaction record which remains PENDING, and thus rely on the
// client to issue a Rollback() for cleanup.
return EvalResult{}, roachpb.NewTransactionStatusError(
"transaction deadline exceeded")
}
// Set transaction status to COMMITTED or ABORTED as per the
// args.Commit parameter.
if args.Commit {
if isEndTransactionTriggeringRetryError(h.Txn, reply.Txn) {
return EvalResult{}, roachpb.NewTransactionRetryError()
}
reply.Txn.Status = roachpb.COMMITTED
} else {
reply.Txn.Status = roachpb.ABORTED
}
desc, err := cArgs.EvalCtx.Desc()
if err != nil {
return EvalResult{}, err
}
externalIntents := resolveLocalIntents(ctx, desc,
batch, ms, *args, reply.Txn, cArgs.EvalCtx.StoreTestingKnobs())
if err := updateTxnWithExternalIntents(ctx, batch, ms, *args, reply.Txn, externalIntents); err != nil {
return EvalResult{}, err
}
// Run triggers if successfully committed.
var pd EvalResult
if reply.Txn.Status == roachpb.COMMITTED {
var err error
if pd, err = runCommitTrigger(ctx, cArgs.EvalCtx, batch.(engine.Batch), ms, *args, reply.Txn); err != nil {
return EvalResult{}, NewReplicaCorruptionError(err)
}
}
// Note: there's no need to clear the abort cache state if we've
// successfully finalized a transaction, as there's no way in
// which an abort cache entry could have been written (the txn would
// already have been in state=ABORTED).
//
// Summary of transaction replay protection after EndTransaction:
// When a transactional write gets replayed over its own resolved
// intents, the write will succeed but only as an intent with a
// newer timestamp (with a WriteTooOldError). However, the replayed
// intent cannot be resolved by a subsequent replay of this
// EndTransaction call because the txn timestamp will be too
// old. Replays which include a BeginTransaction never succeed
// because EndTransaction inserts in the write timestamp cache,
// forcing the BeginTransaction to fail with a transaction retry
// error. If the replay didn't include a BeginTransaction, any push
// will immediately succeed as a missing txn record on push sets the
// transaction to aborted. In both cases, the txn will be GC'd on
// the slow path.
intentsResult := intentsToEvalResult(externalIntents, args)
intentsResult.Local.updatedTxn = reply.Txn
if err := pd.MergeAndDestroy(intentsResult); err != nil {
return EvalResult{}, err
}
return pd, nil
}
// isEndTransactionExceedingDeadline returns true if the transaction
// exceeded its deadline.
func isEndTransactionExceedingDeadline(t hlc.Timestamp, args roachpb.EndTransactionRequest) bool {
return args.Deadline != nil && args.Deadline.Less(t)
}
// isEndTransactionTriggeringRetryError returns true if the
// EndTransactionRequest cannot be committed and needs to return a
// TransactionRetryError.
func isEndTransactionTriggeringRetryError(headerTxn, currentTxn *roachpb.Transaction) bool {
// If we saw any WriteTooOldErrors, we must restart to avoid lost
// update anomalies.
if headerTxn.WriteTooOld {
return true
}
isTxnPushed := currentTxn.Timestamp != headerTxn.OrigTimestamp
// If pushing requires a retry and the transaction was pushed, retry.
if headerTxn.RetryOnPush && isTxnPushed {
return true
}
// If the isolation level is SERIALIZABLE, return a transaction
// retry error if the commit timestamp isn't equal to the txn
// timestamp.
if headerTxn.Isolation == enginepb.SERIALIZABLE && isTxnPushed {
return true
}
return false
}
// resolveLocalIntents synchronously resolves any intents that are
// local to this range in the same batch. The remainder are collected
// and returned so that they can be handed off to asynchronous
// processing.
func resolveLocalIntents(
ctx context.Context,
desc *roachpb.RangeDescriptor,
batch engine.ReadWriter,
ms *enginepb.MVCCStats,
args roachpb.EndTransactionRequest,
txn *roachpb.Transaction,
storeTestingKnobs StoreTestingKnobs,
) []roachpb.Intent {
var preMergeDesc *roachpb.RangeDescriptor
if mergeTrigger := args.InternalCommitTrigger.GetMergeTrigger(); mergeTrigger != nil {
// If this is a merge, then use the post-merge descriptor to determine
// which intents are local (note that for a split, we want to use the
// pre-split one instead because it's larger).
preMergeDesc = desc
desc = &mergeTrigger.LeftDesc
}
iterAndBuf := engine.GetIterAndBuf(batch)
defer iterAndBuf.Cleanup()
var externalIntents []roachpb.Intent
for _, span := range args.IntentSpans {
if err := func() error {
intent := roachpb.Intent{Span: span, Txn: txn.TxnMeta, Status: txn.Status}
if len(span.EndKey) == 0 {
// For single-key intents, do a KeyAddress-aware check of
// whether it's contained in our Range.
if !containsKey(*desc, span.Key) {
externalIntents = append(externalIntents, intent)
return nil
}
resolveMS := ms
if preMergeDesc != nil && !containsKey(*preMergeDesc, span.Key) {
// If this transaction included a merge and the intents
// are from the subsumed range, ignore the intent resolution
// stats, as they will already be accounted for during the
// merge trigger.
resolveMS = nil
}
return engine.MVCCResolveWriteIntentUsingIter(ctx, batch, iterAndBuf, resolveMS, intent)
}
// For intent ranges, cut into parts inside and outside our key
// range. Resolve locally inside, delegate the rest. In particular,
// an intent range for range-local data is correctly considered local.
inSpan, outSpans := intersectSpan(span, *desc)
for _, span := range outSpans {
outIntent := intent
outIntent.Span = span
externalIntents = append(externalIntents, outIntent)
}
if inSpan != nil {
intent.Span = *inSpan
num, err := engine.MVCCResolveWriteIntentRangeUsingIter(ctx, batch, iterAndBuf, ms, intent, math.MaxInt64)
if storeTestingKnobs.NumKeysEvaluatedForRangeIntentResolution != nil {
atomic.AddInt64(storeTestingKnobs.NumKeysEvaluatedForRangeIntentResolution, num)
}
return err
}
return nil
}(); err != nil {
// TODO(tschottdorf): any legitimate reason for this to happen?
// Figure that out and if not, should still be ReplicaCorruption
// and not a panic.
panic(fmt.Sprintf("error resolving intent at %s on end transaction [%s]: %s", span, txn.Status, err))
}
}
return externalIntents
}
// updateTxnWithExternalIntents persists the transaction record with
// updated status (& possibly timestamp). If we've already resolved
// all intents locally, we actually delete the record right away - no
// use in keeping it around.
func updateTxnWithExternalIntents(
ctx context.Context,
batch engine.ReadWriter,
ms *enginepb.MVCCStats,
args roachpb.EndTransactionRequest,
txn *roachpb.Transaction,
externalIntents []roachpb.Intent,
) error {
key := keys.TransactionKey(txn.Key, *txn.ID)
if txnAutoGC && len(externalIntents) == 0 {
if log.V(2) {
log.Infof(ctx, "auto-gc'ed %s (%d intents)", txn.Short(), len(args.IntentSpans))
}
return engine.MVCCDelete(ctx, batch, ms, key, hlc.Timestamp{}, nil /* txn */)
}
txn.Intents = make([]roachpb.Span, len(externalIntents))
for i := range externalIntents {
txn.Intents[i] = externalIntents[i].Span
}
return engine.MVCCPutProto(ctx, batch, ms, key, hlc.Timestamp{}, nil /* txn */, txn)
}
// intersectSpan takes an intent and a descriptor. It then splits the
// intent's range into up to three pieces: A first piece which is contained in
// the Range, and a slice of up to two further intents which are outside of the
// key range. An intent for which [Key, EndKey) is empty does not result in any
// intents; thus intersectIntent only applies to intent ranges.
// A range-local intent range is never split: It's returned as either
// belonging to or outside of the descriptor's key range, and passing an intent
// which begins range-local but ends non-local results in a panic.
// TODO(tschottdorf) move to proto, make more gen-purpose - kv.truncate does
// some similar things.
func intersectSpan(
span roachpb.Span, desc roachpb.RangeDescriptor,
) (middle *roachpb.Span, outside []roachpb.Span) {
start, end := desc.StartKey.AsRawKey(), desc.EndKey.AsRawKey()
if len(span.EndKey) == 0 {
outside = append(outside, span)
return
}
if bytes.Compare(span.Key, keys.LocalRangeMax) < 0 {
if bytes.Compare(span.EndKey, keys.LocalRangeMax) >= 0 {
panic(fmt.Sprintf("a local intent range may not have a non-local portion: %s", span))
}
if containsKeyRange(desc, span.Key, span.EndKey) {
return &span, nil
}
return nil, append(outside, span)
}
// From now on, we're dealing with plain old key ranges - no more local
// addressing.
if bytes.Compare(span.Key, start) < 0 {
// Intent spans a part to the left of [start, end).
iCopy := span
if bytes.Compare(start, span.EndKey) < 0 {
iCopy.EndKey = start
}
span.Key = iCopy.EndKey
outside = append(outside, iCopy)
}
if bytes.Compare(span.Key, span.EndKey) < 0 && bytes.Compare(end, span.EndKey) < 0 {
// Intent spans a part to the right of [start, end).
iCopy := span
if bytes.Compare(iCopy.Key, end) < 0 {
iCopy.Key = end
}
span.EndKey = iCopy.Key
outside = append(outside, iCopy)
}
if bytes.Compare(span.Key, span.EndKey) < 0 && bytes.Compare(span.Key, start) >= 0 && bytes.Compare(end, span.EndKey) >= 0 {
middle = &span
}
return
}
func runCommitTrigger(
ctx context.Context,
rec ReplicaEvalContext,
batch engine.Batch,
ms *enginepb.MVCCStats,
args roachpb.EndTransactionRequest,
txn *roachpb.Transaction,
) (EvalResult, error) {
ct := args.InternalCommitTrigger
if ct == nil {
return EvalResult{}, nil
}
if ct.GetSplitTrigger() != nil {
newMS, trigger, err := splitTrigger(
ctx, rec, batch, *ms, ct.SplitTrigger, txn.Timestamp,
)
*ms = newMS
return trigger, err