-
Notifications
You must be signed in to change notification settings - Fork 515
/
snapshot.go
271 lines (245 loc) · 7.43 KB
/
snapshot.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
// Copyright 2015 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package tikv
import (
"bytes"
"context"
"encoding/json"
"fmt"
pb "github.com/pingcap-incubator/tinykv/proto/pkg/kvrpcpb"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb/kv"
"strings"
"github.com/pingcap/tidb/store/tikv/tikvrpc"
"github.com/pingcap/tidb/tablecodec"
"github.com/pingcap/tidb/util/logutil"
"go.uber.org/zap"
)
var (
_ kv.Snapshot = (*tikvSnapshot)(nil)
)
const (
scanBatchSize = 256
)
// tikvSnapshot implements the kv.Snapshot interface.
type tikvSnapshot struct {
store *tikvStore
version kv.Version
syncLog bool
keyOnly bool
vars *kv.Variables
minCommitTSPushed
// Cache the result of BatchGet.
// The invariance is that calling BatchGet multiple times using the same start ts,
// the result should not change.
// NOTE: This representation here is different from the BatchGet API.
// cached use len(value)=0 to represent a key-value entry doesn't exist (a reliable truth from TiKV).
// In the BatchGet API, it use no key-value entry to represent non-exist.
// It's OK as long as there are no zero-byte values in the protocol.
cached map[string][]byte
}
// newTiKVSnapshot creates a snapshot of an TiKV store.
func newTiKVSnapshot(store *tikvStore, ver kv.Version) *tikvSnapshot {
return &tikvSnapshot{
store: store,
version: ver,
vars: kv.DefaultVars,
minCommitTSPushed: minCommitTSPushed{
data: make(map[uint64]struct{}, 5),
},
}
}
func (s *tikvSnapshot) setSnapshotTS(ts uint64) {
// Invalidate cache if the snapshotTS change!
s.version.Ver = ts
s.cached = nil
// And also the minCommitTS pushed information.
s.minCommitTSPushed.data = make(map[uint64]struct{}, 5)
}
// Get gets the value for key k from snapshot.
func (s *tikvSnapshot) Get(ctx context.Context, k kv.Key) ([]byte, error) {
ctx = context.WithValue(ctx, txnStartKey, s.version.Ver)
val, err := s.get(NewBackoffer(ctx, getMaxBackoff), k)
if err != nil {
return nil, errors.Trace(err)
}
if len(val) == 0 {
return nil, kv.ErrNotExist
}
return val, nil
}
func (s *tikvSnapshot) get(bo *Backoffer, k kv.Key) ([]byte, error) {
// Check the cached values first.
if s.cached != nil {
if value, ok := s.cached[string(k)]; ok {
return value, nil
}
}
failpoint.Inject("snapshot-get-cache-fail", func(_ failpoint.Value) {
if bo.ctx.Value("TestSnapshotCache") != nil {
panic("cache miss")
}
})
cli := clientHelper{
LockResolver: s.store.lockResolver,
RegionCache: s.store.regionCache,
minCommitTSPushed: &s.minCommitTSPushed,
Client: s.store.client,
}
req := tikvrpc.NewRequest(tikvrpc.CmdGet,
&pb.GetRequest{
Key: k,
Version: s.version.Ver,
}, pb.Context{})
for {
loc, err := s.store.regionCache.LocateKey(bo, k)
if err != nil {
return nil, errors.Trace(err)
}
resp, _, _, err := cli.SendReqCtx(bo, req, loc.Region, readTimeoutShort, "")
if err != nil {
return nil, errors.Trace(err)
}
regionErr, err := resp.GetRegionError()
if err != nil {
return nil, errors.Trace(err)
}
if regionErr != nil {
err = bo.Backoff(BoRegionMiss, errors.New(regionErr.String()))
if err != nil {
return nil, errors.Trace(err)
}
continue
}
if resp.Resp == nil {
return nil, errors.Trace(ErrBodyMissing)
}
cmdGetResp := resp.Resp.(*pb.GetResponse)
val := cmdGetResp.GetValue()
if keyErr := cmdGetResp.GetError(); keyErr != nil {
// You need to handle the key error here
// If the key error is a lock, there are 2 possible cases:
// 1. The transaction is during commit, wait for a while and retry.
// 2. The transaction is dead with some locks left, resolve it.
// YOUR CODE HERE (proj6).
panic("YOUR CODE HERE")
continue
}
return val, nil
}
}
// Iter return a list of key-value pair after `k`.
func (s *tikvSnapshot) Iter(k kv.Key, upperBound kv.Key) (kv.Iterator, error) {
scanner, err := newScanner(s, k, upperBound, scanBatchSize, false)
return scanner, errors.Trace(err)
}
// IterReverse creates a reversed Iterator positioned on the first entry which key is less than k.
func (s *tikvSnapshot) IterReverse(k kv.Key) (kv.Iterator, error) {
scanner, err := newScanner(s, nil, k, scanBatchSize, true)
return scanner, errors.Trace(err)
}
func extractLockFromKeyErr(keyErr *pb.KeyError) (*Lock, error) {
if locked := keyErr.GetLocked(); locked != nil {
return NewLock(locked), nil
}
return nil, extractKeyErr(keyErr)
}
func extractKeyErr(keyErr *pb.KeyError) error {
failpoint.Inject("ErrMockRetryableOnly", func(val failpoint.Value) {
if val.(bool) {
keyErr.Conflict = nil
keyErr.Retryable = "mock retryable error"
}
})
if keyErr.Conflict != nil {
return newWriteConflictError(keyErr.Conflict)
}
if keyErr.Retryable != "" {
notFoundDetail := prettyLockNotFoundKey(keyErr.GetRetryable())
return kv.ErrTxnRetryable.GenWithStackByArgs(keyErr.GetRetryable() + " " + notFoundDetail)
}
if keyErr.Abort != "" {
err := errors.Errorf("tikv aborts txn: %s", keyErr.GetAbort())
logutil.BgLogger().Warn("2PC failed", zap.Error(err))
return errors.Trace(err)
}
return errors.Errorf("unexpected KeyError: %s", keyErr.String())
}
func prettyLockNotFoundKey(rawRetry string) string {
if !strings.Contains(rawRetry, "TxnLockNotFound") {
return ""
}
start := strings.Index(rawRetry, "[")
if start == -1 {
return ""
}
rawRetry = rawRetry[start:]
end := strings.Index(rawRetry, "]")
if end == -1 {
return ""
}
rawRetry = rawRetry[:end+1]
var key []byte
err := json.Unmarshal([]byte(rawRetry), &key)
if err != nil {
return ""
}
var buf bytes.Buffer
prettyWriteKey(&buf, key)
return buf.String()
}
func newWriteConflictError(conflict *pb.WriteConflict) error {
var buf bytes.Buffer
prettyWriteKey(&buf, conflict.Key)
buf.WriteString(" primary=")
prettyWriteKey(&buf, conflict.Primary)
return kv.ErrWriteConflict.FastGenByArgs(conflict.StartTs, conflict.ConflictTs, buf.String())
}
func prettyWriteKey(buf *bytes.Buffer, key []byte) {
tableID, indexID, indexValues, err := tablecodec.DecodeIndexKey(key)
if err == nil {
_, err1 := fmt.Fprintf(buf, "{tableID=%d, indexID=%d, indexValues={", tableID, indexID)
if err1 != nil {
logutil.BgLogger().Error("error", zap.Error(err1))
}
for _, v := range indexValues {
_, err2 := fmt.Fprintf(buf, "%s, ", v)
if err2 != nil {
logutil.BgLogger().Error("error", zap.Error(err2))
}
}
buf.WriteString("}}")
return
}
tableID, handle, err := tablecodec.DecodeRecordKey(key)
if err == nil {
_, err3 := fmt.Fprintf(buf, "{tableID=%d, handle=%d}", tableID, handle)
if err3 != nil {
logutil.BgLogger().Error("error", zap.Error(err3))
}
return
}
mKey, mField, err := tablecodec.DecodeMetaKey(key)
if err == nil {
_, err3 := fmt.Fprintf(buf, "{metaKey=true, key=%s, field=%s}", string(mKey), string(mField))
if err3 != nil {
logutil.Logger(context.Background()).Error("error", zap.Error(err3))
}
return
}
_, err4 := fmt.Fprintf(buf, "%#v", key)
if err4 != nil {
logutil.BgLogger().Error("error", zap.Error(err4))
}
}