forked from dgraph-io/dgraph
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mapper.go
333 lines (293 loc) · 7.96 KB
/
mapper.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
/*
* 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 bulk
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"log"
"math"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"sync/atomic"
"github.com/dgraph-io/dgraph/gql"
"github.com/dgraph-io/dgraph/posting"
"github.com/dgraph-io/dgraph/protos/api"
"github.com/dgraph-io/dgraph/protos/intern"
"github.com/dgraph-io/dgraph/rdf"
"github.com/dgraph-io/dgraph/tok"
"github.com/dgraph-io/dgraph/types"
"github.com/dgraph-io/dgraph/x"
farm "github.com/dgryski/go-farm"
"github.com/gogo/protobuf/proto"
"github.com/pkg/errors"
)
type mapper struct {
*state
shards []shardState // shard is based on predicate
}
type shardState struct {
// Buffer up map entries until we have a sufficient amount, then sort and
// write them to file.
entriesBuf []byte
mu sync.Mutex // Allow only 1 write per shard at a time.
}
func newMapper(st *state) *mapper {
return &mapper{
state: st,
shards: make([]shardState, st.opt.MapShards),
}
}
func less(lhs, rhs *intern.MapEntry) bool {
if keyCmp := bytes.Compare(lhs.Key, rhs.Key); keyCmp != 0 {
return keyCmp < 0
}
lhsUID := lhs.Uid
rhsUID := rhs.Uid
if lhs.Posting != nil {
lhsUID = lhs.Posting.Uid
}
if rhs.Posting != nil {
rhsUID = rhs.Posting.Uid
}
return lhsUID < rhsUID
}
func (m *mapper) writeMapEntriesToFile(entriesBuf []byte, shardIdx int) {
buf := entriesBuf
var entries []*intern.MapEntry
for len(buf) > 0 {
sz, n := binary.Uvarint(buf)
x.AssertTrue(n > 0)
buf = buf[n:]
me := new(intern.MapEntry)
x.Check(proto.Unmarshal(buf[:sz], me))
buf = buf[sz:]
entries = append(entries, me)
}
sort.Slice(entries, func(i, j int) bool {
return less(entries[i], entries[j])
})
buf = entriesBuf
for _, me := range entries {
n := binary.PutUvarint(buf, uint64(me.Size()))
buf = buf[n:]
n, err := me.MarshalTo(buf)
x.Check(err)
buf = buf[n:]
}
x.AssertTrue(len(buf) == 0)
fileNum := atomic.AddUint32(&m.mapFileId, 1)
filename := filepath.Join(
m.opt.TmpDir,
"shards",
fmt.Sprintf("%03d", shardIdx),
fmt.Sprintf("%06d.map", fileNum),
)
x.Check(os.MkdirAll(filepath.Dir(filename), 0755))
x.Check(x.WriteFileSync(filename, entriesBuf, 0644))
m.shards[shardIdx].mu.Unlock() // Locked by caller.
}
func (m *mapper) run() {
for chunkBuf := range m.rdfChunkCh {
done := false
for !done {
rdf, err := chunkBuf.ReadString('\n')
if err == io.EOF {
// Process the last RDF rather than breaking immediately.
done = true
} else {
x.Check(err)
}
rdf = strings.TrimSpace(rdf)
x.Check(m.parseRDF(rdf))
atomic.AddInt64(&m.prog.rdfCount, 1)
for i := range m.shards {
sh := &m.shards[i]
if len(sh.entriesBuf) >= int(m.opt.MapBufSize) {
sh.mu.Lock() // One write at a time.
go m.writeMapEntriesToFile(sh.entriesBuf, i)
sh.entriesBuf = make([]byte, 0, m.opt.MapBufSize*11/10)
}
}
}
}
for i := range m.shards {
sh := &m.shards[i]
if len(sh.entriesBuf) > 0 {
sh.mu.Lock() // One write at a time.
m.writeMapEntriesToFile(sh.entriesBuf, i)
}
m.shards[i].mu.Lock() // Ensure that the last file write finishes.
}
}
func (m *mapper) addMapEntry(key []byte, p *intern.Posting, shard int) {
atomic.AddInt64(&m.prog.mapEdgeCount, 1)
me := &intern.MapEntry{
Key: key,
}
if p.PostingType != intern.Posting_REF || len(p.Facets) > 0 {
me.Posting = p
} else {
me.Uid = p.Uid
}
sh := &m.shards[shard]
var err error
sh.entriesBuf = x.AppendUvarint(sh.entriesBuf, uint64(me.Size()))
sh.entriesBuf, err = x.AppendProtoMsg(sh.entriesBuf, me)
x.Check(err)
}
func (m *mapper) parseRDF(rdfLine string) error {
nq, err := parseNQuad(rdfLine)
if err != nil {
if err == rdf.ErrEmpty {
return nil
}
return errors.Wrapf(err, "while parsing line %q", rdfLine)
}
m.processNQuad(nq)
return nil
}
func (m *mapper) processNQuad(nq gql.NQuad) {
sid := m.lookupUid(nq.GetSubject())
var oid uint64
var de *intern.DirectedEdge
if nq.GetObjectValue() == nil {
oid = m.lookupUid(nq.GetObjectId())
de = nq.CreateUidEdge(sid, oid)
} else {
var err error
de, err = nq.CreateValueEdge(sid)
x.Check(err)
}
fwd, rev := m.createPostings(nq, de)
shard := m.state.shards.shardFor(nq.Predicate)
key := x.DataKey(nq.Predicate, sid)
m.addMapEntry(key, fwd, shard)
if rev != nil {
key = x.ReverseKey(nq.Predicate, oid)
m.addMapEntry(key, rev, shard)
}
if m.opt.ExpandEdges {
key = x.DataKey("_predicate_", sid)
pp := m.createPredicatePosting(nq.Predicate)
m.addMapEntry(key, pp, shard)
}
m.addIndexMapEntries(nq, de)
}
func (m *mapper) lookupUid(xid string) uint64 {
uid, isNew := m.xids.AssignUid(xid)
if !isNew || !m.opt.StoreXids {
return uid
}
if strings.HasPrefix(xid, "_:") {
// Don't store xids for blank nodes.
return uid
}
nq := gql.NQuad{&api.NQuad{
Subject: xid,
Predicate: "xid",
ObjectValue: &api.Value{
Val: &api.Value_StrVal{StrVal: xid},
},
}}
m.processNQuad(nq)
return uid
}
func parseNQuad(line string) (gql.NQuad, error) {
nq, err := rdf.Parse(line)
if err != nil {
return gql.NQuad{}, err
}
return gql.NQuad{NQuad: &nq}, nil
}
func (m *mapper) createPredicatePosting(predicate string) *intern.Posting {
fp := farm.Fingerprint64([]byte(predicate))
return &intern.Posting{
Uid: fp,
Value: []byte(predicate),
ValType: intern.Posting_DEFAULT,
PostingType: intern.Posting_VALUE,
}
}
func (m *mapper) createPostings(nq gql.NQuad,
de *intern.DirectedEdge) (*intern.Posting, *intern.Posting) {
m.schema.validateType(de, nq.ObjectValue == nil)
p := posting.NewPosting(de)
sch := m.schema.getSchema(nq.GetPredicate())
if nq.GetObjectValue() != nil {
if lang := de.GetLang(); len(lang) > 0 {
p.Uid = farm.Fingerprint64([]byte(lang))
} else if sch.List {
p.Uid = farm.Fingerprint64(de.Value)
} else {
p.Uid = math.MaxUint64
}
}
p.Facets = nq.Facets
// Early exit for no reverse edge.
if sch.GetDirective() != intern.SchemaUpdate_REVERSE {
return p, nil
}
// Reverse predicate
x.AssertTruef(nq.GetObjectValue() == nil, "only has reverse schema if object is UID")
de.Entity, de.ValueId = de.ValueId, de.Entity
m.schema.validateType(de, true)
rp := posting.NewPosting(de)
de.Entity, de.ValueId = de.ValueId, de.Entity // de reused so swap back.
return p, rp
}
func (m *mapper) addIndexMapEntries(nq gql.NQuad, de *intern.DirectedEdge) {
if nq.GetObjectValue() == nil {
return // Cannot index UIDs
}
sch := m.schema.getSchema(nq.GetPredicate())
for _, tokerName := range sch.GetTokenizer() {
// Find tokeniser.
toker, ok := tok.GetTokenizer(tokerName)
if !ok {
log.Fatalf("unknown tokenizer %q", tokerName)
}
// Create storage value.
storageVal := types.Val{
Tid: types.TypeID(de.GetValueType()),
Value: de.GetValue(),
}
// Convert from storage type to schema type.
schemaVal, err := types.Convert(storageVal, types.TypeID(sch.GetValueType()))
// Shouldn't error, since we've already checked for convertibility when
// doing edge postings. So okay to be fatal.
x.Check(err)
// Extract tokens.
toks, err := tok.BuildTokens(schemaVal.Value, toker)
x.Check(err)
// Store index posting.
for _, t := range toks {
m.addMapEntry(
x.IndexKey(nq.Predicate, t),
&intern.Posting{
Uid: de.GetEntity(),
PostingType: intern.Posting_REF,
},
m.state.shards.shardFor(nq.Predicate),
)
}
}
}