-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathoracle.go
More file actions
414 lines (359 loc) · 10 KB
/
oracle.go
File metadata and controls
414 lines (359 loc) · 10 KB
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
/*
* Copyright 2017-2025 Hypermode Inc. and Contributors
*
* 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.
*/
package posting
import (
"context"
"encoding/hex"
"math"
"sync"
"sync/atomic"
"time"
"github.com/dgraph-io/badger/v4"
"github.com/golang/glog"
ostats "go.opencensus.io/stats"
"github.com/hypermodeinc/dgraph/v24/protos/pb"
"github.com/hypermodeinc/dgraph/v24/tok/index"
"github.com/hypermodeinc/dgraph/v24/x"
)
var o *oracle
// Oracle returns the global oracle instance.
// TODO: Oracle should probably be located in worker package, instead of posting
// package now that we don't run inSnapshot anymore.
func Oracle() *oracle {
return o
}
func init() {
o = new(oracle)
o.init()
}
// Txn represents a transaction.
type Txn struct {
StartTs uint64
// atomic
shouldAbort uint32
// Fields which can changed after init
sync.Mutex
// Keeps track of conflict keys that should be used to determine if this
// transaction conflicts with another.
conflicts map[uint64]struct{}
// Keeps track of last update wall clock. We use this fact later to
// determine unhealthy, stale txns.
lastUpdate time.Time
cache *LocalCache // This pointer does not get modified.
}
// struct to implement Txn interface from vector-indexer
// acts as wrapper for dgraph *Txn
type viTxn struct {
delegate *Txn
}
func NewViTxn(delegate *Txn) *viTxn {
return &viTxn{delegate: delegate}
}
func (vt *viTxn) Find(prefix []byte, filter func([]byte) bool) (uint64, error) {
return vt.delegate.cache.Find(prefix, filter)
}
func (vt *viTxn) StartTs() uint64 {
return vt.delegate.StartTs
}
func (vt *viTxn) Get(key []byte) (rval index.Value, rerr error) {
pl, err := vt.delegate.cache.Get(key)
if err != nil {
return nil, err
}
pl.Lock()
defer pl.Unlock()
return vt.GetValueFromPostingList(pl)
}
func (vt *viTxn) GetWithLockHeld(key []byte) (rval index.Value, rerr error) {
pl, err := vt.delegate.cache.Get(key)
if err != nil {
return nil, err
}
return vt.GetValueFromPostingList(pl)
}
func (vt *viTxn) GetValueFromPostingList(pl *List) (rval index.Value, rerr error) {
value := pl.findStaticValue(vt.delegate.StartTs)
// When the posting is deleted, we find the key in the badger, but no postings in it. This should also
// return ErrKeyNotFound as that is what we except in the later functions.
if value == nil || len(value.Postings) == 0 {
return nil, ErrNoValue
}
if hasDeleteAll(value.Postings[0]) || value.Postings[0].Op == Del {
return nil, ErrNoValue
}
return value.Postings[0].Value, nil
}
func (vt *viTxn) AddMutation(ctx context.Context, key []byte, t *index.KeyValue) error {
pl, err := vt.delegate.cache.Get(key)
if err != nil {
return err
}
return pl.addMutation(ctx, vt.delegate, indexEdgeToPbEdge(t))
}
func (vt *viTxn) AddMutationWithLockHeld(ctx context.Context, key []byte, t *index.KeyValue) error {
pl, err := vt.delegate.cache.Get(key)
if err != nil {
return err
}
return pl.addMutationInternal(ctx, vt.delegate, indexEdgeToPbEdge(t))
}
func (vt *viTxn) LockKey(key []byte) {
pl, _ := vt.delegate.cache.Get(key)
pl.Lock()
}
func (vt *viTxn) UnlockKey(key []byte) {
pl, _ := vt.delegate.cache.Get(key)
pl.Unlock()
}
// NewTxn returns a new Txn instance.
func NewTxn(startTs uint64) *Txn {
return &Txn{
StartTs: startTs,
cache: NewLocalCache(startTs),
lastUpdate: time.Now(),
}
}
// Get retrieves the posting list for the given list from the local cache.
func (txn *Txn) Get(key []byte) (*List, error) {
return txn.cache.Get(key)
}
// GetFromDelta retrieves the posting list from delta cache, not from Badger.
func (txn *Txn) GetFromDelta(key []byte) (*List, error) {
return txn.cache.GetFromDelta(key)
}
func (txn *Txn) GetScalarList(key []byte) (*List, error) {
l, err := txn.cache.GetFromDelta(key)
if err != nil {
return nil, err
}
l.Lock()
defer l.Unlock()
if l.mutationMap.len() == 0 && len(l.plist.Postings) == 0 {
pl, err := txn.cache.readPostingListAt(key)
if err == badger.ErrKeyNotFound {
return l, nil
}
if err != nil {
return nil, err
}
if pl.Pack != nil {
l.plist = pl
} else {
if pl.CommitTs == 0 {
l.mutationMap.setCurrentEntries(txn.StartTs, pl)
} else {
l.mutationMap.insertCommittedPostings(pl)
}
}
}
return l, nil
}
// Update calls UpdateDeltasAndDiscardLists on the local cache.
func (txn *Txn) Update() {
txn.cache.UpdateDeltasAndDiscardLists()
}
// Store is used by tests.
func (txn *Txn) Store(pl *List) *List {
return txn.cache.SetIfAbsent(string(pl.key), pl)
}
type oracle struct {
x.SafeMutex
// max start ts given out by Zero. Do not use mutex on this, only use atomics.
maxAssigned uint64
// Keeps track of all the startTs we have seen so far, based on the mutations. Then as
// transactions are committed or aborted, we delete entries from the startTs map. When taking a
// snapshot, we need to know the minimum start ts present in the map, which represents a
// mutation which has not yet been committed or aborted. As we iterate over entries, we should
// only discard those whose StartTs is below this minimum pending start ts.
pendingTxns map[uint64]*Txn
// Used for waiting logic for transactions with startTs > maxpending so that we don't read an
// uncommitted transaction.
waiters map[uint64][]chan struct{}
}
func (o *oracle) init() {
o.waiters = make(map[uint64][]chan struct{})
o.pendingTxns = make(map[uint64]*Txn)
}
func (o *oracle) RegisterStartTs(ts uint64) *Txn {
o.Lock()
defer o.Unlock()
txn, ok := o.pendingTxns[ts]
if ok {
txn.lastUpdate = time.Now()
} else {
txn = NewTxn(ts)
o.pendingTxns[ts] = txn
}
return txn
}
func (o *oracle) CacheAt(ts uint64) *LocalCache {
o.RLock()
defer o.RUnlock()
txn, ok := o.pendingTxns[ts]
if !ok {
return nil
}
return txn.cache
}
// MinPendingStartTs returns the min start ts which is currently pending a commit or abort decision.
func (o *oracle) MinPendingStartTs() uint64 {
o.RLock()
defer o.RUnlock()
min := uint64(math.MaxUint64)
for ts := range o.pendingTxns {
if ts < min {
min = ts
}
}
return min
}
func (o *oracle) NumPendingTxns() int {
o.RLock()
defer o.RUnlock()
return len(o.pendingTxns)
}
func (o *oracle) TxnOlderThan(dur time.Duration) (res []uint64) {
o.RLock()
defer o.RUnlock()
cutoff := time.Now().Add(-dur)
for startTs, txn := range o.pendingTxns {
if txn.lastUpdate.Before(cutoff) {
res = append(res, startTs)
}
}
return res
}
func (o *oracle) addToWaiters(startTs uint64) (chan struct{}, bool) {
if startTs <= o.MaxAssigned() {
return nil, false
}
o.Lock()
defer o.Unlock()
// Check again after acquiring lock, because o.waiters is being processed serially. So, if we
// don't check here, then it's possible that we add to waiters here, but MaxAssigned has already
// moved past startTs.
if startTs <= o.MaxAssigned() {
return nil, false
}
ch := make(chan struct{})
o.waiters[startTs] = append(o.waiters[startTs], ch)
return ch, true
}
func (o *oracle) MaxAssigned() uint64 {
return atomic.LoadUint64(&o.maxAssigned)
}
func (o *oracle) WaitForTs(ctx context.Context, startTs uint64) error {
ch, ok := o.addToWaiters(startTs)
if !ok {
return nil
}
select {
case <-ch:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (o *oracle) ProcessDelta(delta *pb.OracleDelta) {
if glog.V(3) {
glog.Infof("ProcessDelta: Max Assigned: %d", delta.MaxAssigned)
glog.Infof("ProcessDelta: Group checksum: %v", delta.GroupChecksums)
for _, txn := range delta.Txns {
if txn.CommitTs == 0 {
glog.Infof("ProcessDelta Aborted: %d", txn.StartTs)
} else {
glog.Infof("ProcessDelta Committed: %d -> %d", txn.StartTs, txn.CommitTs)
}
}
}
o.Lock()
defer o.Unlock()
for _, status := range delta.Txns {
txn := o.pendingTxns[status.StartTs]
if txn != nil && status.CommitTs > 0 {
for k := range txn.cache.deltas {
IncrRollup.addKeyToBatch([]byte(k), 0)
}
}
delete(o.pendingTxns, status.StartTs)
}
curMax := o.MaxAssigned()
if delta.MaxAssigned < curMax {
return
}
// Notify the waiting cattle.
for startTs, toNotify := range o.waiters {
if startTs > delta.MaxAssigned {
continue
}
for _, ch := range toNotify {
close(ch)
}
delete(o.waiters, startTs)
}
x.AssertTrue(atomic.CompareAndSwapUint64(&o.maxAssigned, curMax, delta.MaxAssigned))
ostats.Record(context.Background(),
x.MaxAssignedTs.M(int64(delta.MaxAssigned))) // Can't access o.MaxAssigned without atomics.
}
func (o *oracle) ResetTxns() {
o.Lock()
defer o.Unlock()
o.pendingTxns = make(map[uint64]*Txn)
}
// ResetTxnForNs deletes all the pending transactions for a given namespace.
func (o *oracle) ResetTxnsForNs(ns uint64) {
txns := o.IterateTxns(func(key []byte) bool {
pk, err := x.Parse(key)
if err != nil {
glog.Errorf("error %v while parsing key %v", err, hex.EncodeToString(key))
return false
}
return x.ParseNamespace(pk.Attr) == ns
})
o.Lock()
defer o.Unlock()
for _, txn := range txns {
delete(o.pendingTxns, txn)
}
}
func (o *oracle) GetTxn(startTs uint64) *Txn {
o.RLock()
defer o.RUnlock()
return o.pendingTxns[startTs]
}
func (txn *Txn) matchesDelta(ok func(key []byte) bool) bool {
txn.Lock()
defer txn.Unlock()
for key := range txn.cache.deltas {
if ok([]byte(key)) {
return true
}
}
return false
}
// IterateTxns returns a list of start timestamps for currently pending transactions, which match
// the provided function.
func (o *oracle) IterateTxns(ok func(key []byte) bool) []uint64 {
o.RLock()
defer o.RUnlock()
var timestamps []uint64
for startTs, txn := range o.pendingTxns {
if txn.matchesDelta(ok) {
timestamps = append(timestamps, startTs)
}
}
return timestamps
}