forked from dgraph-io/dgraph
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.go
330 lines (289 loc) · 7.43 KB
/
loader.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
/*
* Copyright 2015 DGraph Labs, 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,
* 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 loader
import (
"bufio"
"io"
"math/rand"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"context"
"github.com/Sirupsen/logrus"
"github.com/dgryski/go-farm"
"github.com/dgraph-io/dgraph/posting"
"github.com/dgraph-io/dgraph/rdf"
"github.com/dgraph-io/dgraph/store"
"github.com/dgraph-io/dgraph/uid"
"github.com/dgraph-io/dgraph/x"
)
var glog = x.Log("loader")
var uidStore, dataStore *store.Store
type counters struct {
read uint64
parsed uint64
processed uint64
ignored uint64
}
type state struct {
sync.RWMutex
input chan string
cnq chan rdf.NQuad
ctr *counters
instanceIdx uint64
numInstances uint64
err error
}
func Init(uidstore, datastore *store.Store) {
uidStore = uidstore
dataStore = datastore
}
func (s *state) Error() error {
s.RLock()
defer s.RUnlock()
return s.err
}
func (s *state) SetError(err error) {
s.Lock()
defer s.Unlock()
if s.err == nil {
s.err = err
}
}
func (s *state) printCounters(ticker *time.Ticker) {
var prev uint64
for _ = range ticker.C {
processed := atomic.LoadUint64(&s.ctr.processed)
if prev == processed {
continue
}
prev = processed
parsed := atomic.LoadUint64(&s.ctr.parsed)
ignored := atomic.LoadUint64(&s.ctr.ignored)
pending := parsed - ignored - processed
glog.WithFields(logrus.Fields{
"read": atomic.LoadUint64(&s.ctr.read),
"processed": processed,
"parsed": parsed,
"ignored": ignored,
"pending": pending,
"len_cnq": len(s.cnq),
}).Info("Counters")
}
}
// Only run this in a single goroutine. This function closes s.input channel.
func (s *state) readLines(r io.Reader) {
var buf []string
scanner := bufio.NewScanner(r)
// Randomize lines to avoid contention on same subject.
for i := 0; i < 1000; i++ {
if scanner.Scan() {
buf = append(buf, scanner.Text())
} else {
break
}
}
ln := len(buf)
for scanner.Scan() {
k := rand.Intn(ln)
s.input <- buf[k]
buf[k] = scanner.Text()
atomic.AddUint64(&s.ctr.read, 1)
}
if err := scanner.Err(); err != nil {
glog.WithError(err).Fatal("While reading file.")
}
for i := 0; i < len(buf); i++ {
s.input <- buf[i]
}
close(s.input)
}
func (s *state) parseStream(wg *sync.WaitGroup) {
defer wg.Done()
for line := range s.input {
if s.Error() != nil {
return
}
line = strings.Trim(line, " \t")
if len(line) == 0 {
glog.Info("Empty line.")
continue
}
glog.Debugf("Got line: %q", line)
nq, err := rdf.Parse(line)
if err != nil {
s.SetError(err)
return
}
s.cnq <- nq
atomic.AddUint64(&s.ctr.parsed, 1)
}
}
func (s *state) handleNQuads(wg *sync.WaitGroup) {
defer wg.Done()
ctx := context.Background()
for nq := range s.cnq {
if s.Error() != nil {
return
}
// Only handle this edge if the attribute satisfies the modulo rule
if farm.Fingerprint64([]byte(nq.Predicate))%s.numInstances != s.instanceIdx {
atomic.AddUint64(&s.ctr.ignored, 1)
continue
}
edge, err := nq.ToEdge()
for err != nil {
// Just put in a retry loop to tackle temporary errors.
if err == posting.E_TMP_ERROR {
time.Sleep(time.Microsecond)
} else {
s.SetError(err)
glog.WithError(err).WithField("nq", nq).
Error("While converting to edge")
return
}
edge, err = nq.ToEdge()
}
key := posting.Key(edge.Entity, edge.Attribute)
plist := posting.GetOrCreate(key, dataStore)
plist.AddMutation(ctx, edge, posting.Set)
atomic.AddUint64(&s.ctr.processed, 1)
}
}
func (s *state) assignUid(xid string) error {
if strings.HasPrefix(xid, "_uid_:") {
_, err := strconv.ParseUint(xid[6:], 0, 64)
return err
}
_, err := uid.GetOrAssign(xid, s.instanceIdx, s.numInstances)
for err != nil {
// Just put in a retry loop to tackle temporary errors.
if err == posting.E_TMP_ERROR {
time.Sleep(time.Microsecond)
glog.WithError(err).WithField("xid", xid).
Debug("Temporary error")
} else {
glog.WithError(err).WithField("xid", xid).
Error("While getting UID")
return err
}
_, err = uid.GetOrAssign(xid, s.instanceIdx, s.numInstances)
}
return nil
}
func (s *state) assignUidsOnly(wg *sync.WaitGroup) {
defer wg.Done()
for nq := range s.cnq {
if s.Error() != nil {
return
}
ignored := true
if farm.Fingerprint64([]byte(nq.Subject))%s.numInstances == s.instanceIdx {
if err := s.assignUid(nq.Subject); err != nil {
s.SetError(err)
glog.WithError(err).Error("While assigning Uid to subject.")
return
}
ignored = false
}
if len(nq.ObjectId) > 0 &&
farm.Fingerprint64([]byte(nq.ObjectId))%s.numInstances == s.instanceIdx {
if err := s.assignUid(nq.ObjectId); err != nil {
s.SetError(err)
glog.WithError(err).Error("While assigning Uid to object.")
return
}
ignored = false
}
if ignored {
atomic.AddUint64(&s.ctr.ignored, 1)
} else {
atomic.AddUint64(&s.ctr.processed, 1)
}
}
}
// Blocking function.
func LoadEdges(reader io.Reader, instanceIdx uint64,
numInstances uint64) (uint64, error) {
s := new(state)
s.ctr = new(counters)
ticker := time.NewTicker(time.Second)
go s.printCounters(ticker)
// Producer: Start buffering input to channel.
s.instanceIdx = instanceIdx
s.numInstances = numInstances
s.input = make(chan string, 10000)
go s.readLines(reader)
s.cnq = make(chan rdf.NQuad, 10000)
numr := runtime.GOMAXPROCS(-1)
var pwg sync.WaitGroup
pwg.Add(numr)
for i := 0; i < numr; i++ {
go s.parseStream(&pwg) // Input --> NQuads
}
nrt := 3000
var wg sync.WaitGroup
wg.Add(nrt)
for i := 0; i < nrt; i++ {
go s.handleNQuads(&wg) // NQuads --> Posting list [slow].
}
// Block until all parseStream goroutines are finished.
pwg.Wait()
close(s.cnq)
// Okay, we've stopped input to cnq, and closed it.
// Now wait for handleNQuads to finish.
wg.Wait()
ticker.Stop()
return atomic.LoadUint64(&s.ctr.processed), s.Error()
}
// AssignUids would pick up all the external ids in RDFs read,
// and assign unique integer ids for them. This function would
// not load the edges, only assign UIDs.
func AssignUids(reader io.Reader, instanceIdx uint64,
numInstances uint64) (uint64, error) {
s := new(state)
s.ctr = new(counters)
ticker := time.NewTicker(time.Second)
go s.printCounters(ticker)
// Producer: Start buffering input to channel.
s.instanceIdx = instanceIdx
s.numInstances = numInstances
s.input = make(chan string, 10000)
go s.readLines(reader)
s.cnq = make(chan rdf.NQuad, 10000)
numr := runtime.GOMAXPROCS(-1)
var pwg sync.WaitGroup
pwg.Add(numr)
for i := 0; i < numr; i++ {
go s.parseStream(&pwg) // Input --> NQuads
}
wg := new(sync.WaitGroup)
for i := 0; i < 3000; i++ {
wg.Add(1)
go s.assignUidsOnly(wg)
}
// Block until all parseStream goroutines are finished.
pwg.Wait()
close(s.cnq)
// Okay, we've stopped input to cnq, and closed it.
// Now wait for handleNQuads to finish.
wg.Wait()
ticker.Stop()
return atomic.LoadUint64(&s.ctr.processed), s.Error()
}