-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy patherrors.go
674 lines (557 loc) · 19.4 KB
/
errors.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
// 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])
package roachpb
import (
"fmt"
"github.com/cockroachdb/cockroach/pkg/util/caller"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/pkg/errors"
)
// RetryableTxnError represents a retryable transaction error - the transaction
// that caused it should be re-run.
type RetryableTxnError struct {
Msg string
TxnID *uuid.UUID
}
func (e *RetryableTxnError) Error() string {
return e.Msg
}
var _ error = &RetryableTxnError{}
func (e *InternalRetryableTxnError) Error() string {
return e.Msg
}
var _ error = &InternalRetryableTxnError{}
// NewRetryableTxnError creates a shim RetryableTxnError that
// reports the given cause when converted to String(). This can be
// used to fake/force a retry at the SQL layer.
//
// txnID is the id of the transaction that this error is supposed to cause a
// retry for. Can be nil, in which case it will cause retries for transactions
// that don't have an ID set.
// TODO(andrei): this function should really take a transaction as an argument.
// The caller (crdb_internal.force_retry) should be given access to the current
// transaction through the EvalContext.
func NewRetryableTxnError(cause string, txnID *uuid.UUID) *RetryableTxnError {
return &RetryableTxnError{
Msg: cause,
TxnID: txnID,
}
}
// ErrorUnexpectedlySet creates a string to panic with when a response (typically
// a roachpb.BatchResponse) unexpectedly has Error set in its response header.
func ErrorUnexpectedlySet(culprit, response interface{}) string {
return fmt.Sprintf("error is unexpectedly set, culprit is %T:\n%+v", culprit, response)
}
// transactionRestartError is an interface implemented by errors that cause
// a transaction to be restarted.
type transactionRestartError interface {
canRestartTransaction() TransactionRestart
}
// GetDetail returns an error detail associated with the error.
func (e *Error) GetDetail() ErrorDetailInterface {
if e == nil {
return nil
}
if e.Detail == nil {
// Unknown error detail; return the generic error.
return (*internalError)(e)
}
if err, ok := e.Detail.GetValue().(ErrorDetailInterface); ok {
return err
}
// Unknown error detail; return the generic error.
return (*internalError)(e)
}
// NewError creates an Error from the given error.
func NewError(err error) *Error {
if err == nil {
return nil
}
e := &Error{}
if intErr, ok := err.(*internalError); ok {
*e = *(*Error)(intErr)
} else if _, ok := err.(*RetryableTxnError); ok {
// This shouldn't happen; RetryableTxnError should never be converted back
// into a pErr because it might lead to the wrong transaction being retried.
// If this conversation were attempted, it'd be a sign of a pErr having been
// converted to an error which is now being converted back to a pErr.
panic("RetryableTxnError being converted back to pErr.")
} else {
e.setGoError(err)
}
return e
}
// NewErrorWithTxn creates an Error from the given error and a transaction.
func NewErrorWithTxn(err error, txn *Transaction) *Error {
e := NewError(err)
e.SetTxn(txn)
return e
}
// NewErrorf creates an Error from the given error message. It is a
// passthrough to fmt.Errorf, with an additional prefix containing the
// filename and line number.
func NewErrorf(format string, a ...interface{}) *Error {
// Cannot use errors.Errorf here due to cyclic dependency.
file, line, _ := caller.Lookup(1)
s := fmt.Sprintf("%s:%d: ", file, line)
return NewError(fmt.Errorf(s+format, a...))
}
// String implements fmt.Stringer.
func (e *Error) String() string {
if e == nil {
return "<nil>"
}
return e.Message
}
type internalError Error
func (e *internalError) Error() string {
return (*Error)(e).String()
}
func (e *internalError) message(_ *Error) string {
return (*Error)(e).String()
}
func (e *internalError) canRestartTransaction() TransactionRestart {
return e.TransactionRestart
}
var _ ErrorDetailInterface = &internalError{}
// ErrorDetailInterface is an interface for each error detail.
type ErrorDetailInterface interface {
error
// message returns an error message.
message(*Error) string
}
// GoError returns a Go error converted from Error.
func (e *Error) GoError() error {
if e == nil {
return nil
}
if e.TransactionRestart != TransactionRestart_NONE {
if tErr, ok := e.GetDetail().(*HandledRetryableError); ok {
return &RetryableTxnError{Msg: tErr.Msg, TxnID: tErr.TxnID}
}
var txnID *uuid.UUID
if e.GetTxn() != nil {
txnID = e.GetTxn().ID
}
// Figure out what updated Transaction the error should carry.
// TransactionAbortedError will not carry a Transaction, signaling to the
// recipient to start a brand new txn.
txn := e.GetTxn()
retryPriority := int32(-1)
retryTimestamp := hlc.MinTimestamp
if txn != nil {
txnClone := txn.Clone()
txn = &txnClone
switch tErr := e.GetDetail().(type) {
case *TransactionAbortedError:
retryTimestamp = txn.Timestamp
retryPriority = txn.Priority
txn = nil
case *ReadWithinUncertaintyIntervalError:
// If the reader encountered a newer write within the uncertainty
// interval, we advance the txn's timestamp just past the last observed
// timestamp from the node.
ts, ok := txn.GetObservedTimestamp(e.OriginNode)
if !ok {
return errors.Wrapf(
tErr,
"no observed timestamp for node %d found on uncertainty restart",
e.OriginNode)
}
txn.Timestamp.Forward(ts)
case *TransactionPushError:
// Increase timestamp if applicable, ensuring that we're just ahead of
// the pushee.
txn.Timestamp.Forward(tErr.PusheeTxn.Timestamp)
txn.UpgradePriority(tErr.PusheeTxn.Priority - 1)
case *TransactionRetryError:
// Nothing to do. Transaction.Timestamp has already been forwarded to be
// ahead of any timestamp cache entries or newer versions which caused
// the restart.
case *WriteTooOldError:
// Increase the timestamp to the ts at which we've actually written.
txn.Timestamp.Forward(tErr.ActualTimestamp)
default:
// Assert that we've covered all the retryable errors.
if _, ok := tErr.(transactionRestartError); ok {
return errors.Wrapf(tErr, "retryable error of type %T not handled in "+
"pErr.GoErr(): %s", tErr, tErr)
}
}
}
err := &InternalRetryableTxnError{
Msg: e.Message,
TxnID: txnID,
Transaction: txn,
}
if retryPriority != -1 {
err.RetryPriority = &retryPriority
}
if retryTimestamp != hlc.MinTimestamp {
err.RetryTimestamp = &retryTimestamp
}
return err
}
return e.GetDetail()
}
// setGoError sets Error using err.
func (e *Error) setGoError(err error) {
if e.Message != "" {
panic("cannot re-use roachpb.Error")
}
if sErr, ok := err.(ErrorDetailInterface); ok {
e.Message = sErr.message(e)
} else {
e.Message = err.Error()
}
var isTxnError bool
if r, ok := err.(transactionRestartError); ok {
isTxnError = true
e.TransactionRestart = r.canRestartTransaction()
}
// If the specific error type exists in the detail union, set it.
detail := &ErrorDetail{}
if detail.SetValue(err) {
e.Detail = detail
} else if _, isInternalError := err.(*internalError); !isInternalError && isTxnError {
panic(fmt.Sprintf("transactionRestartError %T must be an ErrorDetail", err))
}
}
// SetTxn sets the txn and resets the error message.
// TODO(kaneda): Unexpose this method and make callers use NewErrorWithTxn.
func (e *Error) SetTxn(txn *Transaction) {
e.UnexposedTxn = txn
if txn != nil {
txnClone := txn.Clone()
e.UnexposedTxn = &txnClone
}
if e.Detail != nil {
if sErr, ok := e.Detail.GetValue().(ErrorDetailInterface); ok {
// Refresh the message as the txn is updated.
e.Message = sErr.message(e)
}
}
}
// GetTxn returns the txn.
func (e *Error) GetTxn() *Transaction {
if e == nil {
return nil
}
return e.UnexposedTxn
}
// UpdateTxn updates the txn.
func (e *Error) UpdateTxn(o *Transaction) {
if e == nil {
return
}
if e.UnexposedTxn == nil {
e.UnexposedTxn = o
} else {
e.UnexposedTxn.Update(o)
}
}
// SetErrorIndex sets the index of the error.
func (e *Error) SetErrorIndex(index int32) {
e.Index = &ErrPosition{Index: index}
}
func (e *NodeUnavailableError) Error() string {
return e.message(nil)
}
func (*NodeUnavailableError) message(_ *Error) string {
return "node unavailable; try another peer"
}
var _ ErrorDetailInterface = &NodeUnavailableError{}
func (e *NotLeaseHolderError) Error() string {
return e.message(nil)
}
func (e *NotLeaseHolderError) message(_ *Error) string {
const prefix = "[NotLeaseHolderError] "
if e.CustomMsg != "" {
return prefix + e.CustomMsg
}
if e.LeaseHolder == nil {
return fmt.Sprintf("%srange %d: replica %s not lease holder; lease holder unknown", prefix, e.RangeID, e.Replica)
} else if e.Lease != nil {
return fmt.Sprintf("%srange %d: replica %s not lease holder; current lease is %s", prefix, e.RangeID, e.Replica, e.Lease)
}
return fmt.Sprintf("%srange %d: replica %s not lease holder; replica %s is", prefix, e.RangeID, e.Replica, *e.LeaseHolder)
}
var _ ErrorDetailInterface = &NotLeaseHolderError{}
func (e *LeaseRejectedError) Error() string {
return e.message(nil)
}
func (e *LeaseRejectedError) message(_ *Error) string {
return fmt.Sprintf("cannot replace lease %s with %s: %s", e.Existing, e.Requested, e.Message)
}
var _ ErrorDetailInterface = &LeaseRejectedError{}
// NewSendError creates a SendError.
func NewSendError(msg string) *SendError {
return &SendError{Message: msg}
}
func (s SendError) Error() string {
return s.message(nil)
}
func (s *SendError) message(_ *Error) string {
return "failed to send RPC: " + s.Message
}
var _ ErrorDetailInterface = &SendError{}
// NewRangeNotFoundError initializes a new RangeNotFoundError.
func NewRangeNotFoundError(rangeID RangeID) *RangeNotFoundError {
return &RangeNotFoundError{
RangeID: rangeID,
}
}
func (e *RangeNotFoundError) Error() string {
return e.message(nil)
}
func (e *RangeNotFoundError) message(_ *Error) string {
return fmt.Sprintf("range %d was not found", e.RangeID)
}
var _ ErrorDetailInterface = &RangeNotFoundError{}
// NewRangeKeyMismatchError initializes a new RangeKeyMismatchError.
func NewRangeKeyMismatchError(start, end Key, desc *RangeDescriptor) *RangeKeyMismatchError {
if desc != nil && !desc.IsInitialized() {
// We must never send uninitialized ranges back to the client (nil
// is fine) guard against regressions of #6027.
panic(fmt.Sprintf("descriptor is not initialized: %+v", desc))
}
return &RangeKeyMismatchError{
RequestStartKey: start,
RequestEndKey: end,
MismatchedRange: desc,
}
}
func (e *RangeKeyMismatchError) Error() string {
return e.message(nil)
}
func (e *RangeKeyMismatchError) message(_ *Error) string {
if e.MismatchedRange != nil {
return fmt.Sprintf("key range %s-%s outside of bounds of range %s-%s",
e.RequestStartKey, e.RequestEndKey, e.MismatchedRange.StartKey, e.MismatchedRange.EndKey)
}
return fmt.Sprintf("key range %s-%s could not be located within a range on store", e.RequestStartKey, e.RequestEndKey)
}
var _ ErrorDetailInterface = &RangeKeyMismatchError{}
// NewAmbiguousResultError initializes a new AmbiguousResultError with
// an explanatory message.
func NewAmbiguousResultError(msg string) *AmbiguousResultError {
return &AmbiguousResultError{Message: msg}
}
func (e *AmbiguousResultError) Error() string {
return e.message(nil)
}
func (e *AmbiguousResultError) message(_ *Error) string {
return fmt.Sprintf("result is ambiguous (%s)", e.Message)
}
var _ ErrorDetailInterface = &AmbiguousResultError{}
func (e *TransactionAbortedError) Error() string {
return "TransactionAbortedError: txn aborted"
}
func (e *TransactionAbortedError) message(pErr *Error) string {
return fmt.Sprintf("TransactionAbortedError: txn aborted %s", pErr.GetTxn())
}
func (*TransactionAbortedError) canRestartTransaction() TransactionRestart {
return TransactionRestart_IMMEDIATE
}
var _ ErrorDetailInterface = &TransactionAbortedError{}
var _ transactionRestartError = &TransactionAbortedError{}
func (e *HandledRetryableError) Error() string {
return e.message(nil)
}
func (e *HandledRetryableError) message(_ *Error) string {
return fmt.Sprintf("HandledRetryableError: %s", e.Msg)
}
func (*HandledRetryableError) canRestartTransaction() TransactionRestart {
// TODO(andrei): make this dependent on the type of the original error
return TransactionRestart_IMMEDIATE
}
var _ ErrorDetailInterface = &HandledRetryableError{}
var _ transactionRestartError = &HandledRetryableError{}
// NewTransactionAbortedError initializes a new TransactionAbortedError.
func NewTransactionAbortedError() *TransactionAbortedError {
return &TransactionAbortedError{}
}
// NewHandledRetryableError initializes a new HandledRetryableError.
func NewHandledRetryableError(
msg string, txnID *uuid.UUID, txn Transaction,
) *HandledRetryableError {
return &HandledRetryableError{Msg: msg, TxnID: txnID, Transaction: &txn}
}
// NewTransactionPushError initializes a new TransactionPushError.
// The argument is copied.
func NewTransactionPushError(pusheeTxn Transaction) *TransactionPushError {
// Note: this error will cause a txn restart. The error that the client
// receives contains a txn that might have a modified priority.
return &TransactionPushError{PusheeTxn: pusheeTxn.Clone()}
}
func (e *TransactionPushError) Error() string {
return e.message(nil)
}
func (e *TransactionPushError) message(pErr *Error) string {
if pErr.GetTxn() == nil {
return fmt.Sprintf("failed to push %s", e.PusheeTxn)
}
return fmt.Sprintf("txn %s failed to push %s", pErr.GetTxn(), e.PusheeTxn)
}
var _ ErrorDetailInterface = &TransactionPushError{}
var _ transactionRestartError = &TransactionPushError{}
func (*TransactionPushError) canRestartTransaction() TransactionRestart {
return TransactionRestart_IMMEDIATE
}
// NewTransactionRetryError initializes a new TransactionRetryError.
func NewTransactionRetryError() *TransactionRetryError {
return &TransactionRetryError{}
}
func (e *TransactionRetryError) Error() string {
return fmt.Sprintf("TransactionRetryError: retry txn")
}
func (e *TransactionRetryError) message(pErr *Error) string {
return fmt.Sprintf("TransactionRetryError: retry txn %s", pErr.GetTxn())
}
var _ ErrorDetailInterface = &TransactionRetryError{}
var _ transactionRestartError = &TransactionRetryError{}
func (*TransactionRetryError) canRestartTransaction() TransactionRestart {
return TransactionRestart_IMMEDIATE
}
// NewTransactionReplayError initializes a new TransactionReplayError.
func NewTransactionReplayError() *TransactionReplayError {
return &TransactionReplayError{}
}
func (e *TransactionReplayError) Error() string {
return fmt.Sprintf("replay txn")
}
func (e *TransactionReplayError) message(pErr *Error) string {
return fmt.Sprintf("replay txn %s", pErr.GetTxn())
}
var _ ErrorDetailInterface = &TransactionReplayError{}
// NewTransactionStatusError initializes a new TransactionStatusError from
// the given message.
func NewTransactionStatusError(msg string) *TransactionStatusError {
return &TransactionStatusError{Msg: msg}
}
func (e *TransactionStatusError) Error() string {
return e.Msg
}
func (e *TransactionStatusError) message(pErr *Error) string {
return fmt.Sprintf("txn %s: %s", pErr.GetTxn(), e.Msg)
}
var _ ErrorDetailInterface = &TransactionStatusError{}
func (e *WriteIntentError) Error() string {
return e.message(nil)
}
func (e *WriteIntentError) message(_ *Error) string {
var keys []Key
for _, intent := range e.Intents {
keys = append(keys, intent.Key)
}
return fmt.Sprintf("conflicting intents on %v", keys)
}
var _ ErrorDetailInterface = &WriteIntentError{}
func (e *WriteTooOldError) Error() string {
return e.message(nil)
}
func (e *WriteTooOldError) message(_ *Error) string {
return fmt.Sprintf("WriteTooOldError: write at timestamp %s too old; wrote at %s",
e.Timestamp, e.ActualTimestamp)
}
var _ ErrorDetailInterface = &WriteTooOldError{}
var _ transactionRestartError = &WriteTooOldError{}
func (*WriteTooOldError) canRestartTransaction() TransactionRestart {
return TransactionRestart_IMMEDIATE
}
// NewReadWithinUncertaintyIntervalError creates a new uncertainty retry error.
// The read and existing timestamps are purely informational and used for
// formatting the error message.
func NewReadWithinUncertaintyIntervalError(
readTS, existingTS hlc.Timestamp,
) *ReadWithinUncertaintyIntervalError {
return &ReadWithinUncertaintyIntervalError{
ReadTimestamp: readTS,
ExistingTimestamp: existingTS,
}
}
func (e *ReadWithinUncertaintyIntervalError) Error() string {
return e.message(nil)
}
func (e *ReadWithinUncertaintyIntervalError) message(_ *Error) string {
return fmt.Sprintf("ReadWithinUncertaintyIntervalError: read at time %s encountered "+
"previous write with future timestamp %s within uncertainty interval",
e.ReadTimestamp, e.ExistingTimestamp)
}
var _ ErrorDetailInterface = &ReadWithinUncertaintyIntervalError{}
var _ transactionRestartError = &ReadWithinUncertaintyIntervalError{}
func (*ReadWithinUncertaintyIntervalError) canRestartTransaction() TransactionRestart {
return TransactionRestart_IMMEDIATE
}
func (e *OpRequiresTxnError) Error() string {
return e.message(nil)
}
func (e *OpRequiresTxnError) message(_ *Error) string {
return "the operation requires transactional context"
}
var _ ErrorDetailInterface = &OpRequiresTxnError{}
func (e *ConditionFailedError) Error() string {
return e.message(nil)
}
func (e *ConditionFailedError) message(_ *Error) string {
return fmt.Sprintf("unexpected value: %s", e.ActualValue)
}
var _ ErrorDetailInterface = &ConditionFailedError{}
func (e *RaftGroupDeletedError) Error() string {
return e.message(nil)
}
func (*RaftGroupDeletedError) message(_ *Error) string {
return "raft group deleted"
}
var _ ErrorDetailInterface = &RaftGroupDeletedError{}
func (e *ReplicaCorruptionError) Error() string {
return e.message(nil)
}
func (e *ReplicaCorruptionError) message(_ *Error) string {
msg := fmt.Sprintf("replica corruption (processed=%t)", e.Processed)
if e.ErrorMsg != "" {
msg += ": " + e.ErrorMsg
}
return msg
}
var _ ErrorDetailInterface = &ReplicaCorruptionError{}
// NewReplicaTooOldError initializes a new ReplicaTooOldError.
func NewReplicaTooOldError(replicaID ReplicaID) *ReplicaTooOldError {
return &ReplicaTooOldError{
ReplicaID: replicaID,
}
}
func (e *ReplicaTooOldError) Error() string {
return e.message(nil)
}
func (*ReplicaTooOldError) message(_ *Error) string {
return "sender replica too old, discarding message"
}
var _ ErrorDetailInterface = &ReplicaTooOldError{}
// NewStoreNotFoundError initializes a new StoreNotFoundError.
func NewStoreNotFoundError(storeID StoreID) *StoreNotFoundError {
return &StoreNotFoundError{
StoreID: storeID,
}
}
func (e *StoreNotFoundError) Error() string {
return e.message(nil)
}
func (e *StoreNotFoundError) message(_ *Error) string {
return fmt.Sprintf("store %d was not found", e.StoreID)
}
var _ ErrorDetailInterface = &StoreNotFoundError{}