forked from dgraph-io/dgraph
-
Notifications
You must be signed in to change notification settings - Fork 0
/
predicate.go
281 lines (252 loc) · 6.77 KB
/
predicate.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
/*
* 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 worker
import (
"bytes"
"context"
"io"
"math"
"sync"
"sync/atomic"
"time"
"github.com/dgraph-io/badger"
"golang.org/x/net/trace"
"github.com/dgraph-io/dgraph/conn"
"github.com/dgraph-io/dgraph/posting"
"github.com/dgraph-io/dgraph/protos/intern"
"github.com/dgraph-io/dgraph/x"
humanize "github.com/dustin/go-humanize"
)
const (
// MB represents a megabyte.
MB = 1 << 20
)
// writeBatch performs a batch write of key value pairs to BadgerDB.
func writeBatch(ctx context.Context, pstore *badger.ManagedDB, kv chan *intern.KV, che chan error) {
var bytesWritten uint64
t := time.NewTicker(5 * time.Second)
go func() {
now := time.Now()
for range t.C {
x.Printf("Getting SNAPSHOT: Time elapsed: %v, bytes written: %s\n",
x.FixedDuration(time.Since(now)), humanize.Bytes(bytesWritten))
}
}()
var hasError int32
var wg sync.WaitGroup // to wait for all callbacks to return
for i := range kv {
txn := pstore.NewTransactionAt(math.MaxUint64, true)
bytesWritten += uint64(len(i.Key) + len(i.Val))
txn.SetWithMeta(i.Key, i.Val, i.UserMeta[0])
wg.Add(1)
txn.CommitAt(i.Version, func(err error) {
// We don't care about exact error
wg.Done()
if err != nil {
x.Printf("Error while committing kv to badger %v\n", err)
atomic.StoreInt32(&hasError, 1)
}
})
defer txn.Discard()
}
wg.Wait()
t.Stop()
if hasError == 0 {
che <- nil
} else {
che <- x.Errorf("Error while writing to badger")
}
}
// populateShard gets data for a shard from the leader and writes it to BadgerDB on the follower.
func (n *node) populateShard(ps *badger.ManagedDB, pl *conn.Pool) (int, error) {
conn := pl.Get()
c := intern.NewWorkerClient(conn)
n.RLock()
ctx := n.ctx
group := n.gid
stream, err := c.PredicateAndSchemaData(ctx,
&intern.SnapshotMeta{
ClientTs: n.RaftContext.SnapshotTs,
GroupId: group,
})
n.RUnlock()
if err != nil {
if tr, ok := trace.FromContext(ctx); ok {
tr.LazyPrintf(err.Error())
}
return 0, err
}
if tr, ok := trace.FromContext(ctx); ok {
tr.LazyPrintf("Streaming data for group: %v", group)
}
kvs := make(chan *intern.KV, 1000)
che := make(chan error)
go writeBatch(ctx, ps, kvs, che)
ikv, err := stream.Recv()
if err != nil {
return 0, err
}
// First key has the snapshot ts from the leader.
x.AssertTrue(bytes.Equal(ikv.Key, []byte("min_ts")))
n.Lock()
n.RaftContext.SnapshotTs = ikv.Version
n.Unlock()
// We can use count to check the number of posting lists returned in tests.
count := 0
for {
kv, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
if tr, ok := trace.FromContext(ctx); ok {
tr.LazyPrintf(err.Error())
}
close(kvs)
return count, err
}
count++
// We check for errors, if there are no errors we send value to channel.
select {
case kvs <- kv:
// OK
case <-ctx.Done():
if tr, ok := trace.FromContext(ctx); ok {
tr.LazyPrintf("Context timed out while streaming group: %v", group)
}
close(kvs)
return 0, ctx.Err()
case err := <-che:
if tr, ok := trace.FromContext(ctx); ok {
tr.LazyPrintf("Error while doing a batch write for group: %v", group)
}
close(kvs)
// Important: Don't put return count, err
return 0, err
}
}
close(kvs)
if err := <-che; err != nil {
if tr, ok := trace.FromContext(ctx); ok {
tr.LazyPrintf("Error while doing a batch write for group: %v", group)
}
return count, err
}
if tr, ok := trace.FromContext(ctx); ok {
tr.LazyPrintf("Streaming complete for group: %v", group)
}
return count, nil
}
func sendKV(stream intern.Worker_PredicateAndSchemaDataServer, it *badger.Iterator,
pk *x.ParsedKey) error {
item := it.Item()
var kv *intern.KV
if pk.IsSchema() {
val, err := item.Value()
if err != nil {
return err
}
kv = &intern.KV{
Key: item.Key(),
Val: val,
UserMeta: []byte{item.UserMeta()},
Version: item.Version(),
}
if err := stream.Send(kv); err != nil {
return err
}
it.Next()
return nil
}
key := make([]byte, len(item.Key()))
// Key would be modified by ReadPostingList as it advances the iterator and changes the item.
copy(key, item.Key())
l, err := posting.ReadPostingList(key, it)
if err != nil {
return nil
}
kv, err = l.MarshalToKv()
if err != nil {
return err
}
if err := stream.Send(kv); err != nil {
return err
}
return nil
}
func (w *grpcWorker) PredicateAndSchemaData(m *intern.SnapshotMeta, stream intern.Worker_PredicateAndSchemaDataServer) error {
clientTs := m.ClientTs
if !x.IsTestRun() {
if !groups().ServesGroup(m.GroupId) {
return x.Errorf("Group %d not served.", m.GroupId)
}
n := groups().Node
if !n.AmLeader() {
return x.Errorf("Not leader of group: %d", m.GroupId)
}
}
// Any commit which happens in the future will have commitTs greater than
// this.
// TODO: Ensure all deltas have made to disk and read in memory before checking disk.
min_ts := posting.Txns().MinTs()
// Send ts as first KV.
if err := stream.Send(&intern.KV{
Key: []byte("min_ts"),
Version: min_ts,
}); err != nil {
return err
}
txn := pstore.NewTransactionAt(min_ts, false)
defer txn.Discard()
iterOpts := badger.DefaultIteratorOptions
iterOpts.AllVersions = true
iterOpts.PrefetchValues = false
it := txn.NewIterator(iterOpts)
defer it.Close()
var count int
var prevKey []byte
// Do NOT it.Next() by default. Be careful when you "continue" in loop!
for it.Rewind(); it.Valid(); {
iterItem := it.Item()
k := iterItem.Key()
if bytes.Equal(k, prevKey) {
it.Next()
continue
}
if cap(prevKey) < len(k) {
prevKey = make([]byte, len(k))
} else {
prevKey = prevKey[:len(k)]
}
copy(prevKey, k)
pk := x.Parse(prevKey)
// Schema keys always have version 1. So we send it irrespective of the timestamp.
if iterItem.Version() <= clientTs && !pk.IsSchema() {
it.Next()
continue
}
// This key is not present in follower.
if err := sendKV(stream, it, pk); err != nil {
return err
}
count++
} // end of iterator
if tr, ok := trace.FromContext(stream.Context()); ok {
tr.LazyPrintf("Sent %d keys to client. Done.\n", count)
}
return nil
}