-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
server.go
1327 lines (1158 loc) · 36.9 KB
/
server.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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2017-2018 Dgraph Labs, 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 edgraph
import (
"encoding/json"
"fmt"
"io/ioutil"
"math"
"math/rand"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"unicode"
"github.com/dgraph-io/badger"
"github.com/dgraph-io/badger/options"
"github.com/dgraph-io/dgo/v2"
"github.com/dgraph-io/dgo/v2/protos/api"
"github.com/dgraph-io/dgraph/chunker"
"github.com/dgraph-io/dgraph/dgraph/cmd/zero"
"github.com/dgraph-io/dgraph/gql"
"github.com/dgraph-io/dgraph/posting"
"github.com/dgraph-io/dgraph/protos/pb"
"github.com/dgraph-io/dgraph/query"
"github.com/dgraph-io/dgraph/schema"
"github.com/dgraph-io/dgraph/types"
"github.com/dgraph-io/dgraph/types/facets"
"github.com/dgraph-io/dgraph/worker"
"github.com/dgraph-io/dgraph/x"
"github.com/golang/glog"
"github.com/pkg/errors"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
ostats "go.opencensus.io/stats"
"go.opencensus.io/tag"
otrace "go.opencensus.io/trace"
)
const (
methodMutate = "Server.Mutate"
methodQuery = "Server.Query"
groupFile = "group_id"
)
// ServerState holds the state of the Dgraph server.
type ServerState struct {
FinishCh chan struct{} // channel to wait for all pending reqs to finish.
ShutdownCh chan struct{} // channel to signal shutdown.
Pstore *badger.DB
WALstore *badger.DB
vlogTicker *time.Ticker // runs every 1m, check size of vlog and run GC conditionally.
mandatoryVlogTicker *time.Ticker // runs every 10m, we always run vlog GC.
needTs chan tsReq
}
const (
// NeedAuthorize is used to indicate that the request needs to be authorized.
NeedAuthorize = iota
// NoAuthorize is used to indicate that authorization needs to be skipped.
// Used when ACL needs to query information for performing the authorization check.
NoAuthorize
)
// State is the instance of ServerState used by the current server.
var State ServerState
// InitServerState initializes this server's state.
func InitServerState() {
Config.validate()
State.FinishCh = make(chan struct{})
State.ShutdownCh = make(chan struct{})
State.needTs = make(chan tsReq, 100)
State.initStorage()
go State.fillTimestampRequests()
contents, err := ioutil.ReadFile(filepath.Join(Config.PostingDir, groupFile))
if err != nil {
glog.Warningf("%s file not found or could not be opened", groupFile)
return
}
groupId, err := strconv.ParseUint(strings.TrimSpace(string(contents)), 10, 32)
x.Checkf(err, "Error reading %s file inside posting directory %s",
groupFile, Config.PostingDir)
x.WorkerConfig.ProposedGroupId = uint32(groupId)
}
func (s *ServerState) runVlogGC(store *badger.DB) {
// Get initial size on start.
_, lastVlogSize := store.Size()
const GB = int64(1 << 30)
runGC := func() {
var err error
for err == nil {
// If a GC is successful, immediately run it again.
err = store.RunValueLogGC(0.7)
}
_, lastVlogSize = store.Size()
}
for {
select {
case <-s.vlogTicker.C:
_, currentVlogSize := store.Size()
if currentVlogSize < lastVlogSize+GB {
continue
}
runGC()
case <-s.mandatoryVlogTicker.C:
runGC()
}
}
}
func setBadgerOptions(opt badger.Options) badger.Options {
opt = opt.WithSyncWrites(false).WithTruncate(true).WithLogger(&x.ToGlog{})
glog.Infof("Setting Badger table load option: %s", Config.BadgerTables)
switch Config.BadgerTables {
case "mmap":
opt.TableLoadingMode = options.MemoryMap
case "ram":
opt.TableLoadingMode = options.LoadToRAM
case "disk":
opt.TableLoadingMode = options.FileIO
default:
x.Fatalf("Invalid Badger Tables options")
}
glog.Infof("Setting Badger value log load option: %s", Config.BadgerVlog)
switch Config.BadgerVlog {
case "mmap":
opt.ValueLogLoadingMode = options.MemoryMap
case "disk":
opt.ValueLogLoadingMode = options.FileIO
default:
x.Fatalf("Invalid Badger Value log options")
}
return opt
}
func (s *ServerState) initStorage() {
var err error
{
// Write Ahead Log directory
x.Checkf(os.MkdirAll(Config.WALDir, 0700), "Error while creating WAL dir.")
opt := badger.LSMOnlyOptions(Config.WALDir)
opt = setBadgerOptions(opt)
opt.ValueLogMaxEntries = 10000 // Allow for easy space reclamation.
// We should always force load LSM tables to memory, disregarding user settings, because
// Raft.Advance hits the WAL many times. If the tables are not in memory, retrieval slows
// down way too much, causing cluster membership issues. Because of prefix compression and
// value separation provided by Badger, this is still better than using the memory based WAL
// storage provided by the Raft library.
opt.TableLoadingMode = options.LoadToRAM
glog.Infof("Opening write-ahead log BadgerDB with options: %+v\n", opt)
s.WALstore, err = badger.Open(opt)
x.Checkf(err, "Error while creating badger KV WAL store")
}
{
// Postings directory
// All the writes to posting store should be synchronous. We use batched writers
// for posting lists, so the cost of sync writes is amortized.
x.Check(os.MkdirAll(Config.PostingDir, 0700))
opt := badger.DefaultOptions(Config.PostingDir).WithValueThreshold(1 << 10 /* 1KB */).
WithNumVersionsToKeep(math.MaxInt32)
opt = setBadgerOptions(opt)
glog.Infof("Opening postings BadgerDB with options: %+v\n", opt)
s.Pstore, err = badger.OpenManaged(opt)
x.Checkf(err, "Error while creating badger KV posting store")
}
s.vlogTicker = time.NewTicker(1 * time.Minute)
s.mandatoryVlogTicker = time.NewTicker(10 * time.Minute)
go s.runVlogGC(s.Pstore)
go s.runVlogGC(s.WALstore)
}
// Dispose stops and closes all the resources inside the server state.
func (s *ServerState) Dispose() {
if err := s.Pstore.Close(); err != nil {
glog.Errorf("Error while closing postings store: %v", err)
}
if err := s.WALstore.Close(); err != nil {
glog.Errorf("Error while closing WAL store: %v", err)
}
s.vlogTicker.Stop()
s.mandatoryVlogTicker.Stop()
}
// Server implements protos.DgraphServer
type Server struct{}
func (s *ServerState) fillTimestampRequests() {
const (
initDelay = 10 * time.Millisecond
maxDelay = time.Second
)
var reqs []tsReq
for {
// Reset variables.
reqs = reqs[:0]
delay := initDelay
req := <-s.needTs
slurpLoop:
for {
reqs = append(reqs, req)
select {
case req = <-s.needTs:
default:
break slurpLoop
}
}
// Generate the request.
num := &pb.Num{}
for _, r := range reqs {
if r.readOnly {
num.ReadOnly = true
} else {
num.Val++
}
}
// Execute the request with infinite retries.
retry:
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
ts, err := worker.Timestamps(ctx, num)
cancel()
if err != nil {
glog.Warningf("Error while retrieving timestamps: %v with delay: %v."+
" Will retry...\n", err, delay)
time.Sleep(delay)
delay *= 2
if delay > maxDelay {
delay = maxDelay
}
goto retry
}
var offset uint64
for _, req := range reqs {
if req.readOnly {
req.ch <- ts.ReadOnly
} else {
req.ch <- ts.StartId + offset
offset++
}
}
x.AssertTrue(ts.StartId == 0 || ts.StartId+offset-1 == ts.EndId)
}
}
type tsReq struct {
readOnly bool
// A one-shot chan which we can send a txn timestamp upon.
ch chan uint64
}
func (s *ServerState) getTimestamp(readOnly bool) uint64 {
tr := tsReq{readOnly: readOnly, ch: make(chan uint64)}
s.needTs <- tr
return <-tr.ch
}
// Alter handles requests to change the schema or remove parts or all of the data.
func (s *Server) Alter(ctx context.Context, op *api.Operation) (*api.Payload, error) {
ctx, span := otrace.StartSpan(ctx, "Server.Alter")
defer span.End()
span.Annotatef(nil, "Alter operation: %+v", op)
// Always print out Alter operations because they are important and rare.
glog.Infof("Received ALTER op: %+v", op)
// The following code block checks if the operation should run or not.
if op.Schema == "" && op.DropAttr == "" && !op.DropAll && op.DropOp == api.Operation_NONE {
// Must have at least one field set. This helps users if they attempt
// to set a field but use the wrong name (could be decoded from JSON).
return nil, errors.Errorf("Operation must have at least one field set")
}
empty := &api.Payload{}
if err := x.HealthCheck(); err != nil {
return empty, err
}
if isDropAll(op) && op.DropOp == api.Operation_DATA {
return nil, errors.Errorf("Only one of DropAll and DropData can be true")
}
if !isMutationAllowed(ctx) {
return nil, errors.Errorf("No mutations allowed by server.")
}
if err := isAlterAllowed(ctx); err != nil {
glog.Warningf("Alter denied with error: %v\n", err)
return nil, err
}
if err := authorizeAlter(ctx, op); err != nil {
glog.Warningf("Alter denied with error: %v\n", err)
return nil, err
}
defer glog.Infof("ALTER op: %+v done", op)
// StartTs is not needed if the predicate to be dropped lies on this server but is required
// if it lies on some other machine. Let's get it for safety.
m := &pb.Mutations{StartTs: State.getTimestamp(false)}
if isDropAll(op) {
if len(op.DropValue) > 0 {
return empty, errors.Errorf("If DropOp is set to ALL, DropValue must be empty")
}
m.DropOp = pb.Mutations_ALL
_, err := query.ApplyMutations(ctx, m)
// recreate the admin account after a drop all operation
ResetAcl()
return empty, err
}
if op.DropOp == api.Operation_DATA {
if len(op.DropValue) > 0 {
return empty, errors.Errorf("If DropOp is set to DATA, DropValue must be empty")
}
m.DropOp = pb.Mutations_DATA
_, err := query.ApplyMutations(ctx, m)
// recreate the admin account after a drop data operation
ResetAcl()
return empty, err
}
if len(op.DropAttr) > 0 || op.DropOp == api.Operation_ATTR {
if op.DropOp == api.Operation_ATTR && len(op.DropValue) == 0 {
return empty, errors.Errorf("If DropOp is set to ATTR, DropValue must not be empty")
}
var attr string
if len(op.DropAttr) > 0 {
attr = op.DropAttr
} else {
attr = op.DropValue
}
// Reserved predicates cannot be dropped.
if x.IsReservedPredicate(attr) {
err := errors.Errorf("predicate %s is reserved and is not allowed to be dropped",
attr)
return empty, err
}
nq := &api.NQuad{
Subject: x.Star,
Predicate: attr,
ObjectValue: &api.Value{Val: &api.Value_StrVal{StrVal: x.Star}},
}
wnq := &gql.NQuad{NQuad: nq}
edge, err := wnq.ToDeletePredEdge()
if err != nil {
return empty, err
}
edges := []*pb.DirectedEdge{edge}
m.Edges = edges
_, err = query.ApplyMutations(ctx, m)
return empty, err
}
if op.DropOp == api.Operation_TYPE {
if len(op.DropValue) == 0 {
return empty, errors.Errorf("If DropOp is set to TYPE, DropValue must not be empty")
}
m.DropOp = pb.Mutations_TYPE
m.DropValue = op.DropValue
_, err := query.ApplyMutations(ctx, m)
return empty, err
}
result, err := schema.Parse(op.Schema)
if err != nil {
return empty, err
}
for _, update := range result.Preds {
// Reserved predicates cannot be altered but let the update go through
// if the update is equal to the existing one.
if schema.IsReservedPredicateChanged(update.Predicate, update) {
err := errors.Errorf("predicate %s is reserved and is not allowed to be modified",
update.Predicate)
return nil, err
}
if err := validatePredName(update.Predicate); err != nil {
return nil, err
}
}
glog.Infof("Got schema: %+v\n", result)
// TODO: Maybe add some checks about the schema.
m.Schema = result.Preds
m.Types = result.Types
_, err = query.ApplyMutations(ctx, m)
return empty, err
}
func annotateStartTs(span *otrace.Span, ts uint64) {
span.Annotate([]otrace.Attribute{otrace.Int64Attribute("startTs", int64(ts))}, "")
}
func (s *Server) doMutate(ctx context.Context, req *api.Request, authorize int) (
resp *api.Response, rerr error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
if len(req.Mutations) != 1 {
return nil, errors.Errorf("Only 1 mutation per request is supported")
}
mu := req.Mutations[0]
if !isMutationAllowed(ctx) {
return resp, errors.Errorf("No mutations allowed.")
}
var parsingTime time.Duration
resp = &api.Response{}
start := time.Now()
defer func() {
totalTime := time.Since(start)
processingTime := totalTime - parsingTime
resp.Latency = &api.Latency{
ParsingNs: uint64(parsingTime.Nanoseconds()),
ProcessingNs: uint64(processingTime.Nanoseconds()),
}
}()
ctx, span := otrace.StartSpan(ctx, methodMutate)
ctx = x.WithMethod(ctx, methodMutate)
defer func() {
span.End()
v := x.TagValueStatusOK
if rerr != nil {
v = x.TagValueStatusError
}
ctx, _ = tag.New(ctx, tag.Upsert(x.KeyStatus, v))
timeSpentMs := x.SinceMs(start)
ostats.Record(ctx, x.LatencyMs.M(timeSpentMs))
}()
if rerr = x.HealthCheck(); rerr != nil {
return
}
ostats.Record(ctx, x.NumMutations.M(1))
if req.Query != "" {
span.Annotatef(nil, "Got Mutation with Upsert Block: %s", mu)
}
if len(mu.SetJson) > 0 {
span.Annotatef(nil, "Got JSON Mutation: %s", mu.SetJson)
} else if len(mu.SetNquads) > 0 {
span.Annotatef(nil, "Got NQuad Mutation: %s", mu.SetNquads)
}
startParsingTime := time.Now()
gmu, err := parseMutationObject(mu)
if err != nil {
return resp, err
}
parsingTime += time.Since(startParsingTime)
if authorize == NeedAuthorize {
if err := authorizeMutation(ctx, gmu); err != nil {
return resp, err
}
}
if len(gmu.Set) == 0 && len(gmu.Del) == 0 {
span.Annotate(nil, "Empty mutation")
return resp, errors.Errorf("Empty mutation")
}
if req.StartTs == 0 {
req.StartTs = State.getTimestamp(false)
}
annotateStartTs(span, req.StartTs)
l, varToUID, err := doQueryInUpsert(ctx, req, gmu)
if err != nil {
return resp, err
}
parsingTime += l.Parsing
if len(varToUID) > 0 {
resp.Vars = make(map[string]*api.Uids, len(varToUID))
for v, uids := range varToUID {
// There could be a lot of these uids which could blow up the response size, especially
// for bulk mutations, hence only return variables which have less than a million uids.
if len(uids) <= 1e6 {
hexUids := make([]string, 0, len(uids))
// doQueryInUpsert returns uids as base10 string representation. We convert them
// to base16 string so that response format is consistent with assigned uids.
for _, uid := range uids {
u, err := strconv.ParseUint(uid, 10, 64)
if err != nil {
return resp, errors.Errorf("Couldn't parse uid: [%v] as base 10 uint64",
uid)
}
huid := fmt.Sprintf("%#x", u)
hexUids = append(hexUids, huid)
}
resp.Vars[v] = &api.Uids{
Uids: hexUids,
}
}
}
}
newUids, err := query.AssignUids(ctx, gmu.Set)
if err != nil {
return resp, err
}
// resp.Uids contains a map of the node name to the uid.
// 1. For a blank node, like _:foo, the key would be foo.
// 2. For a uid variable that is part of an upsert query, like uid(foo), the key would
// be uid(foo).
resp.Uids = query.UidsToHex(query.StripBlankNode(newUids))
edges, err := query.ToDirectedEdges(gmu, newUids)
if err != nil {
return resp, err
}
m := &pb.Mutations{Edges: edges, StartTs: req.StartTs}
span.Annotatef(nil, "Applying mutations: %+v", m)
resp.Txn, err = query.ApplyMutations(ctx, m)
span.Annotatef(nil, "Txn Context: %+v. Err=%v", resp.Txn, err)
if !req.CommitNow {
if err == zero.ErrConflict {
err = status.Error(codes.FailedPrecondition, err.Error())
}
return resp, err
}
// The following logic is for committing immediately.
if err != nil {
// ApplyMutations failed. We now want to abort the transaction,
// ignoring any error that might occur during the abort (the user would
// care more about the previous error).
if resp.Txn == nil {
resp.Txn = &api.TxnContext{StartTs: req.StartTs}
}
resp.Txn.Aborted = true
_, _ = worker.CommitOverNetwork(ctx, resp.Txn)
if err == zero.ErrConflict {
// We have already aborted the transaction, so the error message should reflect that.
return resp, dgo.ErrAborted
}
return resp, err
}
span.Annotatef(nil, "Prewrites err: %v. Attempting to commit/abort immediately.", err)
ctxn := resp.Txn
// zero would assign the CommitTs
cts, err := worker.CommitOverNetwork(ctx, ctxn)
span.Annotatef(nil, "Status of commit at ts: %d: %v", ctxn.StartTs, err)
if err != nil {
if err == dgo.ErrAborted {
err = status.Errorf(codes.Aborted, err.Error())
resp.Txn.Aborted = true
}
return resp, err
}
// CommitNow was true, no need to send keys.
resp.Txn.Keys = resp.Txn.Keys[:0]
resp.Txn.CommitTs = cts
return resp, nil
}
// doQueryInUpsert processes the query in upsert block.
// It returns the latency and a map of variables => [ uids ...] used in the upsert mutation.
func doQueryInUpsert(ctx context.Context, req *api.Request, gmu *gql.Mutation) (
*query.Latency, map[string][]string, error) {
l := &query.Latency{}
if req.Query == "" {
return l, nil, nil
}
mu := req.Mutations[0]
upsertQuery := req.Query
needVars := findVars(gmu)
isCondUpsert := strings.TrimSpace(mu.Cond) != ""
// conditionalVar is a dummy var that we use to evaluate the result of
// conditional upsert.
conditionalVar := fmt.Sprintf("__dgraph%d__", rand.Int())
if isCondUpsert {
// @if in upsert is same as @filter in the query
cond := strings.Replace(mu.Cond, "@if", "@filter", 1)
// Add dummy query to evaluate the @if directive, ok to use uid(0) because
// dgraph doesn't check for existence of UIDs until we query for other predicates.
// Here, we are only querying for uid predicate in the dummy query.
//
// For example if - mu.Query = {
// me(...) {...}
// }
//
// Then, upsertQuery = {
// me(...) {...}
// __dgraph0__ as var(func: uid(0)) @if(...)
// }
//
// The variable __dgraph0__ will -
// * be empty if the condition is true
// * have 1 UID (the 0 UID) if the condition is false
upsertQuery = strings.TrimSuffix(strings.TrimSpace(req.Query), "}")
upsertQuery += conditionalVar + ` as var(func: uid(0)) ` + cond + `}`
needVars = append(needVars, conditionalVar)
}
startParsingTime := time.Now()
parsedReq, err := gql.ParseWithNeedVars(gql.Request{
Str: upsertQuery,
Variables: make(map[string]string),
}, needVars)
l.Parsing += time.Since(startParsingTime)
if err != nil {
return nil, nil, errors.Wrapf(err, "while parsing query: %q", upsertQuery)
}
if err := validateQuery(parsedReq.Query); err != nil {
return nil, nil, errors.Wrapf(err, "while validating query: %q", upsertQuery)
}
if err := authorizeQuery(ctx, &parsedReq); err != nil {
return nil, nil, err
}
qr := query.Request{Latency: l, GqlQuery: &parsedReq, ReadTs: req.StartTs}
if err := qr.ProcessQuery(ctx); err != nil {
return nil, nil, errors.Wrapf(err, "while processing query: %q", upsertQuery)
}
if len(qr.Vars) <= 0 {
return nil, nil, errors.Errorf("upsert query block has no variables")
}
// varToUID contains a map of variable name to the uids corresponding to it.
// It is used later for constructing set and delete mutations by replacing variables
// with the actual uids they correspond to.
// If a variable doesn't have any UID, we generate one ourselves later.
varToUID := make(map[string][]string)
for name, v := range qr.Vars {
if v.Uids == nil || len(v.Uids.Uids) <= 0 {
continue
}
uids := make([]string, len(v.Uids.Uids))
for i, u := range v.Uids.Uids {
// We use base 10 here because the RDF mutations expect the uid to be in base 10.
uids[i] = strconv.FormatUint(u, 10)
}
varToUID[name] = uids
}
// If @if condition is false, no need to process the mutations
if isCondUpsert {
v, ok := qr.Vars[conditionalVar]
isMut := ok && v.Uids != nil && len(v.Uids.Uids) == 1
if !isMut {
gmu.Set = nil
gmu.Del = nil
return l, nil, nil
}
}
updateUIDInMutations(gmu, varToUID)
updateValInMutations(gmu, qr)
// varToUID is returned to the client, let's delete the dummy var that we put in there for
// evaluating the conditional upsert.
delete(varToUID, conditionalVar)
return l, varToUID, nil
}
// findVars finds all the variables used in mutation block
func findVars(gmu *gql.Mutation) []string {
vars := make(map[string]struct{})
updateVars := func(s string) {
if strings.HasPrefix(s, "uid(") || strings.HasPrefix(s, "val(") {
varName := s[4 : len(s)-1]
vars[varName] = struct{}{}
}
}
for _, nq := range gmu.Set {
updateVars(nq.Subject)
updateVars(nq.ObjectId)
}
for _, nq := range gmu.Del {
updateVars(nq.Subject)
updateVars(nq.ObjectId)
}
varsList := make([]string, 0, len(vars))
for v := range vars {
varsList = append(varsList, v)
}
if glog.V(3) {
glog.Infof("Variables used in mutation block: %v", varsList)
}
return varsList
}
// updateValInNQuads picks the val() from object and replaces it with its value
// Assumption is that Subject can contain UID, whereas Object can contain Val
// If val(variable) exists in a query, but the values are not there for the variable,
// it will ignore the mutation silently.
func updateValInNQuads(nquads []*api.NQuad, req query.Request) []*api.NQuad {
getNewVals := func(s string) (map[uint64]types.Val, bool) {
if strings.HasPrefix(s, "val(") {
varName := s[4 : len(s)-1]
if vals, ok := req.Vars[varName]; ok {
return vals.Vals, true
}
return nil, true
}
return nil, false
}
getValue := func(key uint64, uidToVal map[uint64]types.Val) (types.Val, bool) {
val, ok := uidToVal[key]
if ok {
return val, true
}
// Check if the variable is aggregate variable
// Only 0 key would exist for aggregate variable
val, ok = uidToVal[0]
return val, ok
}
newNQuads := nquads[:0]
for _, nq := range nquads {
// Check if the nquad contains a val() in Object or not.
// If not then, keep the mutation and continue
uidToVal, found := getNewVals(nq.ObjectId)
if !found {
newNQuads = append(newNQuads, nq)
continue
}
// uid(u) <amount> val(amt)
// For each NQuad, we need to convert the val(variable_name)
// to *api.Value before applying the mutation. For that, first
// we convert key to uint64 and get the UID to Value map from
// the result of the query.
if nq.Subject[0] == '_' {
// UID is of format "_:uid(u)". Ignore silently
continue
}
key, err := strconv.ParseUint(nq.Subject, 0, 64)
if err != nil {
// Key conversion failed, ignoring the nquad. Ideally,
// it shouldn't happen as this is the result of a query.
glog.Errorf("Conversion of subject %s failed. Error: %s",
nq.Subject, err.Error())
continue
}
// Get the value to the corresponding UID(key) from the query result
nq.ObjectId = ""
val, ok := getValue(key, uidToVal)
if !ok {
continue
}
// Convert the value from types.Val to *api.Value
nq.ObjectValue, err = types.ObjectValue(val.Tid, val.Value)
if err != nil {
// Value conversion failed, ignoring the nquad. Ideally,
// it shouldn't happen as this is the result of a query.
glog.Errorf("Conversion of %s failed for %d subject. Error: %s",
nq.ObjectId, key, err.Error())
continue
}
newNQuads = append(newNQuads, nq)
}
return newNQuads
}
// updateValInMuations does following transformations:
// 0x123 <amount> val(v) -> 0x123 <amount> 13.0
func updateValInMutations(gmu *gql.Mutation, req query.Request) {
gmu.Del = updateValInNQuads(gmu.Del, req)
gmu.Set = updateValInNQuads(gmu.Set, req)
}
// updateUIDInMutations does following transformations:
// * uid(v) -> 0x123 -- If v is defined in query block
// * uid(v) -> _:uid(v) -- Otherwise
func updateUIDInMutations(gmu *gql.Mutation, varToUID map[string][]string) {
// usedMutationVars keeps track of variables that are used in mutations.
usedMutationVars := make(map[string]bool)
getNewVals := func(s string) []string {
if strings.HasPrefix(s, "uid(") {
varName := s[4 : len(s)-1]
if uids, ok := varToUID[varName]; ok {
usedMutationVars[varName] = true
return uids
}
return []string{"_:" + s}
}
return []string{s}
}
getNewNQuad := func(nq *api.NQuad, s, o string) *api.NQuad {
// The following copy is fine because we only modify Subject and ObjectId.
// The pointer values are not modified across different copies of NQuad.
n := *nq
n.Subject = s
n.ObjectId = o
return &n
}
// Remove the mutations from gmu.Del when no UID was found.
gmuDel := make([]*api.NQuad, 0, len(gmu.Del))
for _, nq := range gmu.Del {
// if Subject or/and Object are variables, each NQuad can result
// in multiple NQuads if any variable stores more than one UIDs.
newSubs := getNewVals(nq.Subject)
newObs := getNewVals(nq.ObjectId)
for _, s := range newSubs {
for _, o := range newObs {
// Blank node has no meaning in case of deletion.
if strings.HasPrefix(s, "_:uid(") ||
strings.HasPrefix(o, "_:uid(") {
continue
}
gmuDel = append(gmuDel, getNewNQuad(nq, s, o))
}
}
}
gmu.Del = gmuDel
// Update the values in mutation block from the query block.
gmuSet := make([]*api.NQuad, 0, len(gmu.Set))
for _, nq := range gmu.Set {
newSubs := getNewVals(nq.Subject)
newObs := getNewVals(nq.ObjectId)
for _, s := range newSubs {
for _, o := range newObs {
gmuSet = append(gmuSet, getNewNQuad(nq, s, o))
}
}
}
for v := range varToUID {
// We only want to return the vars which are used in the mutation.
if _, ok := usedMutationVars[v]; !ok {
delete(varToUID, v)
}
}
gmu.Set = gmuSet
}
// Query handles queries and returns the data.
func (s *Server) Query(ctx context.Context, req *api.Request) (*api.Response, error) {
if len(req.Mutations) > 0 {
return s.doMutate(ctx, req, NeedAuthorize)
}
return s.doQuery(ctx, req, NeedAuthorize)
}
// This method is used to execute the query and return the response to the
// client as a protocol buffer message.
func (s *Server) doQuery(ctx context.Context, req *api.Request, authorize int) (
resp *api.Response, rerr error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
startTime := time.Now()
var measurements []ostats.Measurement
ctx, span := otrace.StartSpan(ctx, methodQuery)
ctx = x.WithMethod(ctx, methodQuery)
defer func() {
span.End()
v := x.TagValueStatusOK
if rerr != nil {
v = x.TagValueStatusError
}
ctx, _ = tag.New(ctx, tag.Upsert(x.KeyStatus, v))
timeSpentMs := x.SinceMs(startTime)
measurements = append(measurements, x.LatencyMs.M(timeSpentMs))
ostats.Record(ctx, measurements...)
}()
if err := x.HealthCheck(); err != nil {
return nil, err
}
ostats.Record(ctx, x.PendingQueries.M(1), x.NumQueries.M(1))
defer func() {
measurements = append(measurements, x.PendingQueries.M(-1))
}()
resp = &api.Response{}
if len(req.Query) == 0 {
span.Annotate(nil, "Empty query")
return resp, errors.Errorf("Empty query")
}
var l query.Latency
l.Start = time.Now()
span.Annotatef(nil, "Query received: %v", req)
parsedReq, err := gql.Parse(gql.Request{
Str: req.Query,
Variables: req.Vars,
})
if err != nil {
return resp, err
}
if err = validateQuery(parsedReq.Query); err != nil {
return resp, err
}
if authorize == NeedAuthorize {
if err := authorizeQuery(ctx, &parsedReq); err != nil {
return nil, err
}
}
var queryRequest = query.Request{
Latency: &l,
GqlQuery: &parsedReq,
}
// Here we try our best effort to not contact Zero for a timestamp. If we succeed,
// then we use the max known transaction ts value (from ProcessDelta) for a read-only query.
// If we haven't processed any updates yet then fall back to getting TS from Zero.
switch {
case req.BestEffort:
span.Annotate([]otrace.Attribute{otrace.BoolAttribute("be", true)}, "")
case req.ReadOnly:
span.Annotate([]otrace.Attribute{otrace.BoolAttribute("ro", true)}, "")
default:
span.Annotate([]otrace.Attribute{otrace.BoolAttribute("no", true)}, "")
}