forked from dgraph-io/dgraph
/
main.go
394 lines (359 loc) · 10.4 KB
/
main.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
/*
* 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 main
import (
"bufio"
"bytes"
"compress/gzip"
"context"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"gopkg.in/adibiarsotp/dgraph.v83/client"
"gopkg.in/adibiarsotp/dgraph.v83/protos"
"gopkg.in/adibiarsotp/dgraph.v83/rdf"
"gopkg.in/adibiarsotp/dgraph.v83/types"
"gopkg.in/adibiarsotp/dgraph.v83/x"
"github.com/pkg/profile"
)
var (
files = flag.String("r", "", "Location of rdf files to load")
schemaFile = flag.String("s", "", "Location of schema file")
dgraph = flag.String("d", "127.0.0.1:9080", "Dgraph gRPC server address")
concurrent = flag.Int("c", 100, "Number of concurrent requests to make to Dgraph")
numRdf = flag.Int("m", 1000, "Number of RDF N-Quads to send as part of a mutation.")
storeXid = flag.Bool("x", false, "Store xids by adding corresponding xid edges")
mode = flag.String("profile.mode", "", "enable profiling mode, one of [cpu, mem, mutex, block]")
clientDir = flag.String("cd", "c", "Directory to store xid to uid mapping")
blockRate = flag.Int("block", 0, "Block profiling rate")
// TLS configuration
tlsEnabled = flag.Bool("tls.on", false, "Use TLS connections.")
tlsInsecure = flag.Bool("tls.insecure", false, "Skip certificate validation (insecure)")
tlsServerName = flag.String("tls.server_name", "", "Server name.")
tlsCert = flag.String("tls.cert", "", "Certificate file path.")
tlsKey = flag.String("tls.cert_key", "", "Certificate key file path.")
tlsKeyPass = flag.String("tls.cert_key_passphrase", "", "Certificate key passphrase.")
tlsRootCACerts = flag.String("tls.ca_certs", "", "CA Certs file path.")
tlsSystemCACerts = flag.Bool("tls.use_system_ca", false, "Include System CA into CA Certs.")
tlsMinVersion = flag.String("tls.min_version", "TLS11", "TLS min version.")
tlsMaxVersion = flag.String("tls.max_version", "TLS12", "TLS max version.")
version = flag.Bool("version", false, "Prints the version of Dgraphloader")
)
// Reads a single line from a buffered reader. The line is read into the
// passed in buffer to minimize allocations. This is the preferred
// method for loading long lines which could be longer than the buffer
// size of bufio.Scanner.
func readLine(r *bufio.Reader, buf *bytes.Buffer) error {
isPrefix := true
var err error
for isPrefix && err == nil {
var line []byte
// The returned line is an internal buffer in bufio and is only
// valid until the next call to ReadLine. It needs to be copied
// over to our own buffer.
line, isPrefix, err = r.ReadLine()
if err == nil {
buf.Write(line)
}
}
return err
}
// processSchemaFile process schema for a given gz file.
func processSchemaFile(ctx context.Context, file string, dgraphClient *client.Dgraph) error {
fmt.Printf("\nProcessing %s\n", file)
f, err := os.Open(file)
x.Check(err)
defer f.Close()
var reader io.Reader
if strings.HasSuffix(strings.ToLower(file), ".gz") {
reader, err = gzip.NewReader(f)
x.Check(err)
} else {
reader = f
}
b, err := ioutil.ReadAll(reader)
if err != nil {
x.Checkf(err, "Error while reading file")
}
return dgraphClient.SetSchemaBlocking(ctx, string(b))
}
func Node(val string, c *client.Dgraph) (string, error) {
if uid, err := strconv.ParseUint(val, 0, 64); err == nil {
return c.NodeUid(uid).String(), nil
}
if strings.HasPrefix(val, "_:") {
n, err := c.NodeBlank(val[2:])
if err != nil {
return "", err
}
return n.String(), nil
}
n, err := c.NodeXid(val, *storeXid)
if err != nil {
return "", err
}
return n.String(), nil
}
func fileReader(file string) (io.Reader, *os.File) {
f, err := os.Open(file)
x.Check(err)
var r io.Reader
if filepath.Ext(file) == ".gz" {
r, err = gzip.NewReader(f)
x.Check(err)
} else {
r = bufio.NewReader(f)
}
return r, f
}
// processFile sends mutations for a given gz file.
func processFile(ctx context.Context, file string, dgraphClient *client.Dgraph) error {
fmt.Printf("\nProcessing %s\n", file)
gr, f := fileReader(file)
var buf bytes.Buffer
bufReader := bufio.NewReader(gr)
defer f.Close()
absPath, err := filepath.Abs(file)
x.Check(err)
checkpoint, err := dgraphClient.Checkpoint(absPath)
x.Check(err)
if checkpoint != 0 {
fmt.Printf("\nFound checkpoint for: %s. Skipping: %v lines.\n", file, checkpoint)
}
var line uint64
r := new(client.Req)
var batchSize int
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
err = readLine(bufReader, &buf)
if err != nil {
if err != io.EOF {
return err
}
break
}
line++
if line <= checkpoint {
buf.Reset()
// No need to parse. We have already sent it to server.
continue
}
nq, err := rdf.Parse(buf.String())
if err == rdf.ErrEmpty { // special case: comment/empty line
buf.Reset()
continue
} else if err != nil {
return fmt.Errorf("Error while parsing RDF: %v, on line:%v %v", err, line, buf.String())
}
batchSize++
buf.Reset()
if nq.Subject, err = Node(nq.Subject, dgraphClient); err != nil {
return err
}
if len(nq.ObjectId) > 0 {
if nq.ObjectId, err = Node(nq.ObjectId, dgraphClient); err != nil {
return err
}
}
r.Set(client.NewEdge(nq))
if batchSize >= *numRdf {
if err = dgraphClient.BatchSetWithMark(r, absPath, line); err != nil {
return err
}
batchSize = 0
r = new(client.Req)
}
}
if batchSize > 0 {
if err = dgraphClient.BatchSetWithMark(r, absPath, line); err != nil {
return err
}
}
return nil
}
func setupConnection(host string) (*grpc.ClientConn, error) {
if !*tlsEnabled {
return grpc.Dial(host,
grpc.WithDefaultCallOptions(
grpc.MaxCallRecvMsgSize(x.GrpcMaxSize),
grpc.MaxCallSendMsgSize(x.GrpcMaxSize)),
grpc.WithInsecure())
}
tlsCfg, _, err := x.GenerateTLSConfig(x.TLSHelperConfig{
ConfigType: x.TLSClientConfig,
Insecure: *tlsInsecure,
ServerName: *tlsServerName,
Cert: *tlsCert,
Key: *tlsKey,
KeyPassphrase: *tlsKeyPass,
RootCACerts: *tlsRootCACerts,
UseSystemRootCACerts: *tlsSystemCACerts,
MinVersion: *tlsMinVersion,
MaxVersion: *tlsMaxVersion,
})
if err != nil {
return nil, err
}
return grpc.Dial(host,
grpc.WithDefaultCallOptions(
grpc.MaxCallRecvMsgSize(x.GrpcMaxSize),
grpc.MaxCallSendMsgSize(x.GrpcMaxSize)),
grpc.WithTransportCredentials(credentials.NewTLS(tlsCfg)))
}
func fileList(files string) []string {
if len(files) == 0 {
return []string{}
}
return strings.Split(files, ",")
}
func main() {
flag.Parse()
if *version {
x.PrintVersionOnly()
}
runtime.SetBlockProfileRate(*blockRate)
interruptChan := make(chan os.Signal)
signal.Notify(interruptChan, syscall.SIGINT, syscall.SIGTERM)
ctx, cancel := context.WithCancel(context.Background())
go func() {
<-interruptChan
cancel()
}()
go http.ListenAndServe("localhost:6060", nil)
switch *mode {
case "cpu":
defer profile.Start(profile.CPUProfile).Stop()
case "mem":
defer profile.Start(profile.MemProfile).Stop()
case "mutex":
defer profile.Start(profile.MutexProfile).Stop()
case "block":
defer profile.Start(profile.BlockProfile).Stop()
default:
// do nothing
}
var conns []*grpc.ClientConn
hostList := strings.Split(*dgraph, ",")
x.AssertTrue(len(hostList) > 0)
for _, host := range hostList {
host = strings.Trim(host, " \t")
conn, err := setupConnection(host)
x.Checkf(err, "While trying to dial gRPC")
conns = append(conns, conn)
defer conn.Close()
}
bmOpts := client.BatchMutationOptions{
Size: *numRdf,
Pending: *concurrent,
PrintCounters: true,
Ctx: ctx,
}
dgraphClient := client.NewDgraphClient(conns, bmOpts, *clientDir)
defer dgraphClient.Close()
{
ctxTimeout, cancelTimeout := context.WithTimeout(ctx, 1*time.Minute)
dgraphClient.CheckVersion(ctxTimeout)
cancelTimeout()
}
if *storeXid {
if err := dgraphClient.AddSchema(protos.SchemaUpdate{
Predicate: "xid",
ValueType: uint32(types.StringID),
Tokenizer: []string{"hash"},
Directive: protos.SchemaUpdate_INDEX,
}); err != nil {
log.Fatal("While adding schema to batch ", err)
}
}
if len(*schemaFile) > 0 {
if err := processSchemaFile(ctx, *schemaFile, dgraphClient); err != nil {
if err == context.Canceled {
log.Println("Interrupted while processing schema file")
} else {
log.Println(err)
}
return
}
}
filesList := fileList(*files)
totalFiles := len(filesList)
if totalFiles == 0 {
os.Exit(0)
}
x.Check(dgraphClient.NewSyncMarks(filesList))
errCh := make(chan error, totalFiles)
for _, file := range filesList {
file = strings.Trim(file, " \t")
go func(file string) {
errCh <- processFile(ctx, file, dgraphClient)
}(file)
}
interrupted := false
for i := 0; i < totalFiles; i++ {
if err := <-errCh; err != nil {
if err == context.Canceled {
interrupted = true
} else {
log.Fatal("While processing file ", err)
}
}
}
{
if err := dgraphClient.BatchFlush(); err != nil {
if err == context.Canceled {
interrupted = true
} else {
log.Fatalf("While doing BatchFlush: %+v\n", err)
}
}
}
c := dgraphClient.Counter()
var rate uint64
if c.Elapsed.Seconds() < 1 {
rate = c.Rdfs
} else {
rate = c.Rdfs / uint64(c.Elapsed.Seconds())
}
// Lets print an empty line, otherwise Interrupted or Number of Mutations overwrites the
// previous printed line.
fmt.Printf("%100s\r", "")
if interrupted {
fmt.Println("Interrupted.")
}
fmt.Printf("Number of mutations run : %d\n", c.Mutations)
fmt.Printf("Number of RDFs processed : %d\n", c.Rdfs)
fmt.Printf("Time spent : %v\n", c.Elapsed)
fmt.Printf("RDFs processed per second : %d\n", rate)
}