/
db.go
407 lines (344 loc) · 9.66 KB
/
db.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
package db
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"strconv"
"time"
"go.uber.org/zap"
"github.com/distributedio/titan/conf"
"github.com/distributedio/titan/db/store"
"github.com/distributedio/titan/metrics"
)
var (
// ErrTypeMismatch indicates object type of key is not as expect
ErrTypeMismatch = errors.New("type mismatch")
// ErrKeyNotFound key not exist
ErrKeyNotFound = errors.New("key not found")
// ErrInteger valeu is not interge
ErrInteger = errors.New("value is not an integer or out of range")
// ErrPrecision list index reach precision limitatin
ErrPrecision = errors.New("list reaches precision limitation, rebalance now")
// ErrOutOfRange index/offset out of range
ErrOutOfRange = errors.New("error index/offset out of range")
// ErrInvalidLength data length is invalid for unmarshaler"
ErrInvalidLength = errors.New("error data length is invalid for unmarshaler")
// ErrEncodingMismatch object encoding type
ErrEncodingMismatch = errors.New("error object encoding type")
// ErrStorageRetry storage err and try again later
ErrStorageRetry = errors.New("Storage err and try again later")
//ErrSetNilValue means the value corresponding to key is a non-zero value
ErrSetNilValue = errors.New("The value corresponding to key is a non-zero value")
// IsErrNotFound returns true if the key is not found, otherwise return false
IsErrNotFound = store.IsErrNotFound
// IsRetryableError returns true if the error is temporary and can be retried
IsRetryableError = store.IsRetryableError
// IsConflictError return true if the error is conflict
IsConflictError = store.IsConflictError
// sysNamespace default namespace
sysNamespace = "$sys"
// sysDatabaseID default db id
sysDatabaseID = 0
NilValue = []byte{0}
)
// Iterator store.Iterator
type Iterator store.Iterator
// DBID is the redis database ID
type DBID byte
// String returns the string format of DBID
func (id DBID) String() string {
return fmt.Sprintf("%03d", id)
}
// Bytes DBID returns a byte slice
func (id DBID) Bytes() []byte {
return []byte(id.String())
}
func toDBID(v []byte) DBID {
id, _ := strconv.Atoi(string(v))
return DBID(id)
}
// BatchGetValues issues batch requests to get values
func BatchGetValues(txn *Transaction, keys [][]byte) ([][]byte, error) {
kvs, err := store.BatchGetValues(txn.t, keys)
if err != nil {
return nil, err
}
values := make([][]byte, len(keys))
for i := range keys {
values[i] = kvs[string(keys[i])]
}
return values, nil
}
// DB is a redis compatible data structure storage
type DB struct {
Namespace string
ID DBID
kv *RedisStore
}
// RedisStore wraps store.Storage
type RedisStore struct {
store.Storage
conf *conf.TiKV
}
// Open a storage instance
func Open(conf *conf.TiKV) (*RedisStore, error) {
s, err := store.Open(conf.PdAddrs)
if err != nil {
return nil, err
}
rds := &RedisStore{Storage: s, conf: conf}
sysdb := rds.DB(sysNamespace, sysDatabaseID)
go StartGC(sysdb, &conf.GC)
go StartExpire(sysdb, &conf.Expire)
go StartZT(sysdb, &conf.ZT)
go StartTiKVGC(sysdb, &conf.TiKVGC)
return rds, nil
}
// DB returns a DB object with sepcific ID
func (rds *RedisStore) DB(namesapce string, id int) *DB {
return &DB{Namespace: namesapce, ID: DBID(id), kv: rds}
}
// Close the storage instance
func (rds *RedisStore) Close() error {
return rds.Storage.Close()
}
// Transaction supplies transaction for data structures
type Transaction struct {
t store.Transaction
db *DB
}
// Begin a transaction
func (db *DB) Begin() (*Transaction, error) {
txn, err := db.kv.Begin()
if err != nil {
return nil, err
}
return &Transaction{t: txn, db: db}, nil
}
// Prefix returns the prefix of a DB object
func (db *DB) Prefix() []byte {
return dbPrefix(db.Namespace, db.ID.Bytes())
}
// Commit a transaction
func (txn *Transaction) Commit(ctx context.Context) error {
return txn.t.Commit(ctx)
}
// Rollback a transaction
func (txn *Transaction) Rollback() error {
return txn.t.Rollback()
}
// listOption for get a list
type listOption struct {
useZip bool
}
// ListOption customize how to get a list
type ListOption func(o *listOption)
// UseZip will create a ziplist if set when the key is missing
func UseZip() ListOption {
return func(o *listOption) {
o.useZip = true
}
}
// List return a lists object, a new list is created if the key dose not exist.
func (txn *Transaction) List(key []byte, opts ...ListOption) (List, error) {
return GetList(txn, key, opts...)
}
// String returns a string object, but the object is unsafe, maybe the object is expire,or not exist
func (txn *Transaction) String(key []byte) (*String, error) {
return GetString(txn, key)
}
// Strings returns a slice of String
func (txn *Transaction) Strings(keys [][]byte) ([]*String, error) {
sobjs := make([]*String, len(keys))
tkeys := make([][]byte, len(keys))
for i, key := range keys {
tkeys[i] = MetaKey(txn.db, key)
}
mdata, err := store.BatchGetValues(txn.t, tkeys)
if err != nil {
return nil, err
}
for i, key := range keys {
obj := NewString(txn, key)
if data, ok := mdata[string(tkeys[i])]; ok {
if err := obj.decode(data); err != nil {
if logEnv := zap.L().Check(zap.DebugLevel, "Strings decoded value error"); logEnv != nil {
logEnv.Write(zap.ByteString("key", key), zap.Error(err))
}
}
}
sobjs[i] = obj
}
return sobjs, nil
}
// Kv returns a kv object
func (txn *Transaction) Kv() *Kv {
return GetKv(txn)
}
// Hash returns a hash object
func (txn *Transaction) Hash(key []byte) (*Hash, error) {
return GetHash(txn, key)
}
// Set returns a set object
func (txn *Transaction) Set(key []byte) (*Set, error) {
return GetSet(txn, key)
}
// ZSet returns a zset object
func (txn *Transaction) ZSet(key []byte) (*ZSet, error) {
return GetZSet(txn, key)
}
// LockKeys tries to lock the entries with the keys in KV store.
func (txn *Transaction) LockKeys(keys ...[]byte) error {
return store.LockKeys(txn.t, keys)
}
// MetaKey build to metakey from a redis key
func MetaKey(db *DB, key []byte) []byte {
var mkey []byte
mkey = append(mkey, []byte(db.Namespace)...)
mkey = append(mkey, ':')
mkey = append(mkey, db.ID.Bytes()...)
mkey = append(mkey, ':', 'M', ':')
mkey = append(mkey, key...)
return mkey
}
// DataKey builds a datakey from a redis key
func DataKey(db *DB, key []byte) []byte {
var dkey []byte
dkey = append(dkey, []byte(db.Namespace)...)
dkey = append(dkey, ':')
dkey = append(dkey, db.ID.Bytes()...)
dkey = append(dkey, ':', 'D', ':')
dkey = append(dkey, key...)
return dkey
}
func dbPrefix(ns string, id []byte) []byte {
prefix := []byte(ns)
prefix = append(prefix, ':')
if id != nil {
prefix = append(prefix, id...)
prefix = append(prefix, ':')
}
return prefix
}
func flushLease(txn store.Transaction, key, id []byte, interval time.Duration) error {
databytes := make([]byte, 24)
copy(databytes, id)
ts := uint64((time.Now().Add(interval).Unix()))
binary.BigEndian.PutUint64(databytes[16:], ts)
if err := txn.Set(key, databytes); err != nil {
return err
}
return nil
}
func checkLeader(txn store.Transaction, key, id []byte, interval time.Duration) (bool, error) {
val, err := txn.Get(key)
if err != nil {
if !IsErrNotFound(err) {
zap.L().Error("query leader message faild",
zap.ByteString("key", key),
zap.ByteString("id", id),
zap.Error(err))
return false, err
}
if env := zap.L().Check(zap.DebugLevel, "no leader now, create new lease"); env != nil {
env.Write(zap.ByteString("key", key),
zap.ByteString("id", id),
zap.Duration("interval", interval))
}
if err := flushLease(txn, key, id, interval); err != nil {
zap.L().Error("create lease failed",
zap.ByteString("key", key),
zap.ByteString("id", id),
zap.Duration("interval", interval),
zap.Error(err))
return false, err
}
return true, nil
}
curID := val[0:16]
ts := int64(binary.BigEndian.Uint64(val[16:]))
if time.Now().Unix() > ts {
if err := flushLease(txn, key, id, interval); err != nil {
zap.L().Error("create lease failed",
zap.ByteString("key", key),
zap.ByteString("id", id),
zap.Int64("last_ts", ts),
zap.Error(err))
return false, err
}
return true, nil
}
if bytes.Equal(curID, id) {
if err := flushLease(txn, key, id, interval); err != nil {
zap.L().Error("flush lease failed",
zap.ByteString("key", key),
zap.ByteString("curid", curID),
zap.ByteString("id", id),
zap.Error(err))
return false, err
}
return true, nil
}
return false, nil
}
func isLeader(db *DB, leader []byte, id []byte, interval time.Duration) (bool, error) {
count := 0
label := "default"
switch {
case bytes.Equal(leader, sysZTLeader):
label = "ZT"
case bytes.Equal(leader, sysGCLeader):
label = "GC"
case bytes.Equal(leader, sysExpireLeader):
label = "EX"
case bytes.Equal(leader, sysTiKVGCLeader):
label = "TGC"
}
for {
txn, err := db.Begin()
if err != nil {
zap.L().Error("transection begin failed",
zap.ByteString("leader", leader),
zap.Error(err))
continue
}
isLeader, err := checkLeader(txn.t, leader, id, interval)
mtFunc := func() {
if isLeader {
metrics.GetMetrics().IsLeaderGaugeVec.WithLabelValues(label).Set(1)
return
}
metrics.GetMetrics().IsLeaderGaugeVec.WithLabelValues(label).Set(0)
}
if err != nil {
if err := txn.Rollback(); err != nil {
return isLeader, err
}
if IsRetryableError(err) {
count++
if count < 3 {
continue
}
}
mtFunc()
return isLeader, err
}
if err := txn.Commit(context.Background()); err != nil {
if err := txn.Rollback(); err != nil {
return isLeader, err
}
if IsRetryableError(err) {
count++
if count < 3 {
continue
}
}
mtFunc()
return isLeader, err
}
mtFunc()
return isLeader, err
}
}