-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
task.go
2125 lines (1938 loc) · 57.8 KB
/
task.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 2016-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 worker
import (
"bytes"
"sort"
"strconv"
"strings"
"time"
"github.com/dgraph-io/badger"
"github.com/dgraph-io/dgo/v2/protos/api"
"github.com/dgraph-io/dgraph/algo"
"github.com/dgraph-io/dgraph/conn"
"github.com/dgraph-io/dgraph/posting"
"github.com/dgraph-io/dgraph/protos/pb"
"github.com/dgraph-io/dgraph/schema"
ctask "github.com/dgraph-io/dgraph/task"
"github.com/dgraph-io/dgraph/tok"
"github.com/dgraph-io/dgraph/types"
"github.com/dgraph-io/dgraph/types/facets"
"github.com/dgraph-io/dgraph/x"
"github.com/golang/glog"
otrace "go.opencensus.io/trace"
cindex "github.com/google/codesearch/index"
cregexp "github.com/google/codesearch/regexp"
"github.com/pkg/errors"
"golang.org/x/net/context"
)
func invokeNetworkRequest(ctx context.Context, addr string,
f func(context.Context, pb.WorkerClient) (interface{}, error)) (interface{}, error) {
pl, err := conn.GetPools().Get(addr)
if err != nil {
return &pb.Result{}, errors.Wrapf(err, "dispatchTaskOverNetwork: while retrieving connection.")
}
conn := pl.Get()
if span := otrace.FromContext(ctx); span != nil {
span.Annotatef(nil, "invokeNetworkRequest: Sending request to %v", addr)
}
c := pb.NewWorkerClient(conn)
return f(ctx, c)
}
const backupRequestGracePeriod = time.Second
// TODO: Cross-server cancellation as described in Jeff Dean's talk.
func processWithBackupRequest(
ctx context.Context,
gid uint32,
f func(context.Context, pb.WorkerClient) (interface{}, error)) (interface{}, error) {
addrs := groups().AnyTwoServers(gid)
if len(addrs) == 0 {
return nil, errors.New("No network connection")
}
if len(addrs) == 1 {
reply, err := invokeNetworkRequest(ctx, addrs[0], f)
return reply, err
}
type taskresult struct {
reply interface{}
err error
}
chResults := make(chan taskresult, len(addrs))
ctx0, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
reply, err := invokeNetworkRequest(ctx0, addrs[0], f)
chResults <- taskresult{reply, err}
}()
timer := time.NewTimer(backupRequestGracePeriod)
defer timer.Stop()
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-timer.C:
go func() {
reply, err := invokeNetworkRequest(ctx0, addrs[1], f)
chResults <- taskresult{reply, err}
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case result := <-chResults:
if result.err != nil {
select {
case <-ctx.Done():
return nil, ctx.Err()
case result := <-chResults:
return result.reply, result.err
}
} else {
return result.reply, nil
}
}
case result := <-chResults:
if result.err != nil {
cancel() // Might as well cleanup resources ASAP
timer.Stop()
return invokeNetworkRequest(ctx, addrs[1], f)
}
return result.reply, nil
}
}
// ProcessTaskOverNetwork is used to process the query and get the result from
// the instance which stores posting list corresponding to the predicate in the
// query.
func ProcessTaskOverNetwork(ctx context.Context, q *pb.Query) (*pb.Result, error) {
attr := q.Attr
gid, err := groups().BelongsToReadOnly(attr)
if err != nil {
return &pb.Result{}, err
} else if gid == 0 {
return &pb.Result{}, errNonExistentTablet
}
span := otrace.FromContext(ctx)
if span != nil {
span.Annotatef(nil, "ProcessTaskOverNetwork. attr: %v gid: %v, readTs: %d, node id: %d",
attr, gid, q.ReadTs, groups().Node.Id)
}
if groups().ServesGroup(gid) {
// No need for a network call, as this should be run from within this instance.
return processTask(ctx, q, gid)
}
result, err := processWithBackupRequest(ctx, gid,
func(ctx context.Context, c pb.WorkerClient) (interface{}, error) {
return c.ServeTask(ctx, q)
})
if err != nil {
return &pb.Result{}, err
}
reply := result.(*pb.Result)
if span != nil {
span.Annotatef(nil, "Reply from server. len: %v gid: %v Attr: %v",
len(reply.UidMatrix), gid, attr)
}
return reply, nil
}
// convertValue converts the data to the schema.State() type of predicate.
func convertValue(attr, data string) (types.Val, error) {
// Parse given value and get token. There should be only one token.
t, err := schema.State().TypeOf(attr)
if err != nil {
return types.Val{}, err
}
if !t.IsScalar() {
return types.Val{}, errors.Errorf("Attribute %s is not valid scalar type", attr)
}
src := types.Val{Tid: types.StringID, Value: []byte(data)}
dst, err := types.Convert(src, t)
return dst, err
}
// Returns nil byte on error
func convertToType(v types.Val, typ types.TypeID) (*pb.TaskValue, error) {
result := &pb.TaskValue{ValType: typ.Enum(), Val: x.Nilbyte}
if v.Tid == typ {
result.Val = v.Value.([]byte)
return result, nil
}
// convert data from binary to appropriate format
val, err := types.Convert(v, typ)
if err != nil {
return result, err
}
// Marshal
data := types.ValueForType(types.BinaryID)
err = types.Marshal(val, &data)
if err != nil {
return result, errors.Errorf("Failed convertToType during Marshal")
}
result.Val = data.Value.([]byte)
return result, nil
}
// FuncType represents the type of a query function (aggregation, has, etc).
type FuncType int
const (
notAFunction FuncType = iota
aggregatorFn
compareAttrFn
compareScalarFn
geoFn
passwordFn
regexFn
fullTextSearchFn
hasFn
uidInFn
customIndexFn
matchFn
standardFn = 100
)
func parseFuncType(srcFunc *pb.SrcFunction) (FuncType, string) {
if srcFunc == nil {
return notAFunction, ""
}
ftype, fname := parseFuncTypeHelper(srcFunc.Name)
if srcFunc.IsCount && ftype == compareAttrFn {
// gt(release_date, "1990") is 'CompareAttr' which
// takes advantage of indexed-attr
// gt(count(films), 0) is 'CompareScalar', we first do
// counting on attr, then compare the result as scalar with int
return compareScalarFn, fname
}
return ftype, fname
}
func parseFuncTypeHelper(name string) (FuncType, string) {
if len(name) == 0 {
return notAFunction, ""
}
f := strings.ToLower(name)
switch f {
case "le", "ge", "lt", "gt", "eq":
return compareAttrFn, f
case "min", "max", "sum", "avg":
return aggregatorFn, f
case "checkpwd":
return passwordFn, f
case "regexp":
return regexFn, f
case "alloftext", "anyoftext":
return fullTextSearchFn, f
case "has":
return hasFn, f
case "uid_in":
return uidInFn, f
case "anyof", "allof":
return customIndexFn, f
case "match":
return matchFn, f
default:
if types.IsGeoFunc(f) {
return geoFn, f
}
return standardFn, f
}
}
func needsIndex(fnType FuncType) bool {
switch fnType {
case compareAttrFn, geoFn, fullTextSearchFn, standardFn, matchFn:
return true
}
return false
}
// needsIntersect checks if the function type needs algo.IntersectSorted() after the results
// are collected. This is needed for functions that require all values to match, like
// "allofterms", "alloftext", and custom functions with "allof".
// Returns true if function results need intersect, false otherwise.
func needsIntersect(fnName string) bool {
return strings.HasPrefix(fnName, "allof") || strings.HasSuffix(fnName, "allof")
}
type funcArgs struct {
q *pb.Query
gid uint32
srcFn *functionContext
out *pb.Result
}
// The function tells us whether we want to fetch value posting lists or uid posting lists.
func (srcFn *functionContext) needsValuePostings(typ types.TypeID) (bool, error) {
switch srcFn.fnType {
case aggregatorFn, passwordFn:
return true, nil
case compareAttrFn:
if len(srcFn.tokens) > 0 {
return false, nil
}
return true, nil
case geoFn, regexFn, fullTextSearchFn, standardFn, hasFn, customIndexFn, matchFn:
// All of these require an index, hence would require fetching uid postings.
return false, nil
case uidInFn, compareScalarFn:
// Operate on uid postings
return false, nil
case notAFunction:
return typ.IsScalar(), nil
}
return false, errors.Errorf("Unhandled case in fetchValuePostings for fn: %s", srcFn.fname)
}
// Handles fetching of value posting lists and filtering of uids based on that.
func (qs *queryState) handleValuePostings(ctx context.Context, args funcArgs) error {
srcFn := args.srcFn
q := args.q
span := otrace.FromContext(ctx)
stop := x.SpanTimer(span, "handleValuePostings")
defer stop()
if span != nil {
span.Annotatef(nil, "Number of uids: %d. args.srcFn: %+v", srcFn.n, args.srcFn)
}
switch srcFn.fnType {
case notAFunction, aggregatorFn, passwordFn, compareAttrFn:
default:
return errors.Errorf("Unhandled function in handleValuePostings: %s", srcFn.fname)
}
if srcFn.atype == types.PasswordID && srcFn.fnType != passwordFn {
// Silently skip if the user is trying to fetch an attribute of type password.
return nil
}
if srcFn.fnType == passwordFn && srcFn.atype != types.PasswordID {
return errors.Errorf("checkpwd fn can only be used on attr: [%s] with schema type "+
"password. Got type: %s", q.Attr, types.TypeID(srcFn.atype).Name())
}
if srcFn.n == 0 {
return nil
}
// This function has small boiletplate as handleUidPostings, around how the code gets
// concurrently executed. I didn't see much value in trying to separate it out, because the core
// logic constitutes most of the code volume here.
numGo, width := x.DivideAndRule(srcFn.n)
x.AssertTrue(width > 0)
span.Annotatef(nil, "Width: %d. NumGo: %d", width, numGo)
errCh := make(chan error, numGo)
outputs := make([]*pb.Result, numGo)
calculate := func(start, end int) error {
x.AssertTrue(start%width == 0)
out := &pb.Result{}
outputs[start/width] = out
for i := start; i < end; i++ {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
key := x.DataKey(q.Attr, q.UidList.Uids[i])
// Get or create the posting list for an entity, attribute combination.
pl, err := qs.cache.Get(key)
if err != nil {
return err
}
vals, fcs, err := retrieveValuesAndFacets(args, pl)
if err == posting.ErrNoValue || len(vals) == 0 {
out.UidMatrix = append(out.UidMatrix, &pb.List{})
out.FacetMatrix = append(out.FacetMatrix, &pb.FacetsList{})
if q.DoCount {
out.Counts = append(out.Counts, 0)
} else {
out.ValueMatrix = append(out.ValueMatrix,
&pb.ValueList{Values: []*pb.TaskValue{}})
if q.ExpandAll {
// To keep the cardinality same as that of ValueMatrix.
out.LangMatrix = append(out.LangMatrix, &pb.LangList{})
}
}
continue
} else if err != nil {
return err
}
if q.ExpandAll {
langTags, err := pl.GetLangTags(args.q.ReadTs)
if err != nil {
return err
}
out.LangMatrix = append(out.LangMatrix, &pb.LangList{Lang: langTags})
}
uidList := new(pb.List)
var vl pb.ValueList
for _, val := range vals {
newValue, err := convertToType(val, srcFn.atype)
if err != nil {
return err
}
// This means we fetched the value directly instead of fetching index key and intersecting.
// Lets compare the value and add filter the uid.
if srcFn.fnType == compareAttrFn {
// Lets convert the val to its type.
if val, err = types.Convert(val, srcFn.atype); err != nil {
return err
}
if types.CompareVals(srcFn.fname, val, srcFn.ineqValue) {
uidList.Uids = append(uidList.Uids, q.UidList.Uids[i])
break
}
} else {
vl.Values = append(vl.Values, newValue)
}
}
out.ValueMatrix = append(out.ValueMatrix, &vl)
// Add facets to result.
out.FacetMatrix = append(out.FacetMatrix,
&pb.FacetsList{FacetsList: []*pb.Facets{{Facets: fcs}}})
switch {
case q.DoCount:
len := pl.Length(args.q.ReadTs, 0)
if len == -1 {
return posting.ErrTsTooOld
}
out.Counts = append(out.Counts, uint32(len))
// Add an empty UID list to make later processing consistent
out.UidMatrix = append(out.UidMatrix, &pb.List{})
case srcFn.fnType == aggregatorFn:
// Add an empty UID list to make later processing consistent
out.UidMatrix = append(out.UidMatrix, &pb.List{})
case srcFn.fnType == passwordFn:
lastPos := len(out.ValueMatrix) - 1
if len(out.ValueMatrix[lastPos].Values) == 0 {
continue
}
newValue := out.ValueMatrix[lastPos].Values[0]
if len(newValue.Val) == 0 {
out.ValueMatrix[lastPos].Values[0] = ctask.FalseVal
}
pwd := q.SrcFunc.Args[0]
err = types.VerifyPassword(pwd, string(newValue.Val))
if err != nil {
out.ValueMatrix[lastPos].Values[0] = ctask.FalseVal
} else {
out.ValueMatrix[lastPos].Values[0] = ctask.TrueVal
}
// Add an empty UID list to make later processing consistent
out.UidMatrix = append(out.UidMatrix, &pb.List{})
default:
out.UidMatrix = append(out.UidMatrix, uidList)
}
}
return nil
} // End of calculate function.
for i := 0; i < numGo; i++ {
start := i * width
end := start + width
if end > srcFn.n {
end = srcFn.n
}
go func(start, end int) {
errCh <- calculate(start, end)
}(start, end)
}
for i := 0; i < numGo; i++ {
if err := <-errCh; err != nil {
return err
}
}
// All goroutines are done. Now attach their results.
out := args.out
for _, chunk := range outputs {
out.UidMatrix = append(out.UidMatrix, chunk.UidMatrix...)
out.Counts = append(out.Counts, chunk.Counts...)
out.ValueMatrix = append(out.ValueMatrix, chunk.ValueMatrix...)
out.FacetMatrix = append(out.FacetMatrix, chunk.FacetMatrix...)
out.LangMatrix = append(out.LangMatrix, chunk.LangMatrix...)
}
return nil
}
func retrieveValuesAndFacets(args funcArgs, pl *posting.List) ([]types.Val, []*api.Facet, error) {
q := args.q
listType := schema.State().IsList(q.Attr)
var err error
var vals []types.Val
var fcs []*api.Facet
// No facet filtering on values.
if q.FacetsFilter == nil {
// Retrieve values.
if q.ExpandAll {
vals, err = pl.AllValues(args.q.ReadTs)
} else if listType && len(q.Langs) == 0 {
vals, err = pl.AllUntaggedValues(args.q.ReadTs)
} else {
var val types.Val
val, err = pl.ValueFor(args.q.ReadTs, q.Langs)
vals = append(vals, val)
}
if err != nil {
return nil, nil, err
}
// Retrieve facets.
if q.FacetParam != nil {
fcs, _ = pl.Facets(args.q.ReadTs, q.FacetParam, q.Langs)
}
return vals, fcs, nil
}
// Filter values by facets.
facetsTree, err := preprocessFilter(q.FacetsFilter)
if err != nil {
return nil, nil, err
}
err = pl.Iterate(q.ReadTs, 0, func(p *pb.Posting) error {
pick, err := applyFacetsTree(p.Facets, facetsTree)
if err != nil {
return err
}
if pick {
vals = append(vals, types.Val{
Tid: types.TypeID(p.ValType),
Value: p.Value,
})
if q.FacetParam != nil {
fcs = append(fcs, facets.CopyFacets(p.Facets, q.FacetParam)...)
}
}
return nil // continue iteration.
})
if err != nil {
return nil, nil, err
}
return vals, fcs, nil
}
// This function handles operations on uid posting lists. Index keys, reverse keys and some data
// keys store uid posting lists.
func (qs *queryState) handleUidPostings(
ctx context.Context, args funcArgs, opts posting.ListOptions) error {
srcFn := args.srcFn
q := args.q
facetsTree, err := preprocessFilter(q.FacetsFilter)
if err != nil {
return err
}
span := otrace.FromContext(ctx)
stop := x.SpanTimer(span, "handleUidPostings")
defer stop()
if span != nil {
span.Annotatef(nil, "Number of uids: %d. args.srcFn: %+v", srcFn.n, args.srcFn)
}
if srcFn.n == 0 {
return nil
}
// Divide the task into many goroutines.
numGo, width := x.DivideAndRule(srcFn.n)
x.AssertTrue(width > 0)
span.Annotatef(nil, "Width: %d. NumGo: %d", width, numGo)
errCh := make(chan error, numGo)
outputs := make([]*pb.Result, numGo)
calculate := func(start, end int) error {
x.AssertTrue(start%width == 0)
out := &pb.Result{}
outputs[start/width] = out
for i := start; i < end; i++ {
if i%100 == 0 {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
}
var key []byte
switch srcFn.fnType {
case notAFunction, compareScalarFn, hasFn, uidInFn:
if q.Reverse {
key = x.ReverseKey(q.Attr, q.UidList.Uids[i])
} else {
key = x.DataKey(q.Attr, q.UidList.Uids[i])
}
case geoFn, regexFn, fullTextSearchFn, standardFn, customIndexFn, matchFn,
compareAttrFn:
key = x.IndexKey(q.Attr, srcFn.tokens[i])
default:
return errors.Errorf("Unhandled function in handleUidPostings: %s", srcFn.fname)
}
// Get or create the posting list for an entity, attribute combination.
pl, err := qs.cache.Get(key)
if err != nil {
return err
}
switch {
case q.DoCount:
if i == 0 {
span.Annotate(nil, "DoCount")
}
len := pl.Length(args.q.ReadTs, 0)
if len == -1 {
return posting.ErrTsTooOld
}
out.Counts = append(out.Counts, uint32(len))
// Add an empty UID list to make later processing consistent
out.UidMatrix = append(out.UidMatrix, &pb.List{})
case srcFn.fnType == compareScalarFn:
if i == 0 {
span.Annotate(nil, "CompareScalarFn")
}
len := pl.Length(args.q.ReadTs, 0)
if len == -1 {
return posting.ErrTsTooOld
}
count := int64(len)
if evalCompare(srcFn.fname, count, srcFn.threshold) {
tlist := &pb.List{Uids: []uint64{q.UidList.Uids[i]}}
out.UidMatrix = append(out.UidMatrix, tlist)
}
case srcFn.fnType == hasFn:
if i == 0 {
span.Annotate(nil, "HasFn")
}
empty, err := pl.IsEmpty(args.q.ReadTs, 0)
if err != nil {
return err
}
if !empty {
tlist := &pb.List{Uids: []uint64{q.UidList.Uids[i]}}
out.UidMatrix = append(out.UidMatrix, tlist)
}
case srcFn.fnType == uidInFn:
if i == 0 {
span.Annotate(nil, "UidInFn")
}
reqList := &pb.List{Uids: []uint64{srcFn.uidPresent}}
topts := posting.ListOptions{
ReadTs: args.q.ReadTs,
AfterUid: 0,
Intersect: reqList,
}
plist, err := pl.Uids(topts)
if err != nil {
return err
}
if len(plist.Uids) > 0 {
tlist := &pb.List{Uids: []uint64{q.UidList.Uids[i]}}
out.UidMatrix = append(out.UidMatrix, tlist)
}
case q.FacetParam != nil || facetsTree != nil:
if i == 0 {
span.Annotate(nil, "default with facets")
}
uidList := &pb.List{
Uids: make([]uint64, 0, pl.ApproxLen()),
}
var fcsList []*pb.Facets
err = pl.Postings(opts, func(p *pb.Posting) error {
pick, err := applyFacetsTree(p.Facets, facetsTree)
if err != nil {
return err
}
if pick {
// TODO: This way of picking Uids differs from how
// pl.Uids works. So, have a look to see if we're
// catching all the edge cases here.
uidList.Uids = append(uidList.Uids, p.Uid)
if q.FacetParam != nil {
fcsList = append(fcsList, &pb.Facets{
Facets: facets.CopyFacets(p.Facets, q.FacetParam),
})
}
}
return nil // continue iteration.
})
if err != nil {
return err
}
out.UidMatrix = append(out.UidMatrix, uidList)
if q.FacetParam != nil {
out.FacetMatrix = append(out.FacetMatrix, &pb.FacetsList{FacetsList: fcsList})
}
default:
if i == 0 {
span.Annotate(nil, "default no facets")
}
uidList, err := pl.Uids(opts)
if err != nil {
return err
}
out.UidMatrix = append(out.UidMatrix, uidList)
}
}
return nil
} // End of calculate function.
for i := 0; i < numGo; i++ {
start := i * width
end := start + width
if end > srcFn.n {
end = srcFn.n
}
go func(start, end int) {
errCh <- calculate(start, end)
}(start, end)
}
for i := 0; i < numGo; i++ {
if err := <-errCh; err != nil {
return err
}
}
// All goroutines are done. Now attach their results.
out := args.out
for _, chunk := range outputs {
out.FacetMatrix = append(out.FacetMatrix, chunk.FacetMatrix...)
out.Counts = append(out.Counts, chunk.Counts...)
out.UidMatrix = append(out.UidMatrix, chunk.UidMatrix...)
}
var total int
for _, list := range out.UidMatrix {
total += len(list.Uids)
}
span.Annotatef(nil, "Total number of elements in matrix: %d", total)
return nil
}
const (
// UseTxnCache indicates the transaction cache should be used.
UseTxnCache = iota
// NoCache indicates no caches should be used.
NoCache
)
// processTask processes the query, accumulates and returns the result.
func processTask(ctx context.Context, q *pb.Query, gid uint32) (*pb.Result, error) {
ctx, span := otrace.StartSpan(ctx, "processTask."+q.Attr)
defer span.End()
stop := x.SpanTimer(span, "processTask"+q.Attr)
defer stop()
span.Annotatef(nil, "Waiting for startTs: %d", q.ReadTs)
if err := posting.Oracle().WaitForTs(ctx, q.ReadTs); err != nil {
return &pb.Result{}, err
}
if span != nil {
maxAssigned := posting.Oracle().MaxAssigned()
span.Annotatef(nil, "Done waiting for maxAssigned. Attr: %q ReadTs: %d Max: %d",
q.Attr, q.ReadTs, maxAssigned)
}
if err := groups().ChecksumsMatch(ctx); err != nil {
return &pb.Result{}, err
}
span.Annotatef(nil, "Done waiting for checksum match")
// If a group stops serving tablet and it gets partitioned away from group
// zero, then it wouldn't know that this group is no longer serving this
// predicate. There's no issue if a we are serving a particular tablet and
// we get partitioned away from group zero as long as it's not removed.
// BelongsToReadOnly is called instead of BelongsTo to prevent this alpha
// from requesting to serve this tablet.
if gid, err := groups().BelongsToReadOnly(q.Attr); err != nil {
return &pb.Result{}, err
} else if gid == 0 {
return &pb.Result{}, errNonExistentTablet
} else if gid != groups().groupId() {
return &pb.Result{}, errUnservedTablet
}
var qs queryState
if q.Cache == UseTxnCache {
qs.cache = posting.Oracle().CacheAt(q.ReadTs)
}
// For now, remove the query level cache. It is causing contention for queries with high
// fan-out.
out, err := qs.helpProcessTask(ctx, q, gid)
if err != nil {
return &pb.Result{}, err
}
return out, nil
}
type queryState struct {
cache *posting.LocalCache
}
func (qs *queryState) helpProcessTask(ctx context.Context, q *pb.Query, gid uint32) (
*pb.Result, error) {
span := otrace.FromContext(ctx)
out := new(pb.Result)
attr := q.Attr
srcFn, err := parseSrcFn(q)
if err != nil {
return nil, err
}
if q.Reverse && !schema.State().IsReversed(attr) {
return nil, errors.Errorf("Predicate %s doesn't have reverse edge", attr)
}
if needsIndex(srcFn.fnType) && !schema.State().IsIndexed(q.Attr) {
return nil, errors.Errorf("Predicate %s is not indexed", q.Attr)
}
if len(q.Langs) > 0 && !schema.State().HasLang(attr) {
return nil, errors.Errorf("Language tags can only be used with predicates of string type"+
" having @lang directive in schema. Got: [%v]", attr)
}
typ, err := schema.State().TypeOf(attr)
if err != nil {
// All schema checks are done before this, this type is only used to
// convert it to schema type before returning.
// Schema type won't be present only if there is no data for that predicate
// or if we load through bulk loader.
typ = types.DefaultID
}
out.List = schema.State().IsList(attr)
srcFn.atype = typ
// Reverse attributes might have more than 1 results even if the original attribute
// is not a list.
if q.Reverse {
out.List = true
}
opts := posting.ListOptions{
ReadTs: q.ReadTs,
AfterUid: q.AfterUid,
}
// If we have srcFunc and Uids, it means its a filter. So we intersect.
if srcFn.fnType != notAFunction && q.UidList != nil && len(q.UidList.Uids) > 0 {
opts.Intersect = q.UidList
}
args := funcArgs{q, gid, srcFn, out}
needsValPostings, err := srcFn.needsValuePostings(typ)
if err != nil {
return nil, err
}
if needsValPostings {
span.Annotate(nil, "handleValuePostings")
if err = qs.handleValuePostings(ctx, args); err != nil {
return nil, err
}
} else {
span.Annotate(nil, "handleUidPostings")
if err = qs.handleUidPostings(ctx, args, opts); err != nil {
return nil, err
}
}
if srcFn.fnType == hasFn && srcFn.isFuncAtRoot {
span.Annotate(nil, "handleHasFunction")
if err := qs.handleHasFunction(ctx, q, out); err != nil {
return nil, err
}
}
if srcFn.fnType == compareScalarFn && srcFn.isFuncAtRoot {
span.Annotate(nil, "handleCompareScalarFunction")
if err := qs.handleCompareScalarFunction(funcArgs{q, gid, srcFn, out}); err != nil {
return nil, err
}
}
if srcFn.fnType == regexFn {
span.Annotate(nil, "handleRegexFunction")
if err := qs.handleRegexFunction(ctx, funcArgs{q, gid, srcFn, out}); err != nil {
return nil, err
}
}
if srcFn.fnType == matchFn {
span.Annotate(nil, "handleMatchFunction")
if err := qs.handleMatchFunction(ctx, funcArgs{q, gid, srcFn, out}); err != nil {
return nil, err
}
}
// We fetch the actual value for the uids, compare them to the value in the
// request and filter the uids only if the tokenizer IsLossy.
if srcFn.fnType == compareAttrFn && len(srcFn.tokens) > 0 {
span.Annotate(nil, "handleCompareFunction")
if err := qs.handleCompareFunction(ctx, funcArgs{q, gid, srcFn, out}); err != nil {
return nil, err
}
}
// If geo filter, do value check for correctness.
if srcFn.geoQuery != nil {
span.Annotate(nil, "handleGeoFunction")
if err := qs.filterGeoFunction(ctx, funcArgs{q, gid, srcFn, out}); err != nil {
return nil, err
}
}
// For string matching functions, check the language.
if needsStringFiltering(srcFn, q.Langs, attr) {
span.Annotate(nil, "filterStringFunction")
if err := qs.filterStringFunction(funcArgs{q, gid, srcFn, out}); err != nil {
return nil, err
}
}
out.IntersectDest = srcFn.intersectDest
return out, nil
}
func needsStringFiltering(srcFn *functionContext, langs []string, attr string) bool {
if !srcFn.isStringFn {
return false
}
// If a predicate doesn't have @lang directive in schema, we don't need to do any string
// filtering.
if !schema.State().HasLang(attr) {
return false
}
return langForFunc(langs) != "." &&
(srcFn.fnType == standardFn || srcFn.fnType == hasFn ||
srcFn.fnType == fullTextSearchFn || srcFn.fnType == compareAttrFn ||
srcFn.fnType == customIndexFn)
}
func (qs *queryState) handleCompareScalarFunction(arg funcArgs) error {
attr := arg.q.Attr
if ok := schema.State().HasCount(attr); !ok {
return errors.Errorf("Need @count directive in schema for attr: %s for fn: %s at root",
attr, arg.srcFn.fname)
}
count := arg.srcFn.threshold
cp := countParams{
fn: arg.srcFn.fname,
count: count,
attr: attr,
gid: arg.gid,
readTs: arg.q.ReadTs,
reverse: arg.q.Reverse,
}
return qs.evaluate(cp, arg.out)
}
func (qs *queryState) handleRegexFunction(ctx context.Context, arg funcArgs) error {
span := otrace.FromContext(ctx)
stop := x.SpanTimer(span, "handleRegexFunction")
defer stop()
if span != nil {
span.Annotatef(nil, "Number of uids: %d. args.srcFn: %+v", arg.srcFn.n, arg.srcFn)
}
attr := arg.q.Attr
typ, err := schema.State().TypeOf(attr)
span.Annotatef(nil, "Attr: %s. Type: %s", attr, typ.Name())
if err != nil || !typ.IsScalar() {
return errors.Errorf("Attribute not scalar: %s %v", attr, typ)
}
if typ != types.StringID {
return errors.Errorf("Got non-string type. Regex match is allowed only on string type.")
}
useIndex := schema.State().HasTokenizer(tok.IdentTrigram, attr)
span.Annotatef(nil, "Trigram index found: %t, func at root: %t",
useIndex, arg.srcFn.isFuncAtRoot)
query := cindex.RegexpQuery(arg.srcFn.regex.Syntax)
empty := pb.List{}
var uids *pb.List
// Here we determine the list of uids to match.
switch {
// If this is a filter eval, use the given uid list (good)
case arg.q.UidList != nil: