-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathreplica_command.go
3347 lines (3084 loc) · 125 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 ([email protected])
// Author: Jiang-Ming Yang ([email protected])
// Author: Tobias Schottdorf ([email protected])
// Author: Bram Gruneir ([email protected])
package storage
import (
"bytes"
"crypto/sha512"
"encoding/binary"
"fmt"
"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/base"
"github.com/cockroachdb/cockroach/build"
"github.com/cockroachdb/cockroach/internal/client"
"github.com/cockroachdb/cockroach/keys"
"github.com/cockroachdb/cockroach/roachpb"
"github.com/cockroachdb/cockroach/storage/engine"
"github.com/cockroachdb/cockroach/storage/engine/enginepb"
"github.com/cockroachdb/cockroach/storage/storagebase"
"github.com/cockroachdb/cockroach/util/hlc"
"github.com/cockroachdb/cockroach/util/log"
"github.com/cockroachdb/cockroach/util/protoutil"
"github.com/cockroachdb/cockroach/util/timeutil"
"github.com/cockroachdb/cockroach/util/uuid"
)
var errTransactionUnsupported = errors.New("not supported within a transaction")
// ErrMsgConflictUpdatingRangeDesc is an error message that is returned by
// AdminSplit when it conflicts with some other process that updates range
// descriptors.
const ErrMsgConflictUpdatingRangeDesc = "conflict updating range descriptors"
// executeCmd switches over the method and multiplexes to execute the appropriate storage API
// command. It returns the response, an error, and a post commit trigger which
// may be actionable even in the case of an error.
// maxKeys is the number of scan results remaining for this batch
// (MaxInt64 for no limit).
func (r *Replica) executeCmd(
ctx context.Context,
raftCmdID storagebase.CmdIDKey,
index int,
batch engine.ReadWriter,
ms *enginepb.MVCCStats,
h roachpb.Header,
maxKeys int64,
args roachpb.Request,
reply roachpb.Response,
) (*PostCommitTrigger, *roachpb.Error) {
ts := h.Timestamp
if _, ok := args.(*roachpb.NoopRequest); ok {
return nil, nil
}
if err := r.checkCmdHeader(args.Header()); err != nil {
return nil, roachpb.NewErrorWithTxn(err, h.Txn)
}
// If a unittest filter was installed, check for an injected error; otherwise, continue.
if filter := r.store.ctx.TestingKnobs.TestingCommandFilter; filter != nil {
filterArgs := storagebase.FilterArgs{Ctx: ctx, CmdID: raftCmdID, Index: index,
Sid: r.store.StoreID(), Req: args, Hdr: h}
if pErr := filter(filterArgs); pErr != nil {
log.Infof(ctx, "test injecting error: %s", pErr)
return nil, pErr
}
}
// Update the node clock with the serviced request. This maintains a
// high water mark for all ops serviced, so that received ops
// without a timestamp specified are guaranteed one higher than any
// op already executed for overlapping keys.
r.store.Clock().Update(ts)
var err error
var trigger *PostCommitTrigger
var num int64
var span *roachpb.Span
// Note that responses are populated even when an error is returned.
// TODO(tschottdorf): Change that. IIRC there is nontrivial use of it currently.
switch tArgs := args.(type) {
case *roachpb.GetRequest:
resp := reply.(*roachpb.GetResponse)
*resp, trigger, err = r.Get(ctx, batch, h, *tArgs)
case *roachpb.PutRequest:
resp := reply.(*roachpb.PutResponse)
*resp, err = r.Put(ctx, batch, ms, h, *tArgs)
case *roachpb.ConditionalPutRequest:
resp := reply.(*roachpb.ConditionalPutResponse)
*resp, err = r.ConditionalPut(ctx, batch, ms, h, *tArgs)
case *roachpb.InitPutRequest:
resp := reply.(*roachpb.InitPutResponse)
*resp, err = r.InitPut(ctx, batch, ms, h, *tArgs)
case *roachpb.IncrementRequest:
resp := reply.(*roachpb.IncrementResponse)
*resp, err = r.Increment(ctx, batch, ms, h, *tArgs)
case *roachpb.DeleteRequest:
resp := reply.(*roachpb.DeleteResponse)
*resp, err = r.Delete(ctx, batch, ms, h, *tArgs)
case *roachpb.DeleteRangeRequest:
resp := reply.(*roachpb.DeleteRangeResponse)
*resp, span, num, err = r.DeleteRange(ctx, batch, ms, h, maxKeys, *tArgs)
case *roachpb.ScanRequest:
resp := reply.(*roachpb.ScanResponse)
*resp, span, num, trigger, err = r.Scan(ctx, batch, h, maxKeys, *tArgs)
case *roachpb.ReverseScanRequest:
resp := reply.(*roachpb.ReverseScanResponse)
*resp, span, num, trigger, err = r.ReverseScan(ctx, batch, h, maxKeys, *tArgs)
case *roachpb.BeginTransactionRequest:
resp := reply.(*roachpb.BeginTransactionResponse)
*resp, err = r.BeginTransaction(ctx, batch, ms, h, *tArgs)
case *roachpb.EndTransactionRequest:
resp := reply.(*roachpb.EndTransactionResponse)
*resp, trigger, err = r.EndTransaction(ctx, batch, ms, h, *tArgs)
case *roachpb.RangeLookupRequest:
resp := reply.(*roachpb.RangeLookupResponse)
*resp, trigger, err = r.RangeLookup(ctx, batch, h, *tArgs)
case *roachpb.HeartbeatTxnRequest:
resp := reply.(*roachpb.HeartbeatTxnResponse)
*resp, err = r.HeartbeatTxn(ctx, batch, ms, h, *tArgs)
case *roachpb.GCRequest:
resp := reply.(*roachpb.GCResponse)
*resp, trigger, err = r.GC(ctx, batch, ms, h, *tArgs)
case *roachpb.PushTxnRequest:
resp := reply.(*roachpb.PushTxnResponse)
*resp, err = r.PushTxn(ctx, batch, ms, h, *tArgs)
case *roachpb.ResolveIntentRequest:
resp := reply.(*roachpb.ResolveIntentResponse)
*resp, err = r.ResolveIntent(ctx, batch, ms, h, *tArgs)
case *roachpb.ResolveIntentRangeRequest:
resp := reply.(*roachpb.ResolveIntentRangeResponse)
*resp, err = r.ResolveIntentRange(ctx, batch, ms, h, *tArgs)
case *roachpb.MergeRequest:
resp := reply.(*roachpb.MergeResponse)
*resp, err = r.Merge(ctx, batch, ms, h, *tArgs)
case *roachpb.TruncateLogRequest:
resp := reply.(*roachpb.TruncateLogResponse)
*resp, trigger, err = r.TruncateLog(ctx, batch, ms, h, *tArgs)
case *roachpb.RequestLeaseRequest:
resp := reply.(*roachpb.RequestLeaseResponse)
*resp, trigger, err = r.RequestLease(ctx, batch, ms, h, *tArgs)
case *roachpb.TransferLeaseRequest:
resp := reply.(*roachpb.RequestLeaseResponse)
*resp, trigger, err = r.TransferLease(ctx, batch, ms, h, *tArgs)
case *roachpb.LeaseInfoRequest:
resp := reply.(*roachpb.LeaseInfoResponse)
*resp, err = r.LeaseInfo(ctx, *tArgs)
case *roachpb.ComputeChecksumRequest:
resp := reply.(*roachpb.ComputeChecksumResponse)
*resp, trigger, err = r.ComputeChecksum(ctx, batch, ms, h, *tArgs)
case *roachpb.DeprecatedVerifyChecksumRequest:
case *roachpb.ChangeFrozenRequest:
resp := reply.(*roachpb.ChangeFrozenResponse)
*resp, trigger, err = r.ChangeFrozen(ctx, batch, ms, h, *tArgs)
default:
err = errors.Errorf("unrecognized command %s", args.Method())
}
// Set the ResumeSpan and NumKeys.
header := reply.Header()
header.NumKeys = num
header.ResumeSpan = span
reply.SetHeader(header)
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 trigger, pErr
}
func intentsToTrigger(intents []roachpb.Intent, args roachpb.Request) *PostCommitTrigger {
if len(intents) > 0 {
return &PostCommitTrigger{intents: []intentsWithArg{{args: args, intents: intents}}}
}
return nil
}
// Get returns the value for a specified key.
func (r *Replica) Get(
ctx context.Context, batch engine.ReadWriter, h roachpb.Header, args roachpb.GetRequest,
) (roachpb.GetResponse, *PostCommitTrigger, error) {
var reply roachpb.GetResponse
val, intents, err := engine.MVCCGet(ctx, batch, args.Key, h.Timestamp, h.ReadConsistency == roachpb.CONSISTENT, h.Txn)
reply.Value = val
return reply, intentsToTrigger(intents, &args), err
}
// Put sets the value for a specified key.
func (r *Replica) Put(
ctx context.Context,
batch engine.ReadWriter,
ms *enginepb.MVCCStats,
h roachpb.Header,
args roachpb.PutRequest,
) (roachpb.PutResponse, error) {
var reply roachpb.PutResponse
ts := hlc.ZeroTimestamp
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 reply, engine.MVCCBlindPut(ctx, batch, ms, args.Key, ts, args.Value, h.Txn)
}
return reply, engine.MVCCPut(ctx, batch, ms, args.Key, ts, args.Value, h.Txn)
}
// ConditionalPut sets the value for a specified key only if
// the expected value matches. If not, the return value contains
// the actual value.
func (r *Replica) ConditionalPut(
ctx context.Context,
batch engine.ReadWriter,
ms *enginepb.MVCCStats,
h roachpb.Header,
args roachpb.ConditionalPutRequest,
) (roachpb.ConditionalPutResponse, error) {
var reply roachpb.ConditionalPutResponse
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 reply, engine.MVCCBlindConditionalPut(ctx, batch, ms, args.Key, h.Timestamp, args.Value, args.ExpValue, h.Txn)
}
return reply, engine.MVCCConditionalPut(ctx, batch, ms, args.Key, h.Timestamp, args.Value, args.ExpValue, h.Txn)
}
// InitPut 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 (r *Replica) InitPut(
ctx context.Context,
batch engine.ReadWriter,
ms *enginepb.MVCCStats,
h roachpb.Header,
args roachpb.InitPutRequest,
) (roachpb.InitPutResponse, error) {
var reply roachpb.InitPutResponse
return reply, engine.MVCCInitPut(ctx, batch, ms, args.Key, h.Timestamp, args.Value, h.Txn)
}
// Increment 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 (r *Replica) Increment(
ctx context.Context,
batch engine.ReadWriter,
ms *enginepb.MVCCStats,
h roachpb.Header,
args roachpb.IncrementRequest,
) (roachpb.IncrementResponse, error) {
var reply roachpb.IncrementResponse
newVal, err := engine.MVCCIncrement(ctx, batch, ms, args.Key, h.Timestamp, h.Txn, args.Increment)
reply.NewValue = newVal
return reply, err
}
// Delete deletes the key and value specified by key.
func (r *Replica) Delete(
ctx context.Context,
batch engine.ReadWriter,
ms *enginepb.MVCCStats,
h roachpb.Header,
args roachpb.DeleteRequest,
) (roachpb.DeleteResponse, error) {
var reply roachpb.DeleteResponse
return reply, engine.MVCCDelete(ctx, batch, ms, args.Key, h.Timestamp, h.Txn)
}
// DeleteRange deletes the range of key/value pairs specified by
// start and end keys.
func (r *Replica) DeleteRange(
ctx context.Context,
batch engine.ReadWriter,
ms *enginepb.MVCCStats,
h roachpb.Header,
maxKeys int64,
args roachpb.DeleteRangeRequest,
) (roachpb.DeleteRangeResponse, *roachpb.Span, int64, error) {
var reply roachpb.DeleteRangeResponse
deleted, resumeSpan, num, err := engine.MVCCDeleteRange(
ctx, batch, ms, args.Key, args.EndKey, maxKeys, h.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
}
}
return reply, resumeSpan, num, err
}
// Scan 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 (r *Replica) Scan(
ctx context.Context,
batch engine.ReadWriter,
h roachpb.Header,
maxKeys int64,
args roachpb.ScanRequest,
) (roachpb.ScanResponse, *roachpb.Span, int64, *PostCommitTrigger, error) {
rows, resumeSpan, intents, err := engine.MVCCScan(ctx, batch, args.Key, args.EndKey, maxKeys, h.Timestamp,
h.ReadConsistency == roachpb.CONSISTENT, h.Txn)
return roachpb.ScanResponse{Rows: rows}, resumeSpan, int64(len(rows)), intentsToTrigger(intents, &args), err
}
// ReverseScan 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 (r *Replica) ReverseScan(
ctx context.Context,
batch engine.ReadWriter,
h roachpb.Header,
maxKeys int64,
args roachpb.ReverseScanRequest,
) (roachpb.ReverseScanResponse, *roachpb.Span, int64, *PostCommitTrigger, error) {
rows, resumeSpan, intents, err := engine.MVCCReverseScan(ctx, batch, args.Key, args.EndKey, maxKeys,
h.Timestamp, h.ReadConsistency == roachpb.CONSISTENT, h.Txn)
return roachpb.ReverseScanResponse{Rows: rows}, resumeSpan, int64(len(rows)), intentsToTrigger(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
}
// BeginTransaction 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 (r *Replica) BeginTransaction(
ctx context.Context,
batch engine.ReadWriter,
ms *enginepb.MVCCStats,
h roachpb.Header,
args roachpb.BeginTransactionRequest,
) (roachpb.BeginTransactionResponse, error) {
var reply roachpb.BeginTransactionResponse
if err := verifyTransaction(h, &args); err != nil {
return reply, err
}
key := keys.TransactionKey(h.Txn.Key, h.Txn.ID)
clonedTxn := h.Txn.Clone()
reply.Txn = &clonedTxn
// Verify transaction does not already exist.
txn := roachpb.Transaction{}
ok, err := engine.MVCCGetProto(ctx, batch, key, hlc.ZeroTimestamp, true, nil, &txn)
if err != nil {
return reply, err
}
if ok {
switch txn.Status {
case roachpb.ABORTED:
// Check whether someone has come in ahead and already aborted the
// txn.
return reply, roachpb.NewTransactionAbortedError()
case roachpb.PENDING:
if h.Txn.Epoch > txn.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(&txn)
} 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 reply, roachpb.NewTransactionRetryError()
}
case roachpb.COMMITTED:
return reply, roachpb.NewTransactionStatusError(
fmt.Sprintf("BeginTransaction can't overwrite %s", txn),
)
default:
return reply, roachpb.NewTransactionStatusError(
fmt.Sprintf("bad txn state: %s", txn),
)
}
}
r.mu.Lock()
threshold := r.mu.state.TxnSpanGCThreshold
r.mu.Unlock()
// 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 txn.LastActive().Less(threshold) {
return reply, roachpb.NewTransactionAbortedError()
}
// Write the txn record.
reply.Txn.Writing = true
return reply, engine.MVCCPutProto(ctx, batch, ms, key, hlc.ZeroTimestamp, nil, reply.Txn)
}
// EndTransaction 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 (r *Replica) EndTransaction(
ctx context.Context,
batch engine.ReadWriter,
ms *enginepb.MVCCStats,
h roachpb.Header,
args roachpb.EndTransactionRequest,
) (roachpb.EndTransactionResponse, *PostCommitTrigger, error) {
var reply roachpb.EndTransactionResponse
if err := verifyTransaction(h, &args); err != nil {
return reply, nil, err
}
key := keys.TransactionKey(h.Txn.Key, h.Txn.ID)
// Fetch existing transaction.
reply.Txn = &roachpb.Transaction{}
if ok, err := engine.MVCCGetProto(
ctx, batch, key, hlc.ZeroTimestamp, true, nil, reply.Txn,
); err != nil {
return reply, nil, err
} else if !ok {
// Return a fresh empty reply because there's an empty Transaction
// proto in our existing one.
return roachpb.EndTransactionResponse{},
nil, roachpb.NewTransactionStatusError("does not exist")
}
// 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 reply, nil, 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.
externalIntents := r.resolveLocalIntents(ctx, batch, ms, args, reply.Txn)
if err := updateTxnWithExternalIntents(
ctx, batch, ms, args, reply.Txn, externalIntents,
); err != nil {
return reply, nil, err
}
return reply, intentsToTrigger(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 reply,
intentsToTrigger(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 reply, nil, 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 reply, nil, roachpb.NewTransactionStatusError(
fmt.Sprintf("timestamp regression: %s", h.Txn.OrigTimestamp),
)
}
default:
return reply, nil, 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) {
reply.Txn.Status = roachpb.ABORTED
// FIXME(#3037):
// If the deadline has lapsed, return all the intents for
// resolution. Unfortunately, since we're (a) returning an error,
// and (b) not able to write on error (see #1989), we can't write
// ABORTED into the master transaction record, which remains
// PENDING, and that's pretty bad.
return reply,
intentsToTrigger(roachpb.AsIntents(args.IntentSpans, reply.Txn), &args),
roachpb.NewTransactionAbortedError()
}
// Set transaction status to COMMITTED or ABORTED as per the
// args.Commit parameter.
if args.Commit {
if isEndTransactionTriggeringRetryError(h.Txn, reply.Txn) {
return reply, nil, roachpb.NewTransactionRetryError()
}
reply.Txn.Status = roachpb.COMMITTED
} else {
reply.Txn.Status = roachpb.ABORTED
}
externalIntents := r.resolveLocalIntents(ctx, batch, ms, args, reply.Txn)
if err := updateTxnWithExternalIntents(ctx, batch, ms, args, reply.Txn, externalIntents); err != nil {
return reply, nil, err
}
// Run triggers if successfully committed.
var trigger *PostCommitTrigger
if reply.Txn.Status == roachpb.COMMITTED {
var err error
if trigger, err = r.runCommitTrigger(ctx, batch.(engine.Batch), ms, args, reply.Txn); err != nil {
return reply, nil, 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.
trigger = updateTrigger(trigger, intentsToTrigger(externalIntents, &args))
return reply, trigger, 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.Equal(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 (r *Replica) resolveLocalIntents(
ctx context.Context,
batch engine.ReadWriter,
ms *enginepb.MVCCStats,
args roachpb.EndTransactionRequest,
txn *roachpb.Transaction,
) []roachpb.Intent {
desc := r.Desc()
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
_, err := engine.MVCCResolveWriteIntentRangeUsingIter(ctx, batch, iterAndBuf, ms, intent, math.MaxInt64)
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.ID.Short(), len(args.IntentSpans))
}
return engine.MVCCDelete(ctx, batch, ms, key, hlc.ZeroTimestamp, 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.ZeroTimestamp, 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 {
log.Fatalf(context.Background(), "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 (r *Replica) runCommitTrigger(
ctx context.Context,
batch engine.Batch,
ms *enginepb.MVCCStats,
args roachpb.EndTransactionRequest,
txn *roachpb.Transaction,
) (*PostCommitTrigger, error) {
var trigger *PostCommitTrigger
ct := args.InternalCommitTrigger
if err := func() error {
if ct.GetSplitTrigger() != nil {
var err error
var postSplit *PostCommitTrigger
if *ms, postSplit, err = r.splitTrigger(
ctx, batch, *ms, ct.SplitTrigger, txn.Timestamp,
); err != nil {
return err
}
trigger = updateTrigger(trigger, postSplit)
}
if ct.GetMergeTrigger() != nil {
postMerge, err := r.mergeTrigger(ctx, batch, ms, ct.MergeTrigger, txn.Timestamp)
if err != nil {
return err
}
trigger = updateTrigger(trigger, postMerge)
}
if crt := ct.GetChangeReplicasTrigger(); crt != nil {
trigger = updateTrigger(trigger, r.changeReplicasTrigger(ctx, batch, crt))
}
if ct.GetModifiedSpanTrigger() != nil {
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 !r.ContainsKey(keys.SystemConfigSpan.Key) {
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.")
} else {
trigger = updateTrigger(trigger, &PostCommitTrigger{
maybeGossipSystemConfig: true,
})
}
}
}
return nil
}(); err != nil {
return nil, err
}
return trigger, nil
}
// RangeLookup is used to look up RangeDescriptors - a RangeDescriptor
// is a metadata structure which describes the key range and replica locations
// of a distinct range in the cluster.
//
// RangeDescriptors are stored as values in the cockroach cluster's key-value
// store. However, they are always stored using special "Range Metadata keys",
// which are "ordinary" keys with a special prefix prepended. The Range Metadata
// Key for an ordinary key can be generated with the `keys.RangeMetaKey(key)`
// function. The RangeDescriptor for the range which contains a given key can be
// retrieved by generating its Range Metadata Key and dispatching it to
// RangeLookup.
//
// Note that the Range Metadata Key sent to RangeLookup is NOT the key
// at which the desired RangeDescriptor is stored. Instead, this method returns
// the RangeDescriptor stored at the _lowest_ existing key which is _greater_
// than the given key. The returned RangeDescriptor will thus contain the
// ordinary key which was originally used to generate the Range Metadata Key
// sent to RangeLookup.
//
// The "Range Metadata Key" for a range is built by appending the end key of
// the range to the respective meta prefix.
//
// Lookups for range metadata keys usually want to read inconsistently, but
// some callers need a consistent result; both are supported.
//
// This method has an important optimization in the inconsistent case: instead
// of just returning the request RangeDescriptor, it also returns a slice of
// additional range descriptors immediately consecutive to the desired
// RangeDescriptor. This is intended to serve as a sort of caching pre-fetch,
// so that the requesting nodes can aggressively cache RangeDescriptors which
// are likely to be desired by their current workload. The Reverse flag
// specifies whether descriptors are prefetched in descending or ascending
// order.
func (r *Replica) RangeLookup(
ctx context.Context,
batch engine.ReadWriter,
h roachpb.Header,
args roachpb.RangeLookupRequest,
) (roachpb.RangeLookupResponse, *PostCommitTrigger, error) {
log.Event(ctx, "RangeLookup")
var reply roachpb.RangeLookupResponse
key, err := keys.Addr(args.Key)
if err != nil {
return reply, nil, err
}
if !key.Equal(args.Key) {
return reply, nil, errors.Errorf("illegal lookup of range-local key %q", args.Key)
}
ts, txn, consistent, rangeCount := h.Timestamp, h.Txn, h.ReadConsistency != roachpb.INCONSISTENT, int64(args.MaxRanges)
if rangeCount < 1 {
return reply, nil, errors.Errorf("range lookup specified invalid maximum range count %d: must be > 0", rangeCount)
}
var checkAndUnmarshal func(roachpb.Value) (*roachpb.RangeDescriptor, error)
var kvs []roachpb.KeyValue // kv descriptor pairs in scan order
var intents []roachpb.Intent
if !args.Reverse {
// If scanning forward, there's no special "checking": Just decode the
// descriptor and return it.
checkAndUnmarshal = func(v roachpb.Value) (*roachpb.RangeDescriptor, error) {
var rd roachpb.RangeDescriptor
if err := v.GetProto(&rd); err != nil {
return nil, err
}
return &rd, nil
}
// We want to search for the metadata key greater than
// args.Key. Scan for both the requested key and the keys immediately
// afterwards, up to MaxRanges.
startKey, endKey, err := keys.MetaScanBounds(key)
if err != nil {
return reply, nil, err
}
// Scan for descriptors.
kvs, _, intents, err = engine.MVCCScan(
ctx, batch, startKey, endKey, rangeCount, ts, consistent, txn,
)
if err != nil {
// An error here is likely a WriteIntentError when reading consistently.
return reply, nil, err
}
} else {
// Use MVCCScan to get the first range. There are three cases:
// 1. args.Key is not an endpoint of the range.
// 2a. args.Key is the start/end key of the range.
// 2b. args.Key is roachpb.KeyMax.
// In the first case, we need use the MVCCScan() to get the first
// range descriptor, because ReverseScan can't do the work. If we
// have ranges [a,c) and [c,f) and the reverse scan request's key
// range is [b,d), then d.Next() is less than "f", and so the meta
// row {f->[c,f)} would be ignored by MVCCReverseScan. In case 2a,
// the range descriptor received by MVCCScan will be filtered before
// results are returned: With ranges [c,f) and [f,z), reverse scan
// on [d,f) receives the descriptor {z->[f,z)}, which is discarded
// below since it's not being asked for. Finally, in case 2b, we
// don't even attempt the forward scan because it's neither defined
// nor required.
// Note that Meta1KeyMax is admissible: it means we're looking for
// the range descriptor that houses Meta2KeyMax, and a forward scan
// handles it correctly.
// In this case, checkAndUnmarshal is more complicated: It needs
// to weed out descriptors from the forward scan above, which could
// return a result or an intent we're not supposed to return.
checkAndUnmarshal = func(v roachpb.Value) (*roachpb.RangeDescriptor, error) {
var rd roachpb.RangeDescriptor
if err := v.GetProto(&rd); err != nil {
return nil, err
}
startKeyAddr, err := keys.Addr(keys.RangeMetaKey(rd.StartKey))
if err != nil {
return nil, err
}
if !startKeyAddr.Less(key) {
// This is the case in which we've picked up an extra descriptor
// we don't want.
return nil, nil
}