-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
server.go
1256 lines (1088 loc) · 34.5 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 (
"bytes"
"encoding/json"
"math"
"sort"
"strconv"
"strings"
"time"
"unicode"
"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/conn"
"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/gogo/protobuf/jsonpb"
"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"
"go.opencensus.io/trace"
otrace "go.opencensus.io/trace"
)
const (
methodMutate = "Server.Mutate"
methodQuery = "Server.Query"
groupFile = "group_id"
)
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
)
// Server implements protos.DgraphServer
type Server struct{}
// 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: worker.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, qc *queryContext, resp *api.Response) error {
if len(qc.gmuList) == 0 {
return nil
}
if ctx.Err() != nil {
return ctx.Err()
}
start := time.Now()
defer func() {
qc.latency.Processing += time.Since(start)
}()
if !isMutationAllowed(ctx) {
return errors.Errorf("no mutations allowed")
}
// update mutations from the query results before assigning UIDs
updateMutations(qc)
newUids, err := query.AssignUids(ctx, qc.gmuList)
if err != nil {
return 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(qc.gmuList, newUids)
if err != nil {
return err
}
predHints := make(map[string]pb.Metadata_HintType)
for _, gmu := range qc.gmuList {
for pred, hint := range gmu.Metadata.GetPredHints() {
if oldHint := predHints[pred]; oldHint == pb.Metadata_LIST {
continue
}
predHints[pred] = hint
}
}
m := &pb.Mutations{
Edges: edges,
StartTs: qc.req.StartTs,
Metadata: &pb.Metadata{
PredHints: predHints,
},
}
qc.span.Annotatef(nil, "Applying mutations: %+v", m)
resp.Txn, err = query.ApplyMutations(ctx, m)
qc.span.Annotatef(nil, "Txn Context: %+v. Err=%v", resp.Txn, err)
if !qc.req.CommitNow {
if err == zero.ErrConflict {
err = status.Error(codes.FailedPrecondition, err.Error())
}
return 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: qc.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 dgo.ErrAborted
}
return err
}
qc.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)
qc.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 err
}
// CommitNow was true, no need to send keys.
resp.Txn.Keys = resp.Txn.Keys[:0]
resp.Txn.CommitTs = cts
return nil
}
// buildUpsertQuery modifies the query to evaluate the
// @if condition defined in Conditional Upsert.
func buildUpsertQuery(qc *queryContext) string {
if len(qc.req.Query) == 0 || len(qc.gmuList) == 0 {
return qc.req.Query
}
qc.condVars = make([]string, len(qc.req.Mutations))
upsertQuery := strings.TrimSuffix(qc.req.Query, "}")
for i, gmu := range qc.gmuList {
isCondUpsert := strings.TrimSpace(gmu.Cond) != ""
if isCondUpsert {
qc.condVars[i] = "__dgraph__" + strconv.Itoa(i)
qc.uidRes[qc.condVars[i]] = nil
// @if in upsert is same as @filter in the query
cond := strings.Replace(gmu.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(...) {...}
// __dgraph_0__ as var(func: uid(0)) @filter(...)
// }
//
// The variable __dgraph_0__ will -
// * be empty if the condition is true
// * have 1 UID (the 0 UID) if the condition is false
upsertQuery += qc.condVars[i] + ` as var(func: uid(0)) ` + cond + `
`
}
}
upsertQuery += `}`
return upsertQuery
}
// updateMutations updates the mutation and replaces uid(var) and val(var) with
// their values or a blank node, in case of an upsert.
// We use the values stored in qc.uidRes and qc.valRes to update the mutation.
func updateMutations(qc *queryContext) {
for i, condVar := range qc.condVars {
gmu := qc.gmuList[i]
if len(condVar) != 0 {
uids, ok := qc.uidRes[condVar]
if !(ok && len(uids) == 1) {
gmu.Set = nil
gmu.Del = nil
continue
}
}
updateUIDInMutations(gmu, qc)
updateValInMutations(gmu, qc)
}
}
// findMutationVars finds all the variables used in mutation block and stores them
// qc.uidRes and qc.valRes so that we only look for these variables in query results.
func findMutationVars(qc *queryContext) []string {
updateVars := func(s string) {
if strings.HasPrefix(s, "uid(") {
varName := s[4 : len(s)-1]
qc.uidRes[varName] = nil
} else if strings.HasPrefix(s, "val(") {
varName := s[4 : len(s)-1]
qc.valRes[varName] = nil
}
}
for _, gmu := range qc.gmuList {
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(qc.uidRes)+len(qc.valRes))
for v := range qc.uidRes {
varsList = append(varsList, v)
}
for v := range qc.valRes {
varsList = append(varsList, v)
}
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, qc *queryContext) []*api.NQuad {
getNewVals := func(s string) (map[uint64]types.Val, bool) {
if strings.HasPrefix(s, "val(") {
varName := s[4 : len(s)-1]
if v, ok := qc.valRes[varName]; ok && v != nil {
return v, 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, qc *queryContext) {
gmu.Del = updateValInNQuads(gmu.Del, qc)
gmu.Set = updateValInNQuads(gmu.Set, qc)
}
// updateUIDInMutations does following transformations:
// * uid(v) -> 0x123 -- If v is defined in query block
// * uid(v) -> _:uid(v) -- Otherwise
func updateUIDInMutations(gmu *gql.Mutation, qc *queryContext) {
// usedMutationVars keeps track of variables that are used in mutations.
getNewVals := func(s string) []string {
if strings.HasPrefix(s, "uid(") {
varName := s[4 : len(s)-1]
if uids, ok := qc.uidRes[varName]; ok && len(uids) != 0 {
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))
}
}
}
gmu.Set = gmuSet
}
// queryContext is used to pass around all the variables needed
// to process a request for query, mutation or upsert.
type queryContext struct {
// req is the incoming, not yet parsed request containing
// a query or more than one mutations or both (in case of upsert)
req *api.Request
// gmuList is the list of mutations after parsing req.Mutations
gmuList []*gql.Mutation
// gqlRes contains result of parsing the req.Query
gqlRes gql.Result
// condVars are conditional variables used in the (modified) query to figure out
// whether the condition in Conditional Upsert is true. The string would be empty
// if the corresponding mutation is not a conditional upsert.
// Note that, len(condVars) == len(gmuList).
condVars []string
// uidRes stores mapping from variable names to UIDs for UID variables.
// These variables are either dummy variables used for Conditional
// Upsert or variables used in the mutation block in the incoming request.
uidRes map[string][]string
// valRes stores mapping from variable names to values for value
// variables used in the mutation block of incoming request.
valRes map[string]map[uint64]types.Val
// l stores latency numbers
latency *query.Latency
// span stores a opencensus span used throughout the query processing
span *trace.Span
}
// HealthAll handles health?all requests
func (s *Server) HealthAll(ctx context.Context) (*api.Response, error) {
return s.doHealthAll(ctx, NeedAuthorize)
}
func (s *Server) doHealthAll(ctx context.Context, authorize int) (*api.Response, error) {
var err error
if ctx.Err() != nil {
return nil, ctx.Err()
}
if authorize == NeedAuthorize {
if err := authorizeForGroot(ctx); err != nil {
return nil, err
}
}
ms := worker.GetMembershipState()
if ms == nil {
return nil, errors.Errorf("No membership state found")
}
health := make(map[string][]pb.HealthInfo)
process := func(vm *pb.Member) {
curr := pb.HealthInfo{
Addr: vm.GetAddr(),
}
// get health locally if self.
if vm.GetAddr() == x.WorkerConfig.MyAddr {
curr.Instance = "alpha"
curr.Group = strconv.Itoa(int(vm.GroupId))
curr.Version = x.Version()
curr.Uptime = uint64(time.Since(x.WorkerConfig.BeginTime))
} else {
p, err := conn.GetPools().Get(vm.GetAddr())
if err != nil {
health["unhealthy"] = append(health["unhealthy"], curr)
return
}
curr = p.GetHealthInfo()
}
health["healthy"] = append(health["healthy"], curr)
}
// get health from each group member
for _, vg := range ms.Groups {
for _, vm := range vg.Members {
process(vm)
}
}
// get health from zeros.
for _, vz := range ms.Zeros {
process(vz)
}
var jsonOut []byte
if jsonOut, err = json.Marshal(health); err != nil {
return nil, errors.Errorf("Unable to Marshal. Err %v", err)
}
return &api.Response{Json: jsonOut}, nil
}
// State handles state requests
func (s *Server) State(ctx context.Context) (*api.Response, error) {
return s.doState(ctx, NeedAuthorize)
}
func (s *Server) doState(ctx context.Context, authorize int) (
*api.Response, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
if authorize == NeedAuthorize {
if err := authorizeForGroot(ctx); err != nil {
return nil, err
}
}
ms := worker.GetMembershipState()
if ms == nil {
return nil, errors.Errorf("No membership state found")
}
m := jsonpb.Marshaler{}
var jsonState bytes.Buffer
if err := m.Marshal(&jsonState, ms); err != nil {
return nil, errors.Errorf("Error marshalling state information to JSON")
}
return &api.Response{Json: jsonState.Bytes()}, nil
}
// Query handles queries or mutations
func (s *Server) Query(ctx context.Context, req *api.Request) (*api.Response, error) {
return s.doQuery(ctx, req, NeedAuthorize)
}
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()
}
l := &query.Latency{}
l.Start = time.Now()
isMutation := len(req.Mutations) > 0
methodRequest := methodQuery
if isMutation {
methodRequest = methodMutate
}
var measurements []ostats.Measurement
ctx, span := otrace.StartSpan(ctx, methodRequest)
ctx = x.WithMethod(ctx, methodRequest)
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(l.Start)
measurements = append(measurements, x.LatencyMs.M(timeSpentMs))
ostats.Record(ctx, measurements...)
}()
if rerr = x.HealthCheck(); rerr != nil {
return
}
req.Query = strings.TrimSpace(req.Query)
isQuery := len(req.Query) != 0
if !isQuery && !isMutation {
span.Annotate(nil, "empty request")
return nil, errors.Errorf("empty request")
}
span.Annotatef(nil, "Request received: %v", req)
if isQuery {
ostats.Record(ctx, x.PendingQueries.M(1), x.NumQueries.M(1))
defer func() {
measurements = append(measurements, x.PendingQueries.M(-1))
}()
}
if isMutation {
ostats.Record(ctx, x.NumMutations.M(1))
}
qc := &queryContext{req: req, latency: l, span: span}
if rerr = parseRequest(qc); rerr != nil {
return
}
if authorize == NeedAuthorize {
if rerr = authorizeRequest(ctx, qc); rerr != nil {
return
}
}
// We use defer here because for queries, startTs will be
// assigned in the processQuery function called below.
defer annotateStartTs(qc.span, qc.req.StartTs)
// For mutations, we update the startTs if necessary.
if isMutation && req.StartTs == 0 {
start := time.Now()
req.StartTs = worker.State.GetTimestamp(false)
qc.latency.AssignTimestamp = time.Since(start)
}
if resp, rerr = processQuery(ctx, qc); rerr != nil {
return
}
if rerr = s.doMutate(ctx, qc, resp); rerr != nil {
return
}
// TODO(martinmr): Include Transport as part of the latency. Need to do
// this separately since it involves modifying the API protos.
resp.Latency = &api.Latency{
AssignTimestampNs: uint64(l.AssignTimestamp.Nanoseconds()),
ParsingNs: uint64(l.Parsing.Nanoseconds()),
ProcessingNs: uint64(l.Processing.Nanoseconds()),
EncodingNs: uint64(l.Json.Nanoseconds()),
TotalNs: uint64((time.Since(l.Start)).Nanoseconds()),
}
return resp, nil
}
func processQuery(ctx context.Context, qc *queryContext) (*api.Response, error) {
resp := &api.Response{}
if len(qc.req.Query) == 0 {
return resp, nil
}
qr := query.Request{
Latency: qc.latency,
GqlQuery: &qc.gqlRes,
}
// 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 qc.req.BestEffort:
qc.span.Annotate([]otrace.Attribute{otrace.BoolAttribute("be", true)}, "")
case qc.req.ReadOnly:
qc.span.Annotate([]otrace.Attribute{otrace.BoolAttribute("ro", true)}, "")
default:
qc.span.Annotate([]otrace.Attribute{otrace.BoolAttribute("no", true)}, "")
}
if qc.req.BestEffort {
// Sanity: check that request is read-only too.
if !qc.req.ReadOnly {
return resp, errors.Errorf("A best effort query must be read-only.")
}
if qc.req.StartTs == 0 {
qc.req.StartTs = posting.Oracle().MaxAssigned()
}
qr.Cache = worker.NoCache
}
if qc.req.StartTs == 0 {
assignTimestampStart := time.Now()
qc.req.StartTs = worker.State.GetTimestamp(qc.req.ReadOnly)
qc.latency.AssignTimestamp = time.Since(assignTimestampStart)
}
qr.ReadTs = qc.req.StartTs
resp.Txn = &api.TxnContext{StartTs: qc.req.StartTs}
// Core processing happens here.
er, err := qr.Process(ctx)
if err != nil {
return resp, errors.Wrap(err, "")
}
if len(er.SchemaNode) > 0 || len(er.Types) > 0 {
sort.Slice(er.SchemaNode, func(i, j int) bool {
return er.SchemaNode[i].Predicate < er.SchemaNode[j].Predicate
})
sort.Slice(er.Types, func(i, j int) bool {
return er.Types[i].TypeName < er.Types[j].TypeName
})
respMap := make(map[string]interface{})
if len(er.SchemaNode) > 0 {
respMap["schema"] = er.SchemaNode
}
if len(er.Types) > 0 {
respMap["types"] = formatTypes(er.Types)
}
resp.Json, err = json.Marshal(respMap)
} else {
resp.Json, err = query.ToJson(qc.latency, er.Subgraphs)
}
if err != nil {
return resp, err
}
qc.span.Annotatef(nil, "Response = %s", resp.Json)
// 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.
for name := range qc.uidRes {
v := qr.Vars[name]
// If the list of UIDs is empty but the map of values is not,
// we need to get the UIDs from the keys in the map.
var uidList []uint64
if v.Uids != nil && len(v.Uids.Uids) > 0 {
uidList = v.Uids.Uids
} else {
uidList = make([]uint64, 0, len(v.Vals))
for uid := range v.Vals {
uidList = append(uidList, uid)
}
}
if len(uidList) == 0 {
continue
}
// We support maximum 1 million UIDs per variable to ensure that we
// don't do bad things to alpha and mutation doesn't become too big.
if len(uidList) > 1e6 {
return resp, errors.Errorf("var [%v] has over million UIDs", name)
}
uids := make([]string, len(uidList))
for i, u := range uidList {
// We use base 10 here because the RDF mutations expect the uid to be in base 10.
uids[i] = strconv.FormatUint(u, 10)
}
qc.uidRes[name] = uids
}
// look for values for value variables
for name := range qc.valRes {
v := qr.Vars[name]
qc.valRes[name] = v.Vals
}
resp.Metrics = &api.Metrics{
NumUids: er.Metrics,
}
return resp, err
}
// parseRequest parses the incoming request
func parseRequest(qc *queryContext) error {
start := time.Now()
defer func() {
qc.latency.Parsing = time.Since(start)
}()
var needVars []string
upsertQuery := qc.req.Query
if len(qc.req.Mutations) > 0 {
// parsing mutations
qc.gmuList = make([]*gql.Mutation, 0, len(qc.req.Mutations))
for _, mu := range qc.req.Mutations {
gmu, err := parseMutationObject(mu)
if err != nil {
return err
}
qc.gmuList = append(qc.gmuList, gmu)
}
qc.uidRes = make(map[string][]string)
qc.valRes = make(map[string]map[uint64]types.Val)
upsertQuery = buildUpsertQuery(qc)
needVars = findMutationVars(qc)
if len(upsertQuery) == 0 {
if len(needVars) > 0 {
return errors.Errorf("variables %v not defined", needVars)
}
return nil
}
}
// parsing the updated query
var err error
qc.gqlRes, err = gql.ParseWithNeedVars(gql.Request{
Str: upsertQuery,
Variables: qc.req.Vars,
}, needVars)
if err != nil {
return err
}
if err = validateQuery(qc.gqlRes.Query); err != nil {
return err
}
return nil
}
func authorizeRequest(ctx context.Context, qc *queryContext) error {
if err := authorizeQuery(ctx, &qc.gqlRes); err != nil {
return err
}
// TODO(Aman): can be optimized to do the authorization in just one func call
for _, gmu := range qc.gmuList {
if err := authorizeMutation(ctx, gmu); err != nil {
return err
}
}
return nil
}
// CommitOrAbort commits or aborts a transaction.
func (s *Server) CommitOrAbort(ctx context.Context, tc *api.TxnContext) (*api.TxnContext, error) {
ctx, span := otrace.StartSpan(ctx, "Server.CommitOrAbort")
defer span.End()
if err := x.HealthCheck(); err != nil {
return &api.TxnContext{}, err
}
tctx := &api.TxnContext{}
if tc.StartTs == 0 {
return &api.TxnContext{}, errors.Errorf(
"StartTs cannot be zero while committing a transaction")
}