-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
server.go
1640 lines (1445 loc) · 46.6 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"
"context"
"encoding/json"
"fmt"
"math"
"net"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
"unicode"
"github.com/gogo/protobuf/jsonpb"
"github.com/golang/glog"
"github.com/pkg/errors"
ostats "go.opencensus.io/stats"
"go.opencensus.io/tag"
"go.opencensus.io/trace"
otrace "go.opencensus.io/trace"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"github.com/dgraph-io/badger/v2/y"
"github.com/dgraph-io/dgo/v200"
"github.com/dgraph-io/dgo/v200/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/ee"
"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/telemetry"
"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"
)
const (
methodMutate = "Server.Mutate"
methodQuery = "Server.Query"
groupFile = "group_id"
)
type GraphqlContextKey int
const (
// IsGraphql is used to validate requests which are allowed to mutate GraphQL reserved
// predicates, like dgraph.graphql.schema and dgraph.graphql.xid.
IsGraphql GraphqlContextKey = iota
// Authorize is used to set if the request requires validation.
Authorize
)
type AuthMode int
const (
// NeedAuthorize is used to indicate that the request needs to be authorized.
NeedAuthorize AuthMode = 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
// CorsMutationAllowed is used to indicate that the given request is authorized to do
// cors mutation.
CorsMutationAllowed
)
var (
numGraphQLPM uint64
numGraphQL uint64
)
var (
errIndexingInProgress = errors.New("errIndexingInProgress. Please retry")
)
// Server implements protos.DgraphServer
type Server struct{}
// graphQLSchemaNode represents the node which contains GraphQL schema
type graphQLSchemaNode struct {
Uid string `json:"uid"`
Schema string `json:"dgraph.graphql.schema"`
}
type existingGQLSchemaQryResp struct {
ExistingGQLSchema []graphQLSchemaNode `json:"ExistingGQLSchema"`
}
// PeriodicallyPostTelemetry periodically reports telemetry data for alpha.
func PeriodicallyPostTelemetry() {
glog.V(2).Infof("Starting telemetry data collection for alpha...")
start := time.Now()
ticker := time.NewTicker(time.Minute * 10)
defer ticker.Stop()
var lastPostedAt time.Time
for range ticker.C {
if time.Since(lastPostedAt) < time.Hour {
continue
}
ms := worker.GetMembershipState()
t := telemetry.NewAlpha(ms)
t.NumGraphQLPM = atomic.SwapUint64(&numGraphQLPM, 0)
t.NumGraphQL = atomic.SwapUint64(&numGraphQL, 0)
t.SinceHours = int(time.Since(start).Hours())
glog.V(2).Infof("Posting Telemetry data: %+v", t)
err := t.Post()
if err == nil {
lastPostedAt = time.Now()
} else {
atomic.AddUint64(&numGraphQLPM, t.NumGraphQLPM)
atomic.AddUint64(&numGraphQL, t.NumGraphQL)
glog.V(2).Infof("Telemetry couldn't be posted. Error: %v", err)
}
}
}
// GetGQLSchema queries for the GraphQL schema node, and returns the uid and the GraphQL schema.
// If multiple schema nodes were found, it returns an error.
func GetGQLSchema() (uid, graphQLSchema string, err error) {
resp, err := (&Server{}).Query(context.WithValue(context.Background(), Authorize, false),
&api.Request{
Query: `
query {
ExistingGQLSchema(func: has(dgraph.graphql.schema)) {
uid
dgraph.graphql.schema
}
}`})
if err != nil {
return "", "", err
}
var result existingGQLSchemaQryResp
if err := json.Unmarshal(resp.GetJson(), &result); err != nil {
return "", "", errors.Wrap(err, "Couldn't unmarshal response from Dgraph query")
}
if len(result.ExistingGQLSchema) == 0 {
// no schema has been stored yet in Dgraph
return "", "", nil
} else if len(result.ExistingGQLSchema) == 1 {
// we found an existing GraphQL schema
gqlSchemaNode := result.ExistingGQLSchema[0]
return gqlSchemaNode.Uid, gqlSchemaNode.Schema, nil
}
// found multiple GraphQL schema nodes, this should never happen
return "", "", worker.ErrMultipleGraphQLSchemaNodes
}
// UpdateGQLSchema updates the GraphQL and Dgraph schemas using the given inputs.
// It first validates and parses the dgraphSchema given in input. If that fails,
// it returns an error. All this is done on the alpha on which the update request is received.
// Then it sends an update request to the worker, which is executed only on Group-1 leader.
func UpdateGQLSchema(ctx context.Context, gqlSchema,
dgraphSchema string) (*pb.UpdateGraphQLSchemaResponse, error) {
var err error
parsedDgraphSchema := &schema.ParsedSchema{}
// The schema could be empty if it only has custom types/queries/mutations.
if dgraphSchema != "" {
op := &api.Operation{Schema: dgraphSchema}
if err = validateAlterOperation(ctx, op); err != nil {
return nil, err
}
if parsedDgraphSchema, err = parseSchemaFromAlterOperation(op); err != nil {
return nil, err
}
}
return worker.UpdateGQLSchemaOverNetwork(ctx, &pb.UpdateGraphQLSchemaRequest{
StartTs: worker.State.GetTimestamp(false),
GraphqlSchema: gqlSchema,
DgraphPreds: parsedDgraphSchema.Preds,
DgraphTypes: parsedDgraphSchema.Types,
})
}
// validateAlterOperation validates the given operation for alter.
func validateAlterOperation(ctx context.Context, op *api.Operation) error {
// 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 errors.Errorf("Operation must have at least one field set")
}
if err := x.HealthCheck(); err != nil {
return err
}
if isDropAll(op) && op.DropOp == api.Operation_DATA {
return errors.Errorf("Only one of DropAll and DropData can be true")
}
if !isMutationAllowed(ctx) {
return errors.Errorf("No mutations allowed by server.")
}
if _, err := hasAdminAuth(ctx, "Alter"); err != nil {
glog.Warningf("Alter denied with error: %v\n", err)
return err
}
if err := authorizeAlter(ctx, op); err != nil {
glog.Warningf("Alter denied with error: %v\n", err)
return err
}
return nil
}
// parseSchemaFromAlterOperation parses the string schema given in input operation to a Go
// struct, and performs some checks to make sure that the schema is valid.
func parseSchemaFromAlterOperation(op *api.Operation) (*schema.ParsedSchema, error) {
// If a background task is already running, we should reject all the new alter requests.
if schema.State().IndexingInProgress() {
return nil, errIndexingInProgress
}
result, err := schema.Parse(op.Schema)
if err != nil {
return nil, err
}
for _, update := range result.Preds {
// Pre-defined predicates cannot be altered but let the update go through
// if the update is equal to the existing one.
if schema.IsPreDefPredChanged(update) {
return nil, errors.Errorf("predicate %s is pre-defined and is not allowed to be"+
" modified", update.Predicate)
}
if err := validatePredName(update.Predicate); err != nil {
return nil, err
}
// Users are not allowed to create a predicate under the reserved `dgraph.` namespace. But,
// there are pre-defined predicates (subset of reserved predicates), and for them we allow
// the schema update to go through if the update is equal to the existing one.
// So, here we check if the predicate is reserved but not pre-defined to block users from
// creating predicates in reserved namespace.
if x.IsReservedPredicate(update.Predicate) && !x.IsPreDefinedPredicate(update.Predicate) {
return nil, errors.Errorf("Can't alter predicate `%s` as it is prefixed with `dgraph.`"+
" which is reserved as the namespace for dgraph's internal types/predicates.",
update.Predicate)
}
}
for _, typ := range result.Types {
// Pre-defined types cannot be altered but let the update go through
// if the update is equal to the existing one.
if schema.IsPreDefTypeChanged(typ) {
return nil, errors.Errorf("type %s is pre-defined and is not allowed to be modified",
typ.TypeName)
}
// Users are not allowed to create types in reserved namespace. But, there are pre-defined
// types for which the update should go through if the update is equal to the existing one.
if x.IsReservedType(typ.TypeName) && !x.IsPreDefinedType(typ.TypeName) {
return nil, errors.Errorf("Can't alter type `%s` as it is prefixed with `dgraph.` "+
"which is reserved as the namespace for dgraph's internal types/predicates.",
typ.TypeName)
}
}
return result, nil
}
// 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)
// check if the operation is valid
if err := validateAlterOperation(ctx, op); err != nil {
return nil, err
}
defer glog.Infof("ALTER op: %+v done", op)
empty := &api.Payload{}
// 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)
if err != nil {
return empty, err
}
// insert empty GraphQL schema, so all alphas get notified to
// reset their in-memory GraphQL schema
_, err = UpdateGQLSchema(ctx, "", "")
// recreate the admin account after a drop all operation
ResetAcl(nil)
ResetCors(nil)
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")
}
// query the GraphQL schema and keep it in memory, so it can be inserted again
_, graphQLSchema, err := GetGQLSchema()
if err != nil {
return empty, err
}
m.DropOp = pb.Mutations_DATA
_, err = query.ApplyMutations(ctx, m)
if err != nil {
return empty, err
}
// just reinsert the GraphQL schema, no need to alter dgraph schema as this was drop_data
_, err = UpdateGQLSchema(ctx, graphQLSchema, "")
// recreate the admin account after a drop data operation
ResetAcl(nil)
ResetCors(nil)
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
}
// Pre-defined predicates cannot be dropped.
if x.IsPreDefinedPredicate(attr) {
return empty, errors.Errorf("predicate %s is pre-defined and is not allowed to be"+
" dropped", attr)
}
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")
}
// Pre-defined types cannot be dropped.
if x.IsPreDefinedType(op.DropValue) {
return empty, errors.Errorf("type %s is pre-defined and is not allowed to be dropped",
op.DropValue)
}
m.DropOp = pb.Mutations_TYPE
m.DropValue = op.DropValue
_, err := query.ApplyMutations(ctx, m)
return empty, err
}
result, err := parseSchemaFromAlterOperation(op)
if 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)
if err != nil {
return empty, err
}
// wait for indexing to complete or context to be canceled.
if err = worker.WaitForIndexingOrCtxError(ctx, !op.RunInBackground); err != nil {
return empty, err
}
return empty, nil
}
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 x.WorkerConfig.LudicrousMode {
// Mutations are automatically committed in case of ludicrous mode, so we don't
// need to manually commit.
if resp.Txn != nil {
resp.Txn.Keys = resp.Txn.Keys[:0]
resp.Txn.CommitTs = qc.req.StartTs
} else {
errors.Wrapf(err, "Txn Context is nil")
}
return 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, isSet bool) []*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.
var key uint64
var err error
switch {
case nq.Subject[0] == '_' && isSet:
// in case aggregate val(var) is there, that should work with blank node.
key = 0
case nq.Subject[0] == '_' && !isSet:
// UID is of format "_:uid(u)". Ignore the delete silently
continue
default:
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, false)
gmu.Set = updateValInNQuads(gmu.Set, qc, true)
}
// 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
// graphql indicates whether the given request is from graphql admin or not.
graphql bool
}
// Health handles /health and /health?all requests.
func (s *Server) Health(ctx context.Context, all bool) (*api.Response, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
var healthAll []pb.HealthInfo
if all {
if err := AuthorizeGuardians(ctx); err != nil {
return nil, err
}
pool := conn.GetPools().GetAll()
for _, p := range pool {
if p.Addr == x.WorkerConfig.MyAddr {
continue
}
healthAll = append(healthAll, p.HealthInfo())
}
}
// Append self.
healthAll = append(healthAll, pb.HealthInfo{
Instance: "alpha",
Address: x.WorkerConfig.MyAddr,
Status: "healthy",
Group: strconv.Itoa(int(worker.GroupId())),
Version: x.Version(),
Uptime: int64(time.Since(x.WorkerConfig.StartTime) / time.Second),
LastEcho: time.Now().Unix(),
Ongoing: worker.GetOngoingTasks(),
Indexing: schema.GetIndexingPredicates(),
EeFeatures: ee.GetEEFeaturesList(),
})
var err error
var jsonOut []byte
if jsonOut, err = json.Marshal(healthAll); 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) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
if err := AuthorizeGuardians(ctx); err != nil {
return nil, err
}
ms := worker.GetMembershipState()
if ms == nil {
return nil, errors.Errorf("No membership state found")
}
m := jsonpb.Marshaler{EmitDefaults: true}
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) {
auth := ctx.Value(Authorize)
if auth == nil || auth.(bool) {
return s.doQuery(ctx, req, NeedAuthorize)
}
return s.doQuery(ctx, req, NoAuthorize)
}
func (s *Server) doQuery(ctx context.Context, req *api.Request, doAuth AuthMode) (
resp *api.Response, rerr error) {
if bool(glog.V(3)) || worker.LogRequestEnabled() {
glog.Infof("Got a query: %+v", req)
}
isGraphQL, _ := ctx.Value(IsGraphql).(bool)
if isGraphQL {
atomic.AddUint64(&numGraphQL, 1)
} else {
atomic.AddUint64(&numGraphQLPM, 1)
}
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, graphql: isGraphQL}
if rerr = parseRequest(qc); rerr != nil {
return
}
if doAuth == NeedAuthorize {
if rerr = authorizeRequest(ctx, qc); rerr != nil {
return
}
}
if doAuth != CorsMutationAllowed {
if rerr = validateCorsInMutation(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 && !x.WorkerConfig.LudicrousMode {
start := time.Now()
req.StartTs = worker.State.GetTimestamp(false)
qc.latency.AssignTimestamp = time.Since(start)
}