forked from dgraph-io/dgraph
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mvcc.go
458 lines (418 loc) · 10.6 KB
/
mvcc.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
/*
* Copyright (C) 2017 Dgraph Labs, Inc. and Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package posting
import (
"bytes"
"context"
"math"
"sort"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/dgraph-io/badger"
"github.com/dgraph-io/dgraph/protos"
"github.com/dgraph-io/dgraph/x"
farm "github.com/dgryski/go-farm"
)
var (
ErrConflict = x.Errorf("Conflicts with pending transaction")
ErrTsTooOld = x.Errorf("Transaction is too old")
txns *transactions
txnMarks *x.WaterMark // Used to find out till which index we can snapshot.
)
func init() {
txns = new(transactions)
txns.m = make(map[uint64]*Txn)
txnMarks = &x.WaterMark{Name: "Transaction watermark"}
txnMarks.Init()
}
func TxnMarks() *x.WaterMark {
return txnMarks
}
func Txns() *transactions {
return txns
}
type delta struct {
key []byte
posting *protos.Posting
}
type Txn struct {
StartTs uint64
// atomic
shouldAbort uint32
// Fields which can changed after init
sync.Mutex
deltas []delta
// Stores list of proposal indexes belonging to the transaction, the watermark would
// be marked as done only when it's committed.
Indices []uint64
}
type transactions struct {
x.SafeMutex
m map[uint64]*Txn
}
func (t *transactions) MinTs() uint64 {
t.Lock()
defer t.Unlock()
var minTs uint64
for ts := range t.m {
if ts < minTs || minTs == 0 {
minTs = ts
}
}
return minTs
}
// Returns startTs of all pending transactions started upto 10000 raft log
// entries after last snapshot if the memory consumed by all raft log entries
// is high.
func (t *transactions) TxnsSinceSnapshot() []uint64 {
lastSnapshotIdx := TxnMarks().DoneUntil()
var timestamps []uint64
t.Lock()
defer t.Unlock()
numKeys := 0
for _, txn := range t.m {
lenDelta, index := txn.lenAndStartIdx()
if index-lastSnapshotIdx <= 10000 {
timestamps = append(timestamps, txn.StartTs)
}
numKeys += lenDelta
}
// Users can do transactions which mutates few edges, numKeys gives us
// a good estimation of space consumed by raft log entries
if numKeys < 10<<20 { // 500MB considering average size of posting to be 50bytes.
return nil
}
return timestamps
}
func (t *transactions) Reset() {
t.Lock()
defer t.Unlock()
for _, txn := range t.m {
txn.done()
}
t.m = make(map[uint64]*Txn)
}
func (t *transactions) Iterate(ok func(key []byte) bool) []uint64 {
t.RLock()
defer t.RUnlock()
var timestamps []uint64
for _, txn := range t.m {
if txn.conflicts(ok) {
timestamps = append(timestamps, txn.StartTs)
}
}
return timestamps
}
func (t *Txn) lenAndStartIdx() (int, uint64) {
t.Lock()
defer t.Unlock()
x.AssertTrue(len(t.Indices) > 0)
return len(t.deltas), t.Indices[0]
}
func (t *Txn) conflicts(ok func(key []byte) bool) bool {
t.Lock()
defer t.Unlock()
for _, d := range t.deltas {
if ok(d.key) {
return true
}
}
return false
}
func (t *transactions) Get(startTs uint64) *Txn {
t.RLock()
defer t.RUnlock()
return t.m[startTs]
}
func (t *transactions) Done(startTs uint64) {
t.Lock()
defer t.Unlock()
txn, ok := t.m[startTs]
if !ok {
return
}
txn.done()
delete(t.m, startTs)
}
func (t *Txn) done() {
t.Lock()
defer t.Unlock()
// All indices should have been added by now.
TxnMarks().DoneMany(t.Indices)
}
// LastIndex returns the index of last prewrite proposal associated with
// the transaction.
func (t *Txn) LastIndex() uint64 {
t.Lock()
defer t.Unlock()
if l := len(t.Indices); l > 0 {
return t.Indices[l-1]
}
return 0
}
func (t *transactions) PutOrMergeIndex(src *Txn) *Txn {
t.Lock()
defer t.Unlock()
dst := t.m[src.StartTs]
if dst == nil {
t.m[src.StartTs] = src
return src
}
x.AssertTrue(src.StartTs == dst.StartTs)
dst.Indices = append(dst.Indices, src.Indices...)
return dst
}
func (t *Txn) SetAbort() {
atomic.StoreUint32(&t.shouldAbort, 1)
}
func (t *Txn) ShouldAbort() bool {
return atomic.LoadUint32(&t.shouldAbort) > 0
}
func (t *Txn) AddDelta(key []byte, p *protos.Posting) {
t.Lock()
defer t.Unlock()
t.deltas = append(t.deltas, delta{key: key, posting: p})
}
func (t *Txn) Fill(ctx *protos.TxnContext) {
t.Lock()
defer t.Unlock()
t.fill(ctx)
}
func (t *Txn) fill(ctx *protos.TxnContext) {
ctx.StartTs = t.StartTs
for _, d := range t.deltas {
fp := farm.Fingerprint64(d.key)
ctx.Keys = append(ctx.Keys, strconv.FormatUint(fp, 36))
}
}
// Don't call this for schema mutations. Directly commit them.
func (tx *Txn) CommitMutations(ctx context.Context, commitTs uint64) error {
tx.Lock()
defer tx.Unlock()
if tx.ShouldAbort() {
return ErrInvalidTxn
}
txn := pstore.NewTransactionAt(commitTs, true)
defer txn.Discard()
// Sort by keys so that we have all postings for same pl side by side.
sort.SliceStable(tx.deltas, func(i, j int) bool {
return bytes.Compare(tx.deltas[i].key, tx.deltas[j].key) < 0
})
var prevKey []byte
var pl *protos.PostingList
i := 0
for i < len(tx.deltas) {
d := tx.deltas[i]
if !bytes.Equal(prevKey, d.key) {
plist := Get(d.key)
if plist.AlreadyCommitted(tx.StartTs) {
// Delta already exists, so skip the key
// There won't be any race from lru eviction, because we don't
// commit in memory unless we write delta to disk.
i++
for i < len(tx.deltas) && bytes.Equal(tx.deltas[i].key, d.key) {
i++
}
continue
}
pl = new(protos.PostingList)
}
prevKey = d.key
var meta byte
d.posting.CommitTs = commitTs
if d.posting.Op == Del && bytes.Equal(d.posting.Value, []byte(x.Star)) {
pl.Postings = pl.Postings[:0]
meta = BitCompletePosting // Indicates that this is the full posting list.
} else {
midx := sort.Search(len(pl.Postings), func(idx int) bool {
mp := pl.Postings[idx]
return d.posting.Uid <= mp.Uid
})
if midx >= len(pl.Postings) {
pl.Postings = append(pl.Postings, d.posting)
} else if pl.Postings[midx].Uid == d.posting.Uid {
// Replace
pl.Postings[midx] = d.posting
} else {
pl.Postings = append(pl.Postings, nil)
copy(pl.Postings[midx+1:], pl.Postings[midx:])
pl.Postings[midx] = d.posting
}
meta = bitDeltaPosting
}
val, err := pl.Marshal()
x.Check(err)
if err = txn.SetWithMeta([]byte(d.key), val, meta); err == badger.ErrTxnTooBig {
if err := txn.CommitAt(commitTs, nil); err != nil {
return err
}
txn = pstore.NewTransactionAt(commitTs, true)
if err := txn.SetWithMeta([]byte(d.key), val, meta); err != nil {
return err
}
} else if err != nil {
return err
}
i++
}
if err := txn.CommitAt(commitTs, nil); err != nil {
return err
}
return tx.commitMutationsMemory(ctx, commitTs)
}
func (tx *Txn) CommitMutationsMemory(ctx context.Context, commitTs uint64) error {
tx.Lock()
defer tx.Unlock()
return tx.commitMutationsMemory(ctx, commitTs)
}
func (tx *Txn) commitMutationsMemory(ctx context.Context, commitTs uint64) error {
for _, d := range tx.deltas {
plist := Get(d.key)
err := plist.CommitMutation(ctx, tx.StartTs, commitTs)
for err == ErrRetry {
time.Sleep(5 * time.Millisecond)
plist = Get(d.key)
err = plist.CommitMutation(ctx, tx.StartTs, commitTs)
}
if err != nil {
return err
}
}
return nil
}
func (tx *Txn) AbortMutations(ctx context.Context) error {
tx.Lock()
defer tx.Unlock()
for _, d := range tx.deltas {
plist := Get([]byte(d.key))
err := plist.AbortTransaction(ctx, tx.StartTs)
for err == ErrRetry {
time.Sleep(5 * time.Millisecond)
plist = Get(d.key)
err = plist.AbortTransaction(ctx, tx.StartTs)
}
if err != nil {
return err
}
}
atomic.StoreUint32(&tx.shouldAbort, 1)
return nil
}
func unmarshalOrCopy(plist *protos.PostingList, item *badger.Item) error {
// It's delta
val, err := item.Value()
if err != nil {
return err
}
if len(val) == 0 {
// empty pl
return nil
}
// Found complete pl, no needn't iterate more
if item.UserMeta()&BitUidPosting != 0 {
plist.Uids = make([]byte, len(val))
copy(plist.Uids, val)
} else if len(val) > 0 {
x.Check(plist.Unmarshal(val))
}
return nil
}
// constructs the posting list from the disk using the passed iterator.
// Use forward iterator with allversions enabled in iter options.
func ReadPostingList(key []byte, it *badger.Iterator) (*List, error) {
l := new(List)
l.key = key
l.activeTxns = make(map[uint64]struct{})
l.plist = new(protos.PostingList)
// Iterates from highest Ts to lowest Ts
for it.Valid() {
item := it.Item()
if !bytes.Equal(item.Key(), l.key) {
break
}
if l.commitTs == 0 {
l.commitTs = item.Version()
}
val, err := item.Value()
if err != nil {
return nil, err
}
if item.UserMeta()&BitCompletePosting > 0 {
if err := unmarshalOrCopy(l.plist, item); err != nil {
return nil, err
}
l.minTs = item.Version()
it.Next()
break
} else if item.UserMeta()&bitDeltaPosting > 0 {
var pl protos.PostingList
x.Check(pl.Unmarshal(val))
for _, mpost := range pl.Postings {
// commitTs, startTs are meant to be only in memory, not
// stored on disk.
mpost.CommitTs = item.Version()
l.mlayer = append(l.mlayer, mpost)
}
} else {
x.Fatalf("unexpected meta: %d", item.UserMeta())
}
it.Next()
}
// Sort by Uid, Ts
sort.Slice(l.mlayer, func(i, j int) bool {
if l.mlayer[i].Uid != l.mlayer[j].Uid {
return l.mlayer[i].Uid < l.mlayer[j].Uid
}
return l.mlayer[i].CommitTs >= l.mlayer[j].CommitTs
})
return l, nil
}
func getNew(key []byte, pstore *badger.ManagedDB) (*List, error) {
l := new(List)
l.key = key
l.activeTxns = make(map[uint64]struct{})
l.plist = new(protos.PostingList)
txn := pstore.NewTransactionAt(math.MaxUint64, false)
defer txn.Discard()
item, err := txn.Get(key)
if err == badger.ErrKeyNotFound {
return l, nil
}
if err != nil {
return l, err
}
if item.UserMeta()&BitCompletePosting > 0 {
err = unmarshalOrCopy(l.plist, item)
l.minTs = item.Version()
l.commitTs = item.Version()
} else {
iterOpts := badger.DefaultIteratorOptions
iterOpts.AllVersions = true
it := txn.NewIterator(iterOpts)
defer it.Close()
it.Seek(key)
l, err = ReadPostingList(key, it)
}
l.Lock()
size := l.calculateSize()
l.Unlock()
x.BytesRead.Add(int64(size))
atomic.StoreInt32(&l.estimatedSize, size)
return l, err
}