forked from couchbase/cbft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pindex_bleve.go
2477 lines (2100 loc) · 67.6 KB
/
pindex_bleve.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 (c) 2014 Couchbase, Inc.
// 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 cbft
import (
"container/heap"
"container/list"
"context"
"crypto/tls"
"crypto/x509"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"reflect"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/mux"
"github.com/rcrowley/go-metrics"
"github.com/blevesearch/bleve"
bleveMappingUI "github.com/blevesearch/bleve-mapping-ui"
_ "github.com/blevesearch/bleve/config"
bleveHttp "github.com/blevesearch/bleve/http"
"github.com/blevesearch/bleve/index/scorch"
"github.com/blevesearch/bleve/index/upsidedown"
"github.com/blevesearch/bleve/mapping"
bleveRegistry "github.com/blevesearch/bleve/registry"
log "github.com/couchbase/clog"
"github.com/couchbase/cbgt"
"github.com/couchbase/cbgt/rest"
"github.com/couchbase/moss"
"golang.org/x/net/http2"
)
var BatchBytesAdded uint64
var BatchBytesRemoved uint64
var TotBatchesFlushedOnMaxOps uint64
var TotBatchesFlushedOnTimer uint64
var featureIndexType = "indexType"
var FeatureScorchIndex = featureIndexType + ":" + scorch.Name
var FeatureUpsidedownIndex = featureIndexType + ":" + upsidedown.Name
var BleveMaxOpsPerBatch = 200 // Unlimited when <= 0.
var BleveBatchFlushDuration = time.Duration(100 * time.Millisecond)
var BlevePIndexAllowMoss = false // Unit tests prefer no moss.
var BleveKVStoreMetricsAllow = false // Use metrics wrapper KVStore by default.
// represents the number of async batch workers per pindex
var asyncBatchWorkerCount = 4 // need to make it configurable,
var TotBleveDestOpened uint64
var TotBleveDestClosed uint64
// BleveParams represents the bleve index params. See also
// cbgt.IndexDef.Params. A JSON'ified BleveParams looks like...
// {
// "mapping": {
// // See bleve.mapping.IndexMapping.
// },
// "store": {
// // See BleveParamsStore.
// },
// "doc_config": {
// // See BleveDocumentConfig.
// }
// }
type BleveParams struct {
Mapping mapping.IndexMapping `json:"mapping"`
Store map[string]interface{} `json:"store"`
DocConfig BleveDocumentConfig `json:"doc_config"`
}
// BleveParamsStore represents some of the publically available
// options in the "store" part of a bleve index params. See also the
// BleveParams.Store field.
type BleveParamsStore struct {
// The indexType defaults to bleve.Config.DefaultIndexType.
// Example: "upside_down". See bleve.index.upsidedown.Name and
// bleve.registry.RegisterIndexType().
IndexType string `json:"indexType"`
// The kvStoreName defaults to bleve.Config.DefaultKVStore.
// See also bleve.registry.RegisterKVStore().
KvStoreName string `json:"kvStoreName"`
// The kvStoreMetricsAllow flag defaults to
// cbft.BleveKVStoreMetricsAllow. When true, an
// interposing wrapper that captures additional metrics will be
// initialized as part of a bleve index's KVStore.
//
// Note: the interposing metrics wrapper might introduce
// additional performance costs.
KvStoreMetricsAllow bool `json:"kvStoreMetricsAllow"`
// The kvStoreMossAllow defaults to true.
//
// The moss cache will be used for a bleve index's KVStore when
// both this kvStoreMossAllow flag and the
// cbft.BlevePIndexAllowMoss global flag are true.
//
// A user can also explicitly specify a kvStoreName of "moss" to
// force usage of the moss cache.
KvStoreMossAllow bool `json:"kvStoreMossAllow"`
// The mossCollectionOptions allows users to specify moss cache
// collection options, with defaults coming from
// moss.DefaultCollectionOptions.
//
// It only applies when a moss cache is in use for an index (see
// kvStoreMossAllow).
MossCollectionOptions moss.CollectionOptions `json:"mossCollectionOptions"`
// The mossLowerLevelStoreName specifies which lower-level
// bleve.index.store.KVStore to use underneath a moss cache.
// See also bleve.registry.RegisterKVStore().
//
// It only applies when a moss cache is in use for an index (see
// kvStoreMossAllow).
//
// As a special case, when moss cache is allowed, and the
// kvStoreName is not "moss", and the mossLowerLevelStoreName is
// unspecified or "", then the system will automatically
// reconfigure as a convenience so that the
// mossLowerLevelStoreName becomes the kvStoreName, and the
// kvStoreName becomes "moss", hence injecting moss cache into
// usage for an index.
//
// In another case, when the kvStoreName is "moss" and the
// mossLowerLevelStoreName is "" (empty string), that means the
// moss cache will run in memory-only mode with no lower-level
// storage.
MossLowerLevelStoreName string `json:"mossLowerLevelStoreName"`
// The mossLowerLevelStoreConfig can be used to provide advanced
// options to the lower-level KVStore that's used under a moss
// cache.
//
// NOTE: when the mossLowerLevelStoreName is "mossStore", the
// mossLowerLevelStoreConfig is not used; instead, please use
// mossStoreOptions.
MossLowerLevelStoreConfig map[string]interface{} `json:"mossLowerLevelStoreConfig"`
// The mossStoreOptions allows the user to specify advanced
// configuration options when moss cache is in use and when the
// mossLowerLevelStoreName is "mossStore",
MossStoreOptions moss.StoreOptions `json:"mossStoreOptions"`
}
func NewBleveParams() *BleveParams {
rv := &BleveParams{
Mapping: bleve.NewIndexMapping(),
Store: map[string]interface{}{
"indexType": bleve.Config.DefaultIndexType,
"kvStoreName": bleve.Config.DefaultKVStore,
},
DocConfig: BleveDocumentConfig{
Mode: "type_field",
TypeField: "type",
},
}
return rv
}
type BleveDest struct {
path string
bleveDocConfig BleveDocumentConfig
// Invoked when mgr should restart this BleveDest, like on rollback.
restart func()
m sync.Mutex // Protects the fields that follow.
bindex bleve.Index
partitions map[string]*BleveDestPartition
rev uint64 // Incremented whenever bindex changes.
stats cbgt.PIndexStoreStats
batchReqChs []chan *batchRequest
stopCh chan struct{}
}
// Used to track state for a single partition.
type BleveDestPartition struct {
bdest *BleveDest
bindex bleve.Index
partition string
partitionBytes []byte
partitionOpaque []byte // Key used to implement OpaqueSet/OpaqueGet().
m sync.Mutex // Protects the fields that follow.
seqMax uint64 // Max seq # we've seen for this partition.
seqMaxBatch uint64 // Max seq # that got through batch apply/commit.
seqSnapEnd uint64 // To track snapshot end seq # for this partition.
batch *bleve.Batch // Batch applied when we hit seqSnapEnd.
lastOpaque []byte // Cache most recent value for OpaqueSet()/OpaqueGet().
lastUUID string // Cache most recent partition UUID from lastOpaque.
cwrQueue cbgt.CwrQueue
lastAsyncBatchErr error // for returning async batch err on next call
}
type batchRequest struct {
bdp *BleveDestPartition
bindex bleve.Index
batch *bleve.Batch
}
func NewBleveDest(path string, bindex bleve.Index,
restart func(), bleveDocConfig BleveDocumentConfig) *BleveDest {
bleveDest := &BleveDest{
path: path,
bleveDocConfig: bleveDocConfig,
restart: restart,
bindex: bindex,
partitions: make(map[string]*BleveDestPartition),
stats: cbgt.PIndexStoreStats{
TimerBatchStore: metrics.NewTimer(),
Errors: list.New(),
},
stopCh: make(chan struct{}),
}
bleveDest.batchReqChs = make([]chan *batchRequest, asyncBatchWorkerCount)
for i := 0; i < asyncBatchWorkerCount; i++ {
bleveDest.batchReqChs[i] = make(chan *batchRequest, 1)
go runBatchWorker(bleveDest.batchReqChs[i], bleveDest.stopCh, bindex)
log.Printf("pindex_bleve: started runBatchWorker: %d for pindex: %s", i, bindex.Name())
}
atomic.AddUint64(&TotBleveDestOpened, 1)
return bleveDest
}
// ---------------------------------------------------------
var CurrentNodeDefsFetcher *NodeDefsFetcher
type NodeDefsFetcher struct {
mgr *cbgt.Manager
}
func (ndf *NodeDefsFetcher) SetManager(mgr *cbgt.Manager) {
ndf.mgr = mgr
}
func (ndf *NodeDefsFetcher) Get() (*cbgt.NodeDefs, error) {
if ndf.mgr != nil {
return ndf.mgr.GetNodeDefs(cbgt.NODE_DEFS_WANTED, true)
}
return nil, fmt.Errorf("NodeDefsFetcher Get(): mgr is nil!")
}
// ---------------------------------------------------------
const bleveQueryHelp = `<a href="https://developer.couchbase.com/fts/5.0/query-string-query"
target="_blank">
full text query syntax help
</a>`
func init() {
cbgt.RegisterPIndexImplType("fulltext-index", &cbgt.PIndexImplType{
PrepareParams: PrepareBleveIndexParams,
Validate: ValidateBleve,
New: NewBlevePIndexImpl,
Open: OpenBlevePIndexImpl,
OpenUsing: OpenBlevePIndexImplUsing,
Count: CountBleve,
Query: QueryBleve,
Description: "general/fulltext-index " +
" - a full text index powered by the bleve engine",
StartSample: NewBleveParams(),
QuerySamples: BleveQuerySamples,
QueryHelp: bleveQueryHelp,
InitRouter: BleveInitRouter,
DiagHandlers: []cbgt.DiagHandler{
{Name: "/api/pindex-bleve", Handler: bleveHttp.NewListIndexesHandler(),
HandlerFunc: nil},
},
MetaExtra: BleveMetaExtra,
UI: map[string]string{
"controllerInitName": "blevePIndexInitController",
"controllerDoneName": "blevePIndexDoneController",
},
AnalyzeIndexDefUpdates: RestartOnIndexDefChanges,
})
}
func PrepareBleveIndexParams(indexParams string) (string, error) {
bp := NewBleveParams()
if len(indexParams) > 0 {
b, err := bleveMappingUI.CleanseJSON([]byte(indexParams))
if err != nil {
return "", fmt.Errorf("bleve: PrepareParams CleanseJSON,"+
" err: %v", err)
}
err = json.Unmarshal(b, bp)
if err != nil {
if typeErr, ok := err.(*json.UnmarshalTypeError); ok {
if typeErr.Type.String() == "map[string]json.RawMessage" {
return "", fmt.Errorf("bleve: PrepareParams,"+
" JSON parse was expecting a string key/field-name"+
" but instead saw a %s", typeErr.Value)
}
}
return "", fmt.Errorf("bleve: PrepareParams, err: %v", err)
}
}
updatedParams, err := json.Marshal(bp)
if err != nil {
return "", fmt.Errorf("bleve: PrepareParams Marshal,"+
" err: %v", err)
}
return string(updatedParams), nil
}
func ValidateBleve(indexType, indexName, indexParams string) error {
if len(indexParams) <= 0 {
return nil
}
validateBleveIndexType := func(content interface{}) error {
if CurrentNodeDefsFetcher == nil {
return nil
}
nodeDefs, err := CurrentNodeDefsFetcher.Get()
if err != nil {
return fmt.Errorf("bleve: validation failed: err: %v", err)
}
indexType := ""
if entries, ok := content.(map[string]interface{}); ok {
indexType = entries["indexType"].(string)
}
if indexType != upsidedown.Name {
// Validate any indexType except upsidedown (to support pre-5.5)
if !cbgt.IsFeatureSupportedByCluster(featureIndexType+":"+indexType, nodeDefs) {
return fmt.Errorf("bleve: index validation failed:"+
" indexType: %v not supported on all nodes in"+
" cluster", indexType)
}
}
return nil
}
// Validate token filters in indexParams
validateIndexParams := func() error {
var iParams map[string]interface{}
err := json.Unmarshal([]byte(indexParams), &iParams)
if err != nil {
// Ignore the JSON unmarshalling error, if in the case
// indexParams isn't JSON.
return nil
}
store, found := iParams["store"]
if found {
err = validateBleveIndexType(store)
if err != nil {
return err
}
}
mapping, found := iParams["mapping"]
if !found {
// Entry for mapping not found
return nil
}
analysis, found := mapping.(map[string]interface{})["analysis"]
if !found {
// No sub entry with the name analysis within mapping
return nil
}
tokenfilters, found := analysis.(map[string]interface{})["token_filters"]
if !found {
// No entry for token_filters within mapping/analysis
return nil
}
for _, val := range tokenfilters.(map[string]interface{}) {
param := val.(map[string]interface{})
switch param["type"] {
case "edge_ngram", "length", "ngram", "shingle":
if param["min"].(float64) > param["max"].(float64) {
return fmt.Errorf("bleve: token_filter validation failed"+
" for %v => min(%v) > max(%v)", param["type"],
param["min"], param["max"])
}
case "truncate_token":
if param["length"].(float64) < 0 {
return fmt.Errorf("bleve: token_filter validation failed"+
" for %v => length(%v) < 0", param["type"], param["length"])
}
default:
break
}
}
return nil
}
err := validateIndexParams()
if err != nil {
return err
}
b, err := bleveMappingUI.CleanseJSON([]byte(indexParams))
if err != nil {
return fmt.Errorf("bleve: validate CleanseJSON,"+
" err: %v", err)
}
bp := NewBleveParams()
err = json.Unmarshal(b, bp)
if err != nil {
if typeErr, ok := err.(*json.UnmarshalTypeError); ok {
if typeErr.Type.String() == "map[string]json.RawMessage" {
return fmt.Errorf("bleve: validate params,"+
" JSON parse was expecting a string key/field-name"+
" but instead saw a %s", typeErr.Value)
}
}
return fmt.Errorf("bleve: validate params, err: %v", err)
}
err = bp.Mapping.Validate()
if err != nil {
return fmt.Errorf("bleve: validate mapping, err: %v", err)
}
return nil
}
func NewBlevePIndexImpl(indexType, indexParams, path string,
restart func()) (cbgt.PIndexImpl, cbgt.Dest, error) {
bleveParams := NewBleveParams()
if len(indexParams) > 0 {
buf, err := bleveMappingUI.CleanseJSON([]byte(indexParams))
if err != nil {
return nil, nil, fmt.Errorf("bleve: cleanse params, err: %v", err)
}
err = json.Unmarshal(buf, bleveParams)
if err != nil {
return nil, nil, fmt.Errorf("bleve: parse params, err: %v", err)
}
}
kvConfig, bleveIndexType, kvStoreName := bleveRuntimeConfigMap(bleveParams)
bindex, err := bleve.NewUsing(path, bleveParams.Mapping,
bleveIndexType, kvStoreName, kvConfig)
if err != nil {
return nil, nil, fmt.Errorf("bleve: new index, path: %s,"+
" kvStoreName: %s, kvConfig: %#v, err: %s",
path, kvStoreName, kvConfig, err)
}
pathMeta := path + string(os.PathSeparator) + "PINDEX_BLEVE_META"
err = ioutil.WriteFile(pathMeta, []byte(indexParams), 0600)
if err != nil {
return nil, nil, err
}
return bindex, &cbgt.DestForwarder{
DestProvider: NewBleveDest(path, bindex, restart, bleveParams.DocConfig),
}, nil
}
func OpenBlevePIndexImpl(indexType, path string,
restart func()) (cbgt.PIndexImpl, cbgt.Dest, error) {
return OpenBlevePIndexImplUsing(indexType, path, "", restart)
}
func bleveRuntimeConfigMap(bleveParams *BleveParams) (map[string]interface{},
string, string) {
// check the indexType
bleveIndexType, ok := bleveParams.Store["indexType"].(string)
if !ok || bleveIndexType == "" {
bleveIndexType = bleve.Config.DefaultIndexType
}
kvConfig := map[string]interface{}{
"create_if_missing": true,
"error_if_exists": true,
"unsafe_batch": true,
"eventCallbackName": "scorchEventCallbacks",
"asyncErrorCallbackName": "scorchAsyncErrorCallbacks",
"numSnapshotsToKeep": 3,
}
for k, v := range bleveParams.Store {
kvConfig[k] = v
}
kvStoreName := "scorch"
if bleveIndexType != "scorch" {
kvStoreName, ok = bleveParams.Store["kvStoreName"].(string)
if !ok || kvStoreName == "" {
if bleveIndexType == upsidedown.Name {
kvStoreName = "mossStore"
} else {
kvStoreName = bleve.Config.DefaultKVStore
}
}
// Use the "moss" wrapper KVStore if it's allowed, available
// and also not already configured.
kvStoreMossAllow := true
ksmv, exists := kvConfig["kvStoreMossAllow"]
if exists {
var v bool
v, ok = ksmv.(bool)
if ok {
kvStoreMossAllow = v
}
}
if kvStoreMossAllow && BlevePIndexAllowMoss {
_, exists = kvConfig["mossLowerLevelStoreName"]
if !exists &&
kvStoreName != "moss" &&
bleveRegistry.KVStoreConstructorByName("moss") != nil {
kvConfig["mossLowerLevelStoreName"] = kvStoreName
kvStoreName = "moss"
}
_, exists = kvConfig["mossCollectionOptionsName"]
if !exists {
kvConfig["mossCollectionOptionsName"] = "fts"
}
}
// Use the "metrics" wrapper KVStore if it's allowed, available
// and also not already configured.
kvStoreMetricsAllow := BleveKVStoreMetricsAllow
ksmv, exists = kvConfig["kvStoreMetricsAllow"]
if exists {
var v bool
v, ok = ksmv.(bool)
if ok {
kvStoreMetricsAllow = v
}
}
if kvStoreMetricsAllow {
_, exists := kvConfig["kvStoreName_actual"]
if !exists &&
kvStoreName != "metrics" &&
bleveRegistry.KVStoreConstructorByName("metrics") != nil {
kvConfig["kvStoreName_actual"] = kvStoreName
kvStoreName = "metrics"
}
}
} else {
// dummy entry for bleve in case of scorch indextype
kvConfig["kvStoreName"] = "scorch"
}
return kvConfig, bleveIndexType, kvStoreName
}
func OpenBlevePIndexImplUsing(indexType, path, indexParams string,
restart func()) (cbgt.PIndexImpl, cbgt.Dest, error) {
buf := []byte(indexParams)
var err error
if len(buf) == 0 {
buf, err = ioutil.ReadFile(path +
string(os.PathSeparator) + "PINDEX_BLEVE_META")
if err != nil {
return nil, nil, err
}
}
bleveParams := NewBleveParams()
if len(buf) > 0 {
// It is possible that buf is empty when index params aren't set as
// part of the index definition.
buf, err = bleveMappingUI.CleanseJSON(buf)
if err != nil {
return nil, nil, fmt.Errorf("bleve: cleanse params, err: %v", err)
}
err = json.Unmarshal(buf, bleveParams)
if err != nil {
return nil, nil, fmt.Errorf("bleve: parse params: %v", err)
}
}
// Handle the case where indexType wasn't mentioned in
// the index params (only from pre 5.5 nodes)
if !strings.Contains(indexParams, "indexType") {
bleveParams.Store["indexType"] = upsidedown.Name
if !strings.Contains(indexParams, "kvStoreName") {
bleveParams.Store["kvStoreName"] = "mossStore"
}
}
kvConfig, _, _ := bleveRuntimeConfigMap(bleveParams)
// TODO: boltdb sometimes locks on Open(), so need to investigate,
// where perhaps there was a previous missing or race-y Close().
bindex, err := bleve.OpenUsing(path, kvConfig)
if err != nil {
return nil, nil, err
}
return bindex, &cbgt.DestForwarder{
DestProvider: NewBleveDest(path, bindex, restart, bleveParams.DocConfig),
}, nil
}
// ---------------------------------------------------------------
func CountBleve(mgr *cbgt.Manager, indexName, indexUUID string) (
uint64, error) {
alias, _, _, err := bleveIndexAlias(mgr, indexName, indexUUID, false, nil, nil,
false, nil, "")
if err != nil {
if _, ok := err.(*cbgt.ErrorLocalPIndexHealth); !ok {
return 0, fmt.Errorf("bleve: CountBleve indexAlias error,"+
" indexName: %s, indexUUID: %s, err: %v", indexName, indexUUID, err)
}
}
return alias.DocCount()
}
func ValidateConsistencyParams(c *cbgt.ConsistencyParams) error {
switch c.Level {
case "":
return nil
case "at_plus":
return nil
}
return fmt.Errorf("unsupported consistencyLevel: %s", c.Level)
}
// ---------------------------------------------------------
// totQueryRejectOnNotEnoughQuota tracks the number of rejected
// search requests on hitting the memory threshold for query
var totQueryRejectOnNotEnoughQuota uint64
// QueryPIndexes defines the part of the JSON query request that
// allows the client to specify which pindexes the server should
// consider during query processing.
type QueryPIndexes struct {
// An empty or nil PIndexNames means the query should use all
// the pindexes of the index.
PIndexNames []string `json:"pindexNames,omitempty"`
}
func fireQueryEvent(depth int, kind QueryEventKind, dur time.Duration, size uint64) error {
if RegistryQueryEventCallback != nil {
return RegistryQueryEventCallback(depth, QueryEvent{Kind: kind, Duration: dur}, size)
}
return nil
}
func bleveCtxQueryStartCallback(size uint64) error {
return fireQueryEvent(1, EventQueryStart, 0, size)
}
func bleveCtxQueryEndCallback(size uint64) error {
return fireQueryEvent(1, EventQueryEnd, 0, size)
}
func QueryBleve(mgr *cbgt.Manager, indexName, indexUUID string,
req []byte, res io.Writer) error {
// phase 0 - parsing/validating query
// could return err 400
queryCtlParams := cbgt.QueryCtlParams{
Ctl: cbgt.QueryCtl{
Timeout: cbgt.QUERY_CTL_DEFAULT_TIMEOUT_MS,
},
}
err := UnmarshalJSON(req, &queryCtlParams)
if err != nil {
return fmt.Errorf("bleve: QueryBleve"+
" parsing queryCtlParams, err: %v", err)
}
queryPIndexes := QueryPIndexes{}
err = UnmarshalJSON(req, &queryPIndexes)
if err != nil {
return fmt.Errorf("bleve: QueryBleve"+
" parsing queryPIndexes, err: %v", err)
}
searchRequest := &bleve.SearchRequest{}
err = UnmarshalJSON(req, searchRequest)
if err != nil {
return fmt.Errorf("bleve: QueryBleve"+
" parsing searchRequest, err: %v", err)
}
if queryCtlParams.Ctl.Consistency != nil {
err = ValidateConsistencyParams(queryCtlParams.Ctl.Consistency)
if err != nil {
return fmt.Errorf("bleve: QueryBleve"+
" validating consistency, err: %v", err)
}
}
err = searchRequest.Validate()
if err != nil {
return fmt.Errorf("bleve: QueryBleve"+
" validating request, err: %v", err)
}
v, exists := mgr.Options()["bleveMaxResultWindow"]
if exists {
var bleveMaxResultWindow int
bleveMaxResultWindow, err = strconv.Atoi(v)
if err != nil {
return fmt.Errorf("bleve: QueryBleve"+
" atoi: %v, err: %v", v, err)
}
if searchRequest.From+searchRequest.Size > bleveMaxResultWindow {
return fmt.Errorf("bleve: bleveMaxResultWindow exceeded,"+
" from: %d, size: %d, bleveMaxResultWindow: %d",
searchRequest.From, searchRequest.Size, bleveMaxResultWindow)
}
}
// phase 1 - set up timeouts, wait for local consistency reqiurements
// to be satisfied, could return err 412
// create a context with the appropriate timeout
ctx, cancel, cancelCh := setupContextAndCancelCh(queryCtlParams, nil)
// defer a call to cancel, this ensures that goroutine from
// setupContextAndCancelCh always exits
defer cancel()
var onlyPIndexes map[string]bool
if len(queryPIndexes.PIndexNames) > 0 {
onlyPIndexes = cbgt.StringsToMap(queryPIndexes.PIndexNames)
}
alias, remoteClients, numPIndexes, err1 := bleveIndexAlias(mgr, indexName,
indexUUID, true, queryCtlParams.Ctl.Consistency,
cancelCh, true, onlyPIndexes, queryCtlParams.Ctl.PartitionSelection)
if err1 != nil {
if _, ok := err1.(*cbgt.ErrorLocalPIndexHealth); !ok {
return err1
}
}
// estimate memory needed for merging search results from all
// the pindexes
mergeEstimate := uint64(numPIndexes) * bleve.MemoryNeededForSearchResult(searchRequest)
err = fireQueryEvent(0, EventQueryStart, 0, mergeEstimate)
if err != nil {
atomic.AddUint64(&totQueryRejectOnNotEnoughQuota, 1)
return err
}
defer fireQueryEvent(0, EventQueryEnd, 0, mergeEstimate)
// set query start/end callbacks
ctx = context.WithValue(ctx, bleve.SearchQueryStartCallbackKey,
bleve.SearchQueryStartCallbackFn(bleveCtxQueryStartCallback))
ctx = context.WithValue(ctx, bleve.SearchQueryEndCallbackKey,
bleve.SearchQueryEndCallbackFn(bleveCtxQueryEndCallback))
// register with the QuerySupervisor
id := querySupervisor.AddEntry(&QuerySupervisorContext{
Query: searchRequest.Query,
Cancel: cancel,
Size: searchRequest.Size,
From: searchRequest.From,
Timeout: queryCtlParams.Ctl.Timeout,
})
defer querySupervisor.DeleteEntry(id)
searchResult, err := alias.SearchInContext(ctx, searchRequest)
if searchResult != nil {
// check to see if any of the remote searches returned anything
// other than 0, 200, 412, 429, these are returned to the user as
// error status 400, and appear as phase 0 errors detected late.
// 0 means we never heard anything back, and that is dealt with
// in the following section
for _, remoteClient := range remoteClients {
lastStatus, lastErrBody := remoteClient.GetLast()
if lastStatus == http.StatusTooManyRequests {
log.Printf("bleve: remoteClient: %s query reject, statusCode: %d,"+
" err: %v", remoteClient.HostPort, lastStatus, err)
continue
}
if lastStatus != http.StatusOK &&
lastStatus != http.StatusPreconditionFailed &&
lastStatus != 0 {
return fmt.Errorf("bleve: QueryBleve remote client"+
" returned status: %d body: %s", lastStatus, lastErrBody)
}
}
// now see if any of the remote searches returned 412; these should be
// collated into a single 412 response at this level and will
// be presented as phase 1 errors detected late
remoteConsistencyWaitError := cbgt.ErrorConsistencyWait{
Status: "remote consistency error",
StartEndSeqs: make(map[string][]uint64),
}
numRemoteSilent := 0
for _, remoteClient := range remoteClients {
lastStatus, lastErrBody := remoteClient.GetLast()
if lastStatus == 0 {
numRemoteSilent++
}
if lastStatus == http.StatusPreconditionFailed {
var remoteConsistencyErr = struct {
StartEndSeqs map[string][]uint64 `json:"startEndSeqs"`
}{}
err = UnmarshalJSON(lastErrBody, &remoteConsistencyErr)
if err == nil {
for k, v := range remoteConsistencyErr.StartEndSeqs {
remoteConsistencyWaitError.StartEndSeqs[k] = v
}
}
}
}
// if we had any explicitly returned consistency errors, return those
if len(remoteConsistencyWaitError.StartEndSeqs) > 0 {
return &remoteConsistencyWaitError
}
// we had *some* consistency requirements, but we never heard back
// from some of the remote pindexes; just punt for now and return
// a mostly empty 412 indicating we aren't sure
if queryCtlParams.Ctl.Consistency != nil &&
len(queryCtlParams.Ctl.Consistency.Vectors) > 0 &&
numRemoteSilent > 0 {
return &remoteConsistencyWaitError
}
if err1 != nil {
if err2, ok := err1.(*cbgt.ErrorLocalPIndexHealth); ok && len(err2.IndexErrMap) > 0 {
// populate the searchResuls with the details of
// pindexes not searched/covered in this query.
if searchResult.Status.Errors == nil {
searchResult.Status.Errors = make(map[string]error)
}
for pi, e := range err2.IndexErrMap {
searchResult.Status.Errors[pi] = e
searchResult.Status.Failed++
searchResult.Status.Total++
}
}
}
mustEncode(res, searchResult)
// update return error status to indicate any errors within the
// search result that was already propagated as response.
if searchResult.Status != nil && len(searchResult.Status.Errors) > 0 {
err = rest.ErrorAlreadyPropagated
}
}
return err
}
// ---------------------------------------------------------
func (t *BleveDest) Dest(partition string) (cbgt.Dest, error) {
t.m.Lock()
d, err := t.getPartitionLOCKED(partition)
t.m.Unlock()
return d, err
}
func (t *BleveDest) getPartitionLOCKED(partition string) (
*BleveDestPartition, error) {
if t.bindex == nil {
return nil, fmt.Errorf("bleve: BleveDest already closed")
}
bdp, exists := t.partitions[partition]
if !exists || bdp == nil {
bdp = &BleveDestPartition{
bdest: t,
bindex: t.bindex,
partition: partition,
partitionBytes: []byte(partition),
partitionOpaque: []byte("o:" + partition),
batch: t.bindex.NewBatch(),
cwrQueue: cbgt.CwrQueue{},
}
heap.Init(&bdp.cwrQueue)
t.partitions[partition] = bdp
}
return bdp, nil
}
// ---------------------------------------------------------
func (t *BleveDest) Close() error {
t.m.Lock()
err := t.closeLOCKED()
t.m.Unlock()
return err
}
func (t *BleveDest) closeLOCKED() error {
if t.bindex == nil {
return nil // Already closed.
}
atomic.AddUint64(&TotBleveDestClosed, 1)
close(t.stopCh)
partitions := t.partitions
t.partitions = make(map[string]*BleveDestPartition)
t.bindex.Close()
t.bindex = nil
go func() {
// Cancel/error any consistency wait requests.
err := fmt.Errorf("bleve: closeLOCKED")
for _, bdp := range partitions {
bdp.m.Lock()
for _, cwr := range bdp.cwrQueue {
cwr.DoneCh <- err
close(cwr.DoneCh)
}
bdp.m.Unlock()
}
}()
return nil
}
// ---------------------------------------------------------
func (t *BleveDest) ConsistencyWait(partition, partitionUUID string,
consistencyLevel string,
consistencySeq uint64,
cancelCh <-chan bool) error {
if consistencyLevel == "" {
return nil
}
if consistencyLevel != "at_plus" {
return fmt.Errorf("bleve: unsupported consistencyLevel: %s",
consistencyLevel)
}
cwr := &cbgt.ConsistencyWaitReq{
PartitionUUID: partitionUUID,