forked from couchbase/indexing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
indexer.go
5213 lines (4092 loc) · 146 KB
/
indexer.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 indexer
import (
"bytes"
"crypto/tls"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"os"
"path/filepath"
"runtime"
"runtime/debug"
"runtime/pprof"
"strings"
"sync"
"time"
"github.com/couchbase/cbauth"
"github.com/couchbase/indexing/secondary/common"
"github.com/couchbase/indexing/secondary/fdb"
"github.com/couchbase/indexing/secondary/logging"
"github.com/couchbase/indexing/secondary/memdb"
"github.com/couchbase/indexing/secondary/memdb/nodetable"
projClient "github.com/couchbase/indexing/secondary/projector/client"
"github.com/couchbase/indexing/secondary/stubs/nitro/mm"
"github.com/couchbase/indexing/secondary/stubs/nitro/plasma"
)
type Indexer interface {
Shutdown() Message
}
var StreamAddrMap StreamAddressMap
var StreamTopicName map[common.StreamId]string
var ServiceAddrMap map[string]string
type BucketIndexCountMap map[string]int
type BucketFlushInProgressMap map[string]bool
type BucketObserveFlushDoneMap map[string]MsgChannel
type BucketRequestStopCh map[string]StopChannel
type BucketRollbackTs map[string]*common.TsVbuuid
//mem stats
var (
gMemstatCache runtime.MemStats
gMemstatCacheLastUpdated time.Time
gMemstatLock sync.RWMutex
)
// Errors
var (
ErrFatalComm = errors.New("Fatal Internal Communication Error")
ErrInconsistentState = errors.New("Inconsistent Internal State")
ErrKVRollbackForInitRequest = errors.New("KV Rollback Received For Initial Build Request")
ErrMaintStreamMissingBucket = errors.New("Bucket Missing in Maint Stream")
ErrInvalidStream = errors.New("Invalid Stream")
ErrIndexerInRecovery = errors.New("Indexer In Recovery")
ErrKVConnect = errors.New("Error Connecting KV")
ErrUnknownBucket = errors.New("Unknown Bucket")
ErrIndexerNotActive = errors.New("Indexer Not Active")
ErrInvalidMetadata = errors.New("Invalid Metadata")
ErrBucketEphemeral = errors.New("Ephemeral Buckets Must Use MOI Storage")
)
type indexer struct {
id string
state common.IndexerState
indexInstMap common.IndexInstMap //map of indexInstId to IndexInst
indexPartnMap IndexPartnMap //map of indexInstId to PartitionInst
streamBucketStatus map[common.StreamId]BucketStatus
streamBucketFlushInProgress map[common.StreamId]BucketFlushInProgressMap
streamBucketObserveFlushDone map[common.StreamId]BucketObserveFlushDoneMap
streamBucketRequestStopCh map[common.StreamId]BucketRequestStopCh
streamBucketRollbackTs map[common.StreamId]BucketRollbackTs
streamBucketRequestQueue map[common.StreamId]map[string]chan *kvRequest
streamBucketRequestLock map[common.StreamId]map[string]chan *sync.Mutex
bucketRollbackTimes map[string]int64
bucketBuildTs map[string]Timestamp
//TODO Remove this once cbq bridge support goes away
bucketCreateClientChMap map[string]MsgChannel
wrkrRecvCh MsgChannel //channel to receive messages from workers
internalRecvCh MsgChannel //buffered channel to queue worker requests
adminRecvCh MsgChannel //channel to receive admin messages
internalAdminRecvCh MsgChannel //internal channel to receive admin messages
internalAdminRespCh chan bool //internal channel to respond admin messages
shutdownInitCh MsgChannel //internal shutdown channel for indexer
shutdownCompleteCh MsgChannel //indicate shutdown completion
mutMgrCmdCh MsgChannel //channel to send commands to mutation manager
storageMgrCmdCh MsgChannel //channel to send commands to storage manager
tkCmdCh MsgChannel //channel to send commands to timekeeper
adminMgrCmdCh MsgChannel //channel to send commands to admin port manager
rebalMgrCmdCh MsgChannel //channel to send commands to rebalance manager
ddlSrvMgrCmdCh MsgChannel //channel to send commands to ddl service manager
compactMgrCmdCh MsgChannel //channel to send commands to compaction manager
clustMgrAgentCmdCh MsgChannel //channel to send messages to index coordinator
kvSenderCmdCh MsgChannel //channel to send messages to kv sender
settingsMgrCmdCh MsgChannel
statsMgrCmdCh MsgChannel
scanCoordCmdCh MsgChannel //chhannel to send messages to scan coordinator
mutMgrExitCh MsgChannel //channel to indicate mutation manager exited
tk Timekeeper //handle to timekeeper
storageMgr StorageManager //handle to storage manager
compactMgr CompactionManager //handle to compaction manager
mutMgr MutationManager //handle to mutation manager
adminMgr AdminManager //handle to admin port manager
rebalMgr RebalanceMgr //handle to rebalance manager
ddlSrvMgr *DDLServiceMgr //handle to ddl service manager
clustMgrAgent ClustMgrAgent //handle to ClustMgrAgent
kvSender KVSender //handle to KVSender
settingsMgr settingsManager
statsMgr *statsManager
scanCoord ScanCoordinator //handle to ScanCoordinator
config common.Config
kvlock sync.Mutex //fine-grain lock for KVSender
stateLock sync.RWMutex //lock to protect the bucketStatus map
stats *IndexerStats
enableManager bool
cpuProfFd *os.File
rebalanceRunning bool
rebalanceToken *RebalanceToken
}
type kvRequest struct {
lock *sync.Mutex
bucket string
streamId common.StreamId
grantCh chan bool
}
func NewIndexer(config common.Config) (Indexer, Message) {
idx := &indexer{
wrkrRecvCh: make(MsgChannel, WORKER_RECV_QUEUE_LEN),
internalRecvCh: make(MsgChannel, WORKER_MSG_QUEUE_LEN),
adminRecvCh: make(MsgChannel, WORKER_MSG_QUEUE_LEN),
internalAdminRecvCh: make(MsgChannel),
internalAdminRespCh: make(chan bool),
shutdownInitCh: make(MsgChannel),
shutdownCompleteCh: make(MsgChannel),
mutMgrCmdCh: make(MsgChannel),
storageMgrCmdCh: make(MsgChannel),
tkCmdCh: make(MsgChannel),
adminMgrCmdCh: make(MsgChannel),
rebalMgrCmdCh: make(MsgChannel),
ddlSrvMgrCmdCh: make(MsgChannel),
compactMgrCmdCh: make(MsgChannel),
clustMgrAgentCmdCh: make(MsgChannel),
kvSenderCmdCh: make(MsgChannel),
settingsMgrCmdCh: make(MsgChannel),
statsMgrCmdCh: make(MsgChannel),
scanCoordCmdCh: make(MsgChannel),
mutMgrExitCh: make(MsgChannel),
indexInstMap: make(common.IndexInstMap),
indexPartnMap: make(IndexPartnMap),
streamBucketStatus: make(map[common.StreamId]BucketStatus),
streamBucketFlushInProgress: make(map[common.StreamId]BucketFlushInProgressMap),
streamBucketObserveFlushDone: make(map[common.StreamId]BucketObserveFlushDoneMap),
streamBucketRequestStopCh: make(map[common.StreamId]BucketRequestStopCh),
streamBucketRollbackTs: make(map[common.StreamId]BucketRollbackTs),
streamBucketRequestQueue: make(map[common.StreamId]map[string]chan *kvRequest),
streamBucketRequestLock: make(map[common.StreamId]map[string]chan *sync.Mutex),
bucketBuildTs: make(map[string]Timestamp),
bucketRollbackTimes: make(map[string]int64),
bucketCreateClientChMap: make(map[string]MsgChannel),
}
logging.Infof("Indexer::NewIndexer Status Warmup")
snapshotNotifych := make(chan IndexSnapshot, 100)
var res Message
idx.settingsMgr, idx.config, res = NewSettingsManager(idx.settingsMgrCmdCh, idx.wrkrRecvCh, config)
if res.GetMsgType() != MSG_SUCCESS {
logging.Fatalf("Indexer::NewIndexer settingsMgr Init Error %+v", res)
return nil, res
}
idx.stats = NewIndexerStats()
// Read memquota setting
memQuota := int64(idx.config["settings.memory_quota"].Uint64())
idx.stats.memoryQuota.Set(memQuota)
plasma.SetMemoryQuota(int64(float64(memQuota) * PLASMA_MEMQUOTA_FRAC))
memdb.Debug(idx.config["settings.moi.debug"].Bool())
reclaimBlockSize := int64(idx.config["plasma.LSSReclaimBlockSize"].Int())
plasma.SetLogReclaimBlockSize(reclaimBlockSize)
logging.Infof("Indexer::NewIndexer Starting with Vbuckets %v", idx.config["numVbuckets"].Int())
idx.initStreamAddressMap()
idx.initStreamFlushMap()
idx.initServiceAddressMap()
//Start Mutation Manager
idx.mutMgr, res = NewMutationManager(idx.mutMgrCmdCh, idx.wrkrRecvCh, idx.config)
if res.GetMsgType() != MSG_SUCCESS {
logging.Fatalf("Indexer::NewIndexer Mutation Manager Init Error %+v", res)
return nil, res
}
//Start KV Sender
idx.kvSender, res = NewKVSender(idx.kvSenderCmdCh, idx.wrkrRecvCh, idx.config)
if res.GetMsgType() != MSG_SUCCESS {
logging.Fatalf("Indexer::NewIndexer KVSender Init Error %+v", res)
return nil, res
}
//Start Timekeeper
idx.tk, res = NewTimekeeper(idx.tkCmdCh, idx.wrkrRecvCh, idx.config)
if res.GetMsgType() != MSG_SUCCESS {
logging.Fatalf("Indexer::NewIndexer Timekeeper Init Error %+v", res)
return nil, res
}
//Start Scan Coordinator
idx.scanCoord, res = NewScanCoordinator(idx.scanCoordCmdCh, idx.wrkrRecvCh, idx.config, snapshotNotifych)
if res.GetMsgType() != MSG_SUCCESS {
logging.Fatalf("Indexer::NewIndexer Scan Coordinator Init Error %+v", res)
return nil, res
}
idx.enableManager = idx.config["enableManager"].Bool()
if idx.enableManager {
idx.clustMgrAgent, res = NewClustMgrAgent(idx.clustMgrAgentCmdCh, idx.adminRecvCh, idx.config)
if res.GetMsgType() != MSG_SUCCESS {
logging.Fatalf("Indexer::NewIndexer ClusterMgrAgent Init Error %+v", res)
return nil, res
}
}
idx.statsMgr, res = NewStatsManager(idx.statsMgrCmdCh, idx.wrkrRecvCh, idx.config)
if res.GetMsgType() != MSG_SUCCESS {
logging.Fatalf("Indexer::NewIndexer statsMgr Init Error %+v", res)
return nil, res
}
isEnterprise := idx.config["isEnterprise"].Bool()
if isEnterprise {
common.SetBuildMode(common.ENTERPRISE)
} else {
common.SetBuildMode(common.COMMUNITY)
}
logging.Infof("Indexer::NewIndexer Build Mode Set %v", common.GetBuildMode())
idx.setIndexerState(common.INDEXER_BOOTSTRAP)
idx.stats.indexerState.Set(int64(common.INDEXER_BOOTSTRAP))
msgUpdateIndexInstMap := idx.newIndexInstMsg(nil)
if err := idx.sendUpdatedIndexMapToWorker(msgUpdateIndexInstMap, nil, idx.statsMgrCmdCh, "statsMgr"); err != nil {
common.CrashOnError(err)
}
idx.scanCoordCmdCh <- &MsgIndexerState{mType: INDEXER_BOOTSTRAP}
<-idx.scanCoordCmdCh
// Setup http server
addr := net.JoinHostPort("", idx.config["httpPort"].String())
logging.PeriodicProfile(logging.Debug, addr, "goroutine")
go func() {
if err := http.ListenAndServe(addr, nil); err != nil {
logging.Fatalf("indexer:: Error Starting Http Server: %v", err)
common.CrashOnError(err)
}
}()
sslPort := idx.config["httpsPort"].String()
if sslPort != "" {
certFile := idx.config["certFile"].String()
keyFile := idx.config["keyFile"].String()
sslAddr := net.JoinHostPort("", sslPort)
var reload bool = false
var tlslsnr *net.Listener = nil
cbauth.RegisterCertRefreshCallback(func() error {
if tlslsnr != nil {
reload = true
(*tlslsnr).Close()
}
return nil
})
go func() {
for {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
logging.Fatalf("indexer:: Error in loading SSL certificate: %v", err)
return
}
// allow only strong ssl as this is an internal API and interop is not a concern
sslsrv := &http.Server{
Addr: sslAddr,
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0),
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{cert},
CipherSuites: []uint16{tls.TLS_RSA_WITH_AES_256_CBC_SHA},
MinVersion: tls.VersionTLS12,
PreferServerCipherSuites: true,
// ClientAuth: tls.RequireAndVerifyClientCert,
},
}
// replace below with ListenAndServeTLS on moving to go1.8
lsnr, err := net.Listen("tcp", sslAddr)
if err != nil {
logging.Fatalf("indexer:: Error in listenting to SSL port: %v", err)
return
}
val := tls.NewListener(lsnr, sslsrv.TLSConfig)
tlslsnr = &val
reload = false
logging.Infof("indexer:: SSL server started: %v", sslAddr)
err = http.Serve(*tlslsnr, nil)
if reload {
logging.Warnf("indexer:: SSL certificate change: %v", err)
} else {
logging.Fatalf("indexer:: Error in SSL Server: %v", err)
return
}
}
}()
}
//read persisted indexer state
if err := idx.bootstrap(snapshotNotifych); err != nil {
logging.Fatalf("Indexer::Unable to Bootstrap Indexer from Persisted Metadata %v", err)
return nil, &MsgError{err: Error{cause: err}}
}
//if storageMode has changed in settings while bootstrap was in progress
//indexer needs to restart
idx.updateStorageMode(idx.config)
//Register with Index Coordinator
if err := idx.registerWithCoordinator(); err != nil {
//log error and exit
}
//sync topology
if err := idx.syncTopologyWithCoordinator(); err != nil {
//log error and exit
}
//Start Admin port listener
idx.adminMgr, res = NewAdminManager(idx.adminMgrCmdCh, idx.adminRecvCh)
if res.GetMsgType() != MSG_SUCCESS {
logging.Fatalf("Indexer::NewIndexer Admin Manager Init Error %+v", res)
return nil, res
}
//Start DDL Service Manager
//Initialize DDL Service Manager before rebalance manager so DDL service manager is ready
//when Rebalancing manager receives ns_server rebalancing callback.
idx.ddlSrvMgr, res = NewDDLServiceMgr(idx.ddlSrvMgrCmdCh, idx.wrkrRecvCh, idx.config)
if res.GetMsgType() != MSG_SUCCESS {
logging.Fatalf("Indexer::NewIndexer DDL Service Manager Init Error %+v", res)
return nil, res
}
//Start Rebalance Manager
idx.rebalMgr, res = NewRebalanceMgr(idx.rebalMgrCmdCh, idx.wrkrRecvCh, idx.config, idx.rebalanceRunning, idx.rebalanceToken)
if res.GetMsgType() != MSG_SUCCESS {
logging.Fatalf("Indexer::NewIndexer Rebalance Manager Init Error %+v", res)
return nil, res
}
if idx.getIndexerState() == common.INDEXER_BOOTSTRAP {
idx.setIndexerState(common.INDEXER_ACTIVE)
idx.stats.indexerState.Set(int64(common.INDEXER_ACTIVE))
}
idx.scanCoordCmdCh <- &MsgIndexerState{mType: INDEXER_RESUME, rollbackTimes: idx.bucketRollbackTimes}
<-idx.scanCoordCmdCh
// Persist node uuid in Metadata store
idx.clustMgrAgentCmdCh <- &MsgClustMgrLocal{
mType: CLUST_MGR_SET_LOCAL,
key: INDEXER_NODE_UUID,
value: idx.config["nodeuuid"].String(),
}
respMsg := <-idx.clustMgrAgentCmdCh
resp := respMsg.(*MsgClustMgrLocal)
errMsg := resp.GetError()
if errMsg != nil {
logging.Fatalf("Indexer::NewIndexer Unable to set INDEXER_NODE_UUID In Local"+
"Meta Storage. Err %v", errMsg)
common.CrashOnError(errMsg)
}
logging.Infof("Indexer::NewIndexer Status %v", idx.getIndexerState())
idx.compactMgr, res = NewCompactionManager(idx.compactMgrCmdCh, idx.wrkrRecvCh, idx.config)
if res.GetMsgType() != MSG_SUCCESS {
logging.Fatalf("Indexer::NewCompactionmanager Init Error %+v", res)
return nil, res
}
// Start indexer endpoints for CRUD operations.
// Initialize the REST server after indexer bootstrap is completed
NewRestServer(idx.config["clusterAddr"].String())
go idx.monitorMemUsage()
go idx.logMemstats()
go idx.collectProgressStats(true)
//start the main indexer loop
idx.run()
return idx, &MsgSuccess{}
}
func (idx *indexer) collectProgressStats(fetchDcp bool) {
respCh := make(chan bool)
idx.internalRecvCh <- &MsgStatsRequest{
mType: INDEX_PROGRESS_STATS,
respch: respCh,
fetchDcp: fetchDcp,
}
<-respCh
logging.Infof("progress stats collection done.")
idx.sendProgressStats()
}
func (idx *indexer) sendProgressStats() {
idx.internalRecvCh <- &MsgStatsRequest{
mType: INDEX_STATS_DONE,
respch: nil,
}
logging.Infof("send progress stats to clients")
}
func (idx *indexer) acquireStreamRequestLock(bucket string, streamId common.StreamId) *kvRequest {
// queue request
request := &kvRequest{grantCh: make(chan bool, 1), lock: nil, bucket: bucket, streamId: streamId}
idx.kvlock.Lock()
defer idx.kvlock.Unlock()
// allocate the request queue
rq, ok := idx.streamBucketRequestQueue[streamId][bucket]
if !ok {
rq = make(chan *kvRequest, 5000)
if _, ok = idx.streamBucketRequestQueue[streamId]; !ok {
idx.streamBucketRequestQueue[streamId] = make(map[string]chan *kvRequest)
}
idx.streamBucketRequestQueue[streamId][bucket] = rq
}
// allocate the lock
lq, ok := idx.streamBucketRequestLock[streamId][bucket]
if !ok {
lq = make(chan *sync.Mutex, 1) // hold one lock
if _, ok = idx.streamBucketRequestLock[streamId]; !ok {
idx.streamBucketRequestLock[streamId] = make(map[string]chan *sync.Mutex)
}
idx.streamBucketRequestLock[streamId][bucket] = lq
// seed the lock
lq <- new(sync.Mutex)
}
// acquire the lock if it is available and there is no other request ahead of me
if len(rq) == 0 && len(lq) == 1 {
request.lock = <-lq
request.grantCh <- true
} else if len(rq) < 5000 {
rq <- request
} else {
common.CrashOnError(errors.New("acquireStreamRequestLock: too many requests acquiring stream request lock"))
}
return request
}
func (idx *indexer) waitStreamRequestLock(req *kvRequest) {
<-req.grantCh
}
func (idx *indexer) releaseStreamRequestLock(req *kvRequest) {
if req.lock == nil {
return
}
idx.kvlock.Lock()
defer idx.kvlock.Unlock()
streamId := req.streamId
bucket := req.bucket
rq, ok := idx.streamBucketRequestQueue[streamId][bucket]
if ok && len(rq) != 0 {
next := <-rq
next.lock = req.lock
next.grantCh <- true
} else {
if lq, ok := idx.streamBucketRequestLock[streamId][bucket]; ok {
lq <- req.lock
} else {
common.CrashOnError(errors.New("releaseStreamRequestLock: streamBucketRequestLock is not initialized"))
}
}
}
func (idx *indexer) registerWithCoordinator() error {
//get the IndexerId from persistence and send it to Index Coordinator
//if there is no IndexerId, send an empty one. Coordinator will assign
//a new IndexerId in that case and treat this as a fresh node.
return nil
}
func (idx *indexer) syncTopologyWithCoordinator() error {
//get the latest topology from coordinator
return nil
}
func (idx *indexer) recoverPersistedSnapshots() error {
//recover persisted snapshots from disk
return nil
}
//run starts the main loop for the indexer
func (idx *indexer) run() {
go idx.listenWorkerMsgs()
go idx.listenAdminMsgs()
for {
select {
case msg, ok := <-idx.internalRecvCh:
if ok {
idx.handleWorkerMsgs(msg)
}
case msg, ok := <-idx.internalAdminRecvCh:
if ok {
idx.handleAdminMsgs(msg)
idx.internalAdminRespCh <- true
}
case <-idx.shutdownInitCh:
//send shutdown to all workers
idx.shutdownWorkers()
//close the shutdown complete channel to indicate
//all workers are shutdown
close(idx.shutdownCompleteCh)
return
}
}
}
//run starts the main loop for the indexer
func (idx *indexer) listenAdminMsgs() {
waitForStream := true
for {
select {
case msg, ok := <-idx.adminRecvCh:
if ok {
// internalAdminRecvCh size is 1. So it will blocked if the previous msg is being
// processed.
idx.internalAdminRecvCh <- msg
<-idx.internalAdminRespCh
if waitForStream {
// now that indexer has processed the message. Let's make sure that
// the stream request is finished before processing the next admin
// msg. This is done by acquiring a lock on the stream request for each
// bucket (on both streams). The lock is FIFO, so if this function
// can get a lock, it will mean that previous stream request would have
// been cleared.
buckets := idx.getBucketForAdminMsg(msg)
for _, bucket := range buckets {
f := func(streamId common.StreamId, bucket string) {
lock := idx.acquireStreamRequestLock(bucket, streamId)
defer idx.releaseStreamRequestLock(lock)
idx.waitStreamRequestLock(lock)
}
f(common.INIT_STREAM, bucket)
f(common.MAINT_STREAM, bucket)
}
}
}
case <-idx.shutdownInitCh:
return
}
}
}
func (idx *indexer) getBucketForAdminMsg(msg Message) []string {
switch msg.GetMsgType() {
case CLUST_MGR_CREATE_INDEX_DDL, CBQ_CREATE_INDEX_DDL:
createMsg := msg.(*MsgCreateIndex)
return []string{createMsg.GetIndexInst().Defn.Bucket}
case CLUST_MGR_BUILD_INDEX_DDL:
buildMsg := msg.(*MsgBuildIndex)
return buildMsg.GetBucketList()
case CLUST_MGR_DROP_INDEX_DDL, CBQ_DROP_INDEX_DDL:
dropMsg := msg.(*MsgDropIndex)
return []string{dropMsg.GetBucket()}
default:
return nil
}
}
func (idx *indexer) listenWorkerMsgs() {
//listen to worker messages
for {
select {
case msg, ok := <-idx.wrkrRecvCh:
if ok {
//handle high priority messages
switch msg.GetMsgType() {
case MSG_ERROR:
err := msg.(*MsgError).GetError()
if err.code == ERROR_MUT_MGR_PANIC {
close(idx.mutMgrExitCh)
}
}
idx.internalRecvCh <- msg
}
case <-idx.shutdownInitCh:
//exit the loop
return
}
}
}
func (idx *indexer) handleWorkerMsgs(msg Message) {
switch msg.GetMsgType() {
case STREAM_READER_HWT:
//fwd the message to timekeeper
idx.tkCmdCh <- msg
<-idx.tkCmdCh
case STREAM_READER_STREAM_BEGIN:
//fwd the message to timekeeper
idx.tkCmdCh <- msg
<-idx.tkCmdCh
case STREAM_READER_STREAM_END:
//fwd the message to timekeeper
idx.tkCmdCh <- msg
<-idx.tkCmdCh
case STREAM_READER_STREAM_DROP_DATA:
logging.Warnf("Indexer::handleWorkerMsgs Received Drop Data "+
"From Mutation Mgr %v. Ignored.", msg)
case STREAM_READER_SNAPSHOT_MARKER:
//fwd the message to timekeeper
idx.tkCmdCh <- msg
<-idx.tkCmdCh
case STREAM_READER_CONN_ERROR:
//fwd the message to timekeeper
idx.tkCmdCh <- msg
<-idx.tkCmdCh
case TK_STABILITY_TIMESTAMP:
//send TS to Mutation Manager
ts := msg.(*MsgTKStabilityTS).GetTimestamp()
bucket := msg.(*MsgTKStabilityTS).GetBucket()
streamId := msg.(*MsgTKStabilityTS).GetStreamId()
changeVec := msg.(*MsgTKStabilityTS).GetChangeVector()
if idx.getStreamBucketState(streamId, bucket) == STREAM_INACTIVE {
logging.Warnf("Indexer: Skipped PersistTs for %v %v. "+
"STREAM_INACTIVE", streamId, bucket)
return
}
idx.streamBucketFlushInProgress[streamId][bucket] = true
if ts.GetSnapType() == common.FORCE_COMMIT {
idx.storageMgrCmdCh <- &MsgMutMgrFlushDone{mType: MUT_MGR_FLUSH_DONE,
streamId: streamId,
bucket: bucket,
ts: ts}
<-idx.storageMgrCmdCh
} else {
idx.mutMgrCmdCh <- &MsgMutMgrFlushMutationQueue{
mType: MUT_MGR_PERSIST_MUTATION_QUEUE,
bucket: bucket,
ts: ts,
streamId: streamId,
changeVec: changeVec}
<-idx.mutMgrCmdCh
}
case MUT_MGR_ABORT_PERSIST:
idx.mutMgrCmdCh <- msg
<-idx.mutMgrCmdCh
case MUT_MGR_FLUSH_DONE:
idx.storageMgrCmdCh <- msg
<-idx.storageMgrCmdCh
case MUT_MGR_ABORT_DONE:
idx.tkCmdCh <- msg
<-idx.tkCmdCh
case STORAGE_SNAP_DONE:
bucket := msg.(*MsgMutMgrFlushDone).GetBucket()
streamId := msg.(*MsgMutMgrFlushDone).GetStreamId()
idx.streamBucketFlushInProgress[streamId][bucket] = false
//if there is any observer for flush done, notify
idx.notifyFlushObserver(msg)
//fwd the message to timekeeper
idx.tkCmdCh <- msg
<-idx.tkCmdCh
case TK_INIT_BUILD_DONE:
idx.handleInitialBuildDone(msg)
case TK_MERGE_STREAM:
idx.handleMergeStream(msg)
case INDEXER_PREPARE_RECOVERY:
idx.handlePrepareRecovery(msg)
case INDEXER_INITIATE_RECOVERY:
idx.handleInitRecovery(msg)
case STORAGE_INDEX_SNAP_REQUEST,
STORAGE_INDEX_STORAGE_STATS,
STORAGE_INDEX_COMPACT:
idx.storageMgrCmdCh <- msg
<-idx.storageMgrCmdCh
case CONFIG_SETTINGS_UPDATE:
idx.handleConfigUpdate(msg)
case INDEXER_INIT_PREP_RECOVERY:
idx.handleInitPrepRecovery(msg)
case INDEXER_PREPARE_UNPAUSE:
idx.handlePrepareUnpause(msg)
case INDEXER_UNPAUSE:
idx.handleUnpause(msg)
case INDEXER_PREPARE_DONE:
idx.handlePrepareDone(msg)
case INDEXER_RECOVERY_DONE:
idx.handleRecoveryDone(msg)
case KV_STREAM_REPAIR:
idx.handleKVStreamRepair(msg)
case TK_INIT_BUILD_DONE_ACK:
idx.handleInitBuildDoneAck(msg)
case TK_MERGE_STREAM_ACK:
idx.handleMergeStreamAck(msg)
case STREAM_REQUEST_DONE:
idx.handleStreamRequestDone(msg)
case KV_SENDER_RESTART_VBUCKETS:
//fwd the message to kv_sender
idx.sendMsgToKVSender(msg)
case STORAGE_STATS:
idx.storageMgrCmdCh <- msg
<-idx.storageMgrCmdCh
case SCAN_STATS:
idx.scanCoordCmdCh <- msg
<-idx.scanCoordCmdCh
case INDEX_PROGRESS_STATS:
idx.tkCmdCh <- msg
<-idx.tkCmdCh
case INDEX_STATS_DONE:
idx.clustMgrAgentCmdCh <- msg
<-idx.clustMgrAgentCmdCh
case INDEXER_BUCKET_NOT_FOUND:
idx.handleBucketNotFound(msg)
case INDEXER_STATS:
idx.handleStats(msg)
case MSG_ERROR,
STREAM_READER_ERROR:
//crash for all errors by default
logging.Fatalf("Indexer::handleWorkerMsgs Fatal Error On Worker Channel %+v", msg)
err := msg.(*MsgError).GetError()
common.CrashOnError(err.cause)
case STATS_RESET:
idx.handleResetStats()
case INDEXER_PAUSE:
idx.handleIndexerPause(msg)
case INDEXER_RESUME:
idx.handleIndexerResume(msg)
case CLUST_MGR_SET_LOCAL:
idx.handleSetLocalMeta(msg)
case CLUST_MGR_GET_LOCAL:
idx.handleGetLocalMeta(msg)
case CLUST_MGR_DEL_LOCAL:
idx.handleDelLocalMeta(msg)
case INDEXER_CHECK_DDL_IN_PROGRESS:
idx.handleCheckDDLInProgress(msg)
case INDEXER_UPDATE_RSTATE:
idx.handleUpdateIndexRState(msg)
default:
logging.Fatalf("Indexer::handleWorkerMsgs Unknown Message %+v", msg)
common.CrashOnError(errors.New("Unknown Msg On Worker Channel"))
}
}
func (idx *indexer) updateStorageMode(newConfig common.Config) {
confStorageMode := strings.ToLower(newConfig["settings.storage_mode"].String())
if confStorageMode != "" && confStorageMode != common.GetClusterStorageMode().String() {
common.SetClusterStorageModeStr(confStorageMode)
}
s := common.IndexTypeToStorageMode(common.IndexType(confStorageMode))
s = idx.promoteStorageModeIfNecessary(s, newConfig)
confStorageMode = string(common.StorageModeToIndexType(s))
logging.Infof("Indexer::updateStorageMode Try setting storage mode to %v", confStorageMode)
if common.GetStorageMode() == common.NOT_SET {
if confStorageMode != "" {
if idx.canSetStorageMode(confStorageMode) {
if common.SetStorageModeStr(confStorageMode) {
logging.Infof("Indexer::updateStorageMode Storage Mode Set %v", common.GetStorageMode())
initStorageSettings(newConfig)
idx.stats.needsRestart.Set(true)
} else {
logging.Infof("Indexer::updateStorageMode Invalid Storage Mode %v", confStorageMode)
}
}
}
} else {
if confStorageMode != "" && confStorageMode != common.GetStorageMode().String() {
if idx.checkAnyValidIndex() {
logging.Warnf("Indexer::updateStorageMode Ignore New Storage Mode %v. Already Set %v. Valid Indexes Found.",
confStorageMode, common.GetStorageMode())
} else {
if common.SetStorageModeStr(confStorageMode) {
logging.Infof("Indexer::updateStorageMode Storage Mode Set %v", common.GetStorageMode())
initStorageSettings(newConfig)
idx.stats.needsRestart.Set(true)
} else {
logging.Infof("Indexer::updateStorageMode Invalid Storage Mode %v", confStorageMode)
}
}
}
}
}
func (idx *indexer) handleConfigUpdate(msg Message) {
cfgUpdate := msg.(*MsgConfigUpdate)
newConfig := cfgUpdate.GetConfig()
idx.updateStorageMode(newConfig)
if newConfig["settings.memory_quota"].Uint64() !=
idx.config["settings.memory_quota"].Uint64() {
memQuota := int64(newConfig["settings.memory_quota"].Uint64())
idx.stats.memoryQuota.Set(memQuota)
plasma.SetMemoryQuota(int64(float64(memQuota) * PLASMA_MEMQUOTA_FRAC))
if common.GetStorageMode() == common.FORESTDB ||
common.GetStorageMode() == common.NOT_SET {
logging.Infof("Indexer::handleConfigUpdate restart indexer due to memory_quota")
idx.stats.needsRestart.Set(true)
}
}
if newConfig["settings.max_array_seckey_size"].Int() !=
idx.config["settings.max_array_seckey_size"].Int() {
logging.Infof("Indexer::handleConfigUpdate restart indexer due to max_array_seckey_size")
idx.stats.needsRestart.Set(true)
}
if newConfig["settings.max_seckey_size"].Int() !=
idx.config["settings.max_seckey_size"].Int() {
logging.Infof("Indexer::handleConfigUpdate restart indexer due to max_seckey_size")
idx.stats.needsRestart.Set(true)
}
if newConfig["settings.allow_large_keys"].Bool() !=
idx.config["settings.allow_large_keys"].Bool() {
logging.Infof("Indexer::handleConfigUpdate restart indexer due to allow_large_keys")
idx.stats.needsRestart.Set(true)
}
if percent, ok := newConfig["settings.gc_percent"]; ok && percent.Int() > 0 {
logging.Infof("Indexer: Setting GC percent to %v", percent.Int())
debug.SetGCPercent(percent.Int())
}
memdb.Debug(idx.config["settings.moi.debug"].Bool())
idx.setProfilerOptions(newConfig)
idx.config = newConfig
idx.compactMgrCmdCh <- msg
<-idx.compactMgrCmdCh
idx.tkCmdCh <- msg
<-idx.tkCmdCh
idx.scanCoordCmdCh <- msg