-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
replica_command.go
2174 lines (2002 loc) · 85.4 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.
package storage
import (
"bytes"
"context"
"fmt"
"math"
"math/rand"
"strings"
"sync/atomic"
"time"
"github.com/coreos/etcd/raft/raftpb"
"github.com/pkg/errors"
"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/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/storage/abortspan"
"github.com/cockroachdb/cockroach/pkg/storage/batcheval"
"github.com/cockroachdb/cockroach/pkg/storage/batcheval/result"
"github.com/cockroachdb/cockroach/pkg/storage/engine"
"github.com/cockroachdb/cockroach/pkg/storage/engine/enginepb"
"github.com/cockroachdb/cockroach/pkg/storage/rditer"
"github.com/cockroachdb/cockroach/pkg/storage/spanset"
"github.com/cockroachdb/cockroach/pkg/storage/stateloader"
"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"
)
// evaluateCommand delegates to the eval method for the given
// roachpb.Request. The returned Result 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 batcheval.EvalContext,
ms *enginepb.MVCCStats,
h roachpb.Header,
maxKeys int64,
args roachpb.Request,
reply roachpb.Response,
) (result.Result, *roachpb.Error) {
if _, ok := args.(*roachpb.NoopRequest); ok {
return result.Result{}, nil
}
// If a unittest filter was installed, check for an injected error; otherwise, continue.
if filter := rec.EvalKnobs().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 result.Result{}, pErr
}
}
var err error
var pd result.Result
if cmd, ok := batcheval.LookupCommand(args.Method()); ok {
cArgs := batcheval.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, _ := rec.GetLease()
desc := rec.Desc()
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, "evaluated %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 init() {
// TODO(tschottdorf): move EndTransaction into batcheval. In doing so,
// unexport DeclareKeysWriteTransaction.
batcheval.RegisterCommand(roachpb.EndTransaction, declareKeysEndTransaction, evalEndTransaction)
}
func declareKeysEndTransaction(
desc roachpb.RangeDescriptor, header roachpb.Header, req roachpb.Request, spans *spanset.SpanSet,
) {
batcheval.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(spanset.SpanReadWrite, span)
}
if header.Txn != nil {
header.Txn.AssertInitialized(context.TODO())
spans.Add(spanset.SpanReadWrite, roachpb.Span{Key: keys.AbortSpanKey(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(spanset.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 (they read
// from the LHS in all cases, and the RHS only when the existing
// stats contain estimates), but they need to declare a write
// access to block all other concurrent writes. We block writes
// to the RHS because they will fail if applied after the split,
// and writes to the LHS because their stat deltas will
// interfere with the non-delta stats computed as a part of the
// split. (see
// https://github.com/cockroachdb/cockroach/issues/14881)
spans.Add(spanset.SpanReadWrite, roachpb.Span{
Key: st.LeftDesc.StartKey.AsRawKey(),
EndKey: st.RightDesc.EndKey.AsRawKey(),
})
spans.Add(spanset.SpanReadWrite, roachpb.Span{
Key: keys.MakeRangeKeyPrefix(st.LeftDesc.StartKey),
EndKey: keys.MakeRangeKeyPrefix(st.RightDesc.EndKey).PrefixEnd(),
})
leftRangeIDPrefix := keys.MakeRangeIDReplicatedPrefix(header.RangeID)
spans.Add(spanset.SpanReadOnly, roachpb.Span{
Key: leftRangeIDPrefix,
EndKey: leftRangeIDPrefix.PrefixEnd(),
})
rightRangeIDPrefix := keys.MakeRangeIDReplicatedPrefix(st.RightDesc.RangeID)
spans.Add(spanset.SpanReadWrite, roachpb.Span{
Key: rightRangeIDPrefix,
EndKey: rightRangeIDPrefix.PrefixEnd(),
})
rightRangeIDUnreplicatedPrefix := keys.MakeRangeIDUnreplicatedPrefix(st.RightDesc.RangeID)
spans.Add(spanset.SpanReadWrite, roachpb.Span{
Key: rightRangeIDUnreplicatedPrefix,
EndKey: rightRangeIDUnreplicatedPrefix.PrefixEnd(),
})
spans.Add(spanset.SpanReadOnly, roachpb.Span{
Key: keys.RangeLastReplicaGCTimestampKey(st.LeftDesc.RangeID),
})
spans.Add(spanset.SpanReadWrite, roachpb.Span{
Key: keys.RangeLastReplicaGCTimestampKey(st.RightDesc.RangeID),
})
spans.Add(spanset.SpanReadOnly, roachpb.Span{
Key: abortspan.MinKey(header.RangeID),
EndKey: abortspan.MaxKey(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(spanset.SpanReadWrite, roachpb.Span{
Key: leftRangeIDPrefix,
EndKey: leftRangeIDPrefix.PrefixEnd(),
})
rightRangeIDPrefix := keys.MakeRangeIDPrefix(mt.RightDesc.RangeID)
spans.Add(spanset.SpanReadWrite, roachpb.Span{
Key: rightRangeIDPrefix,
EndKey: rightRangeIDPrefix.PrefixEnd(),
})
spans.Add(spanset.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 batcheval.CommandArgs, resp roachpb.Response,
) (result.Result, error) {
args := cArgs.Args.(*roachpb.EndTransactionRequest)
h := cArgs.Header
ms := cArgs.Stats
reply := resp.(*roachpb.EndTransactionResponse)
if err := batcheval.VerifyTransaction(h, args); err != nil {
return result.Result{}, err
}
// If a 1PC txn was required and we're in EndTransaction, something went wrong.
if args.Require1PC {
return result.Result{}, 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 result.Result{}, err
} else if !ok {
return result.Result{}, roachpb.NewTransactionNotFoundStatusError()
}
// We're using existingTxn on the reply, although it can be stale
// compared to the Transaction in the request (e.g. the Sequence,
// and various timestamps). We must be careful to update it with the
// supplied ba.Txn if we return it with an error which might be
// retried, as for example to avoid client-side serializable restart.
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 result.Result{}, 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 := cArgs.EvalCtx.Desc()
externalIntents, err := resolveLocalIntents(ctx, desc, batch, ms, *args, reply.Txn, cArgs.EvalCtx)
if err != nil {
return result.Result{}, err
}
if err := updateTxnWithExternalIntents(
ctx, batch, ms, *args, reply.Txn, externalIntents,
); err != nil {
return result.Result{}, err
}
// Use alwaysReturn==true because the transaction is definitely
// aborted, no matter what happens to this command.
return result.FromEndTxn(reply.Txn, true /* alwaysReturn */, args.Poison), 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).
//
// Similarly to above, use alwaysReturn==true. The caller isn't trying
// to abort, but the transaction is definitely aborted and its intents
// can go.
reply.Txn.Intents = args.IntentSpans
return result.FromEndTxn(reply.Txn, true /* alwaysReturn */, args.Poison), 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 result.Result{}, 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 result.Result{}, roachpb.NewTransactionStatusError(
fmt.Sprintf("timestamp regression: %s", h.Txn.OrigTimestamp),
)
}
default:
return result.Result{}, roachpb.NewTransactionStatusError(
fmt.Sprintf("bad txn status: %s", reply.Txn),
)
}
// Update the existing txn with the supplied txn.
reply.Txn.Update(h.Txn)
// Set transaction status to COMMITTED or ABORTED as per the
// args.Commit parameter.
if args.Commit {
if retry, reason := isEndTransactionTriggeringRetryError(reply.Txn, *args); retry {
return result.Result{}, roachpb.NewTransactionRetryError(reason)
}
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.
//
// N.B. This deadline test is expected to be a Noop for Serializable
// transactions; unless the client misconfigured the txn, the deadline can
// only be expired if the txn has been pushed, and pushed Serializable
// transactions are detected above.
return result.Result{}, roachpb.NewTransactionStatusError(
"transaction deadline exceeded")
}
reply.Txn.Status = roachpb.COMMITTED
} else {
reply.Txn.Status = roachpb.ABORTED
}
desc := cArgs.EvalCtx.Desc()
externalIntents, err := resolveLocalIntents(ctx, desc, batch, ms, *args, reply.Txn, cArgs.EvalCtx)
if err != nil {
return result.Result{}, err
}
if err := updateTxnWithExternalIntents(ctx, batch, ms, *args, reply.Txn, externalIntents); err != nil {
return result.Result{}, err
}
// Run triggers if successfully committed.
var pd result.Result
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 result.Result{}, NewReplicaCorruptionError(err)
}
}
// Note: there's no need to clear the AbortSpan 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.
//
// We specify alwaysReturn==false because if the commit fails below Raft, we
// don't want the intents to be up for resolution. That should happen only
// if the commit actually happens; otherwise, we risk losing writes.
intentsResult := result.FromEndTxn(reply.Txn, false /* alwaysReturn */, args.Poison)
intentsResult.Local.UpdatedTxns = &[]*roachpb.Transaction{reply.Txn}
if err := pd.MergeAndDestroy(intentsResult); err != nil {
return result.Result{}, 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(
txn *roachpb.Transaction, args roachpb.EndTransactionRequest,
) (retry bool, reason roachpb.TransactionRetryReason) {
// If we saw any WriteTooOldErrors, we must restart to avoid lost
// update anomalies.
if txn.WriteTooOld {
retry, reason = true, roachpb.RETRY_WRITE_TOO_OLD
} else {
origTimestamp := txn.OrigTimestamp
origTimestamp.Forward(txn.RefreshedTimestamp)
isTxnPushed := txn.Timestamp != origTimestamp
// If the isolation level is SERIALIZABLE, return a transaction
// retry error if the commit timestamp isn't equal to the txn
// timestamp.
if isTxnPushed {
if txn.Isolation == enginepb.SERIALIZABLE {
retry, reason = true, roachpb.RETRY_SERIALIZABLE
} else if txn.RetryOnPush {
// If pushing requires a retry and the transaction was pushed, retry.
retry, reason = true, roachpb.RETRY_DELETE_RANGE
}
}
}
// A serializable transaction can still avoid a retry under certain conditions.
if retry && txn.IsSerializable() && canForwardSerializableTimestamp(txn, args.NoRefreshSpans) {
retry, reason = false, 0
}
return retry, reason
}
// canForwardSerializableTimestamp returns whether a serializable txn can
// be safely committed with a forwarded timestamp. This requires that
// the transaction's timestamp has not leaked and that the transaction
// has encountered no spans which require refreshing at the forwarded
// timestamp. If either of those conditions are true, a cient-side
// retry is required.
func canForwardSerializableTimestamp(txn *roachpb.Transaction, noRefreshSpans bool) bool {
return !txn.OrigTimestampWasObserved && noRefreshSpans
}
// 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. Note that there is a maximum intent resolution
// allowance of intentResolverBatchSize meant to avoid creating a
// batch which is too large for Raft. Any local intents which exceed
// the allowance are treated as external and are resolved
// asynchronously with the external intents.
func resolveLocalIntents(
ctx context.Context,
desc *roachpb.RangeDescriptor,
batch engine.ReadWriter,
ms *enginepb.MVCCStats,
args roachpb.EndTransactionRequest,
txn *roachpb.Transaction,
evalCtx batcheval.EvalContext,
) ([]roachpb.Span, error) {
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
}
min, max := txn.InclusiveTimeBounds()
iter := batch.NewTimeBoundIterator(min, max, false)
iterAndBuf := engine.GetBufUsingIter(iter)
defer iterAndBuf.Cleanup()
var externalIntents []roachpb.Span
var resolveAllowance int64 = intentResolverBatchSize
for _, span := range args.IntentSpans {
if err := func() error {
if resolveAllowance == 0 {
externalIntents = append(externalIntents, span)
return nil
}
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, span)
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
}
resolveAllowance--
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)
externalIntents = append(externalIntents, outSpans...)
if inSpan != nil {
intent.Span = *inSpan
num, resumeSpan, err := engine.MVCCResolveWriteIntentRangeUsingIter(ctx, batch, iterAndBuf, ms, intent, resolveAllowance)
if err != nil {
return err
}
if evalCtx.EvalKnobs().NumKeysEvaluatedForRangeIntentResolution != nil {
atomic.AddInt64(evalCtx.EvalKnobs().NumKeysEvaluatedForRangeIntentResolution, num)
}
resolveAllowance -= num
if resumeSpan != nil {
if resolveAllowance != 0 {
log.Fatalf(ctx, "expected resolve allowance to be exactly 0 resolving %s; got %d", intent.Span, resolveAllowance)
}
externalIntents = append(externalIntents, *resumeSpan)
}
return nil
}
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))
}
}
// If the poison arg is set, make sure to set the abort span entry.
if args.Poison && txn.Status == roachpb.ABORTED {
if err := batcheval.SetAbortSpan(ctx, evalCtx, batch, ms, txn.TxnMeta, true /* poison */); err != nil {
return nil, err
}
}
return externalIntents, nil
}
// 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.Span,
) 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 = externalIntents
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 batcheval.EvalContext,
batch engine.Batch,
ms *enginepb.MVCCStats,
args roachpb.EndTransactionRequest,
txn *roachpb.Transaction,
) (result.Result, error) {
ct := args.InternalCommitTrigger
if ct == nil {
return result.Result{}, nil
}
if ct.GetSplitTrigger() != nil {
newMS, trigger, err := splitTrigger(
ctx, rec, batch, *ms, ct.SplitTrigger, txn.Timestamp,
)
*ms = newMS
return trigger, err
}
if ct.GetMergeTrigger() != nil {
return mergeTrigger(ctx, rec, batch, ms, ct.MergeTrigger, txn.Timestamp)
}
if crt := ct.GetChangeReplicasTrigger(); crt != nil {
return changeReplicasTrigger(ctx, rec, batch, crt), nil
}
if ct.GetModifiedSpanTrigger() != nil {
var pd result.Result
if ct.ModifiedSpanTrigger.SystemConfigSpan {
// Check if we need to gossip the system config.
// NOTE: System config gossiping can only execute correctly if
// the transaction record is located on the range that contains
// the system span. If a transaction is created which modifies
// both system *and* non-system data, it should be ensured that
// the transaction record itself is on the system span. This can
// be done by making sure a system key is the first key touched
// in the transaction.
if rec.ContainsKey(keys.SystemConfigSpan.Key) {
if err := pd.MergeAndDestroy(
result.Result{
Local: result.LocalResult{
MaybeGossipSystemConfig: true,
},
},
); err != nil {
return result.Result{}, err
}
} else {
log.Errorf(ctx, "System configuration span was modified, but the "+
"modification trigger is executing on a non-system range. "+
"Configuration changes will not be gossiped.")
}
}
if nlSpan := ct.ModifiedSpanTrigger.NodeLivenessSpan; nlSpan != nil {
if err := pd.MergeAndDestroy(
result.Result{
Local: result.LocalResult{
MaybeGossipNodeLiveness: nlSpan,
},
},
); err != nil {
return result.Result{}, err
}
}
return pd, nil
}
log.Fatalf(ctx, "unknown commit trigger: %+v", ct)
return result.Result{}, nil
}
// AdminSplit divides the range into into two ranges using args.SplitKey.
func (r *Replica) AdminSplit(
ctx context.Context, args roachpb.AdminSplitRequest,
) (reply roachpb.AdminSplitResponse, pErr *roachpb.Error) {
if len(args.SplitKey) == 0 {
return roachpb.AdminSplitResponse{}, roachpb.NewErrorf("cannot split range with no key provided")
}
retryOpts := base.DefaultRetryOptions()
retryOpts.MaxRetries = 10
for retryable := retry.StartWithCtx(ctx, retryOpts); retryable.Next(); {
// Admin commands always require the range lease to begin (see
// executeAdminBatch), but we may have lost it while in this retry loop.
// Without the lease, a replica's local descriptor can be arbitrarily
// stale, which will result in a ConditionFailedError. To avoid this,
// we make sure that we still have the lease before each attempt.
if _, pErr = r.redirectOnOrAcquireLease(ctx); pErr != nil {
return roachpb.AdminSplitResponse{}, pErr
}
reply, _, pErr = r.adminSplitWithDescriptor(ctx, args, r.Desc())
// On seeing a ConditionFailedError or an AmbiguousResultError, retry the
// command with the updated descriptor.
switch pErr.GetDetail().(type) {
case *roachpb.ConditionFailedError:
case *roachpb.AmbiguousResultError:
default:
return reply, pErr
}
}
// If we broke out of the loop after MaxRetries, return the last error.
return roachpb.AdminSplitResponse{}, pErr
}
func maybeDescriptorChangedError(desc *roachpb.RangeDescriptor, err error) (string, bool) {
if detail, ok := err.(*roachpb.ConditionFailedError); ok {
// Provide a better message in the common case that the range being changed
// was already changed by a concurrent transaction.
var actualDesc roachpb.RangeDescriptor
if err := detail.ActualValue.GetProto(&actualDesc); err == nil {
if desc.RangeID == actualDesc.RangeID && !desc.Equal(actualDesc) {
return fmt.Sprintf("descriptor changed: [expected] %s != [actual] %s",
desc, actualDesc), true
}
}
}
return "", false
}
// adminSplitWithDescriptor divides the range into into two ranges, using
// either args.SplitKey (if provided) or an internally computed key that aims
// to roughly equipartition the range by size. The split is done inside of a
// distributed txn which writes updated left and new right hand side range
// descriptors, and updates the range addressing metadata. The handover of
// responsibility for the reassigned key range is carried out seamlessly
// through a split trigger carried out as part of the commit of that
// transaction.
//
// The supplied RangeDescriptor is used as a form of optimistic lock. An
// operation which might split a range should obtain a copy of the range's
// current descriptor before making the decision to split. If the decision is
// affirmative the descriptor is passed to AdminSplit, which performs a
// Conditional Put on the RangeDescriptor to ensure that no other operation has
// modified the range in the time the decision was being made.
// TODO(tschottdorf): should assert that split key is not a local key.
//
// See the comment on splitTrigger for details on the complexities.
func (r *Replica) adminSplitWithDescriptor(
ctx context.Context, args roachpb.AdminSplitRequest, desc *roachpb.RangeDescriptor,
) (_ roachpb.AdminSplitResponse, validSplitKey bool, _ *roachpb.Error) {
var reply roachpb.AdminSplitResponse
// Determine split key if not provided with args. This scan is
// allowed to be relatively slow because admin commands don't block
// other commands.
log.Event(ctx, "split begins")
var splitKey roachpb.RKey
{
// Once a split occurs, it can't be rolled back even on a downgrade, so
// we only allow meta2 splits if the minimum supported version is
// VersionMeta2Splits, as opposed to allowing them if the active version
// is VersionMeta2Splits.
allowMeta2Splits := r.store.cfg.Settings.Version.IsMinSupported(cluster.VersionMeta2Splits)
var foundSplitKey roachpb.Key
if len(args.SplitKey) == 0 {
// Find a key to split by size.
var err error
targetSize := r.GetMaxBytes() / 2
foundSplitKey, err = engine.MVCCFindSplitKey(
ctx, r.store.engine, desc.StartKey, desc.EndKey, targetSize, allowMeta2Splits)
if err != nil {
return reply, false, roachpb.NewErrorf("unable to determine split key: %s", err)
}
if foundSplitKey == nil {
// No suitable split key could be found.
return reply, false, nil
}
} else {
// If the key that routed this request to this range is now out of this
// range's bounds, return an error for the client to try again on the
// correct range.
if !containsKey(*desc, args.Span.Key) {
return reply, false,
roachpb.NewError(roachpb.NewRangeKeyMismatchError(args.Span.Key, args.Span.Key, desc))
}
foundSplitKey = args.SplitKey
}
if !containsKey(*desc, foundSplitKey) {
return reply, false,
roachpb.NewErrorf("requested split key %s out of bounds of %s", args.SplitKey, r)
}
var err error
splitKey, err = keys.Addr(foundSplitKey)
if err != nil {
return reply, false, roachpb.NewError(err)
}
if !splitKey.Equal(foundSplitKey) {
return reply, false, roachpb.NewErrorf("cannot split range at range-local key %s", splitKey)
}
if !engine.IsValidSplitKey(foundSplitKey, allowMeta2Splits) {
return reply, false, roachpb.NewErrorf("cannot split range at key %s", splitKey)
}
}
// If the range starts at the splitKey, we treat the AdminSplit
// as a no-op and return success instead of throwing an error.
if desc.StartKey.Equal(splitKey) {
log.Event(ctx, "range already split")
return reply, false, nil
}
log.Event(ctx, "found split key")
// Create right hand side range descriptor with the newly-allocated Range ID.
rightDesc, err := r.store.NewRangeDescriptor(ctx, splitKey, desc.EndKey, desc.Replicas)
if err != nil {
return reply, true,
roachpb.NewErrorf("unable to allocate right hand side range descriptor: %s", err)
}
// Init updated version of existing range descriptor.
leftDesc := *desc
leftDesc.EndKey = splitKey
log.Infof(ctx, "initiating a split of this range at key %s [r%d]",
splitKey, rightDesc.RangeID)
if err := r.store.DB().Txn(ctx, func(ctx context.Context, txn *client.Txn) error {
log.Event(ctx, "split closure begins")
defer log.Event(ctx, "split closure ends")
txn.SetDebugName(splitTxnName)
// Update existing range descriptor for left hand side of
// split. Note that we mutate the descriptor for the left hand
// side of the split first to locate the txn record there.
{
b := txn.NewBatch()
leftDescKey := keys.RangeDescriptorKey(leftDesc.StartKey)
if err := updateRangeDescriptor(b, leftDescKey, desc, leftDesc); err != nil {
return err
}
// Commit this batch first to ensure that the transaction record
// is created in the right place (split trigger relies on this),
// but also to ensure the transaction record is created _before_
// intents for the RHS range descriptor or addressing records.
// Keep in mind that the BeginTransaction request is injected
// to accompany the first write request, but if part of a batch
// which spans ranges, the dist sender does not guarantee the
// order which parts of the split batch arrive.
//
// Sending the batch containing only the first write guarantees
// the transaction record is written first, preventing cases
// where splits are aborted early due to conflicts with meta
// intents (see #9265).
log.Event(ctx, "updating LHS descriptor")
if err := txn.Run(ctx, b); err != nil {
return err
}
}
// Log the split into the range event log.
// TODO(spencer): event logging API should accept a batch
// instead of a transaction; there's no reason this logging
// shouldn't be done in parallel via the batch with the updated
// range addressing.
if err := r.store.logSplit(ctx, txn, leftDesc, *rightDesc); err != nil {
return err
}
b := txn.NewBatch()
// Create range descriptor for right hand side of the split.
rightDescKey := keys.RangeDescriptorKey(rightDesc.StartKey)
if err := updateRangeDescriptor(b, rightDescKey, nil, *rightDesc); err != nil {
return err
}
// Update range descriptor addressing record(s).
if err := splitRangeAddressing(b, rightDesc, &leftDesc); err != nil {
return err
}
// End the transaction manually, instead of letting RunTransaction
// loop do it, in order to provide a split trigger.
b.AddRawRequest(&roachpb.EndTransactionRequest{
Commit: true,
InternalCommitTrigger: &roachpb.InternalCommitTrigger{
SplitTrigger: &roachpb.SplitTrigger{
LeftDesc: leftDesc,
RightDesc: *rightDesc,
},
},
})
// Commit txn with final batch (RHS descriptor and meta).
log.Event(ctx, "commit txn with batch containing RHS descriptor and meta records")
return txn.Run(ctx, b)
}); err != nil {
// The ConditionFailedError can occur because the descriptors acting
// as expected values in the CPuts used to update the left or right
// range descriptors are picked outside the transaction. Return
// ConditionFailedError in the error detail so that the command can be
// retried.
pErr := roachpb.NewError(err)
if msg, ok := maybeDescriptorChangedError(desc, err); ok {
pErr.Message = fmt.Sprintf("split at key %s failed: %s", splitKey, msg)
} else {
pErr.Message = fmt.Sprintf("split at key %s failed: %s", splitKey, err)
}
return reply, true, pErr
}
return reply, true, nil
}
// splitTrigger is called on a successful commit of a transaction
// containing an AdminSplit operation. It copies the AbortSpan for
// the new range and recomputes stats for both the existing, left hand
// side (LHS) range and the right hand side (RHS) range. For
// performance it only computes the stats for the original range (the
// left hand side) and infers the RHS stats by subtracting from the
// original stats. We compute the LHS stats because the split key
// computation ensures that we do not create large LHS
// ranges. However, this optimization is only possible if the stats
// are fully accurate. If they contain estimates, stats for both the
// LHS and RHS are computed.
//
// Splits are complicated. A split is initiated when a replica receives an
// AdminSplit request. Note that this request (and other "admin" requests)
// differs from normal requests in that it doesn't go through Raft but instead
// allows the lease holder Replica to act as the orchestrator for the
// distributed transaction that performs the split. As such, this request is
// only executed on the lease holder replica and the request is redirected to
// the lease holder if the recipient is a follower.
//
// Splits do not require the lease for correctness (which is good, because we
// only check that the lease is held at the beginning of the operation, and
// have no way to ensure that it is continually held until the end). Followers
// could perform splits too, and the only downside would be that if two splits
// were attempted concurrently (or a split and a ChangeReplicas), one would
// fail. The lease is used to designate one replica for this role and avoid
// wasting time on splits that may fail.
//
// The processing of splits is divided into two phases. The first phase occurs
// in Replica.AdminSplit. In that phase, the split-point is computed, and a
// transaction is started which updates both the LHS and RHS range descriptors
// and the meta range addressing information. (If we're splitting a meta2 range
// we'll be updating the meta1 addressing, otherwise we'll be updating the
// meta2 addressing). That transaction includes a special SplitTrigger flag on
// the EndTransaction request. Like all transactions, the requests within the
// transaction are replicated via Raft, including the EndTransaction request.
//
// The second phase of split processing occurs when each replica for the range
// encounters the SplitTrigger. Processing of the SplitTrigger happens below,
// in Replica.splitTrigger. The processing of the SplitTrigger occurs in two
// stages. The first stage operates within the context of an engine.Batch and
// updates all of the on-disk state for the old and new ranges atomically. The
// second stage is invoked when the batch commits and updates the in-memory
// state, creating the new replica in memory and populating its timestamp cache
// and registering it with the store.
//
// There is lots of subtlety here. The easy scenario is that all of the
// replicas process the SplitTrigger before processing any Raft message for RHS
// (right hand side) of the newly split range. Something like:
//