-
Notifications
You must be signed in to change notification settings - Fork 36
/
manager.go
841 lines (677 loc) · 26.1 KB
/
manager.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
// Copyright 2014-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package manager
import (
//"fmt"
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
gometaC "github.com/couchbase/gometa/common"
gometaL "github.com/couchbase/gometa/log"
"github.com/couchbase/indexing/secondary/common"
"github.com/couchbase/indexing/secondary/logging"
"github.com/couchbase/indexing/secondary/manager/client"
)
///////////////////////////////////////////////////////
// Type Definition
///////////////////////////////////////////////////////
var USE_MASTER_REPO = false
type IndexManager struct {
repo *MetadataRepo
coordinator *Coordinator
eventMgr *eventManager
lifecycleMgr *LifecycleMgr
cinfoClient *common.ClusterInfoClient
reqcic *common.ClusterInfoClient
requestServer RequestServer
basepath string
quota uint64
clusterURL string
repoName string
// bucket monitor
monitorKillch chan bool
mutex sync.Mutex
isClosed bool
}
//
// Index Lifecycle
// 1) Index Creation
// A) When an index is created, the index definition is assigned to a 64 bits UUID (IndexDefnId).
// B) IndexManager will persist the index definition.
// C) IndexManager will persist the index instance with INDEX_STATE_CREATED status.
// Each instance is assigned a 64 bits IndexInstId. For the first instance of an index,
// the IndexInstId is equal to the IndexDefnId.
// D) IndexManager will invovke MetadataNotifier.OnIndexCreate().
// E) IndexManager will update instance to status INDEX_STATE_READY.
// F) If there is any error in (1B) - (1E), IndexManager will cleanup by deleting index definition and index instance.
// Since there is no atomic transaction, cleanup may not be completed, and the index will be left in an invalid state.
// See (5) for conditions where the index is considered valid.
// G) If there is any error in (1E), IndexManager will also invoke OnIndexDelete()
// H) Any error from (1A) or (1F), the error will be reported back to MetadataProvider.
//
// 2) Immediate Index Build (index definition is persisted successfully and deferred build flag is false)
// A) MetadataNotifier.OnIndexBuild() is invoked. OnIndexBuild() is responsible for updating the state of the index
// instance (e.g. from READY to INITIAL).
// B) If there is an error in (2A), the error will be returned to the MetadataProvider.
// C) No cleanup will be perfromed by IndexManager if OnIndexBuild() fails. In other words, the index can be left in
// INDEX_STATE_READY. The user should be able to kick off index build again using deferred build.
// D) OnIndexBuild() can be running on a separate go-rountine. It can invoke UpdateIndexInstance() at any time during
// index build. This update will be queued serially and apply to the topology specific for that index instance (will
// not affect any other index instance). The new index state will be returned to the MetadataProvider asynchronously.
//
// 3) Deferred Index Build
// A) For Deferred Index Build, it will follow step (2A) - (2D).
//
// 4) Index Deletion
// A) When an index is deleted, IndexManager will set the index to INDEX_STATE_DELETED.
// B) If (4A) fails, the error will be returned and the index is considered as NOT deleted.
// C) IndexManager will then invoke MetadataNotifier.OnIndexDelete().
// D) The IndexManager will delete the index definition first before deleting the index instance. since there is no atomic
// transaction, the cleanup may not be completed, and index can be in inconsistent state. See (5) for valid index state.
// E) Any error returned from (4C) to (4D) will not be returned to the client (since these are cleanup steps)
//
// 5) Valid Index States
// A) Both index definition and index instance exist.
// B) Index Instance is not in INDEX_STATE_CREATE or INDEX_STATE_DELETED.
//
type MetadataNotifier interface {
OnIndexCreate(*common.IndexDefn, common.IndexInstId, int, []common.PartitionId, []int, uint32, common.IndexInstId, *common.MetadataRequestContext) error
OnIndexDelete(common.IndexInstId, string, *common.MetadataRequestContext) error
OnIndexBuild([]common.IndexInstId, []string, *common.MetadataRequestContext) map[common.IndexInstId]error
OnPartitionPrune(common.IndexInstId, []common.PartitionId, *common.MetadataRequestContext) error
OnFetchStats() error
}
type RequestServer interface {
MakeRequest(opCode gometaC.OpCode, key string, value []byte) error
MakeAsyncRequest(opCode gometaC.OpCode, key string, value []byte) error
}
///////////////////////////////////////////////////////
// public function
///////////////////////////////////////////////////////
//
// Create a new IndexManager. It is a singleton owned by the ClustMgrAgent object, which is owned by Indexer.
//
func NewIndexManager(config common.Config, storageMode common.StorageMode) (mgr *IndexManager, err error) {
return NewIndexManagerInternal(config, storageMode)
}
//
// Create a new IndexManager singleton that wraps a LocalMetadataRepo (not a RemoteMetadataRepo).
//
func NewIndexManagerInternal(config common.Config, storageMode common.StorageMode) (mgr *IndexManager, err error) {
gometaL.Current = &logging.SystemLogger
mgr = new(IndexManager)
mgr.isClosed = false
if storageMode == common.StorageMode(common.FORESTDB) {
mgr.quota = mgr.calcBufCacheFromMemQuota(config)
} else {
mgr.quota = 1 * 1024 * 1024 //1 MB
}
// Initialize the event manager. This is non-blocking. The event manager can be
// called indirectly by watcher/meta-repo when new metadata changes are sent
// from gometa master to the indexer node.
mgr.eventMgr, err = newEventManager()
if err != nil {
mgr.Close()
return nil, err
}
mgr.clusterURL = config["clusterAddr"].String()
cic, err := common.NewClusterInfoClient(mgr.clusterURL, common.DEFAULT_POOL, config)
if err != nil {
mgr.Close()
return nil, err
}
mgr.cinfoClient = cic
mgr.cinfoClient.SetUserAgent("IndexMgr")
// Another ClusterInfoClient for RequestHandler to avoid waiting due to locks of cinfoClient.
reqcic, err := common.NewClusterInfoClient(mgr.clusterURL, common.DEFAULT_POOL, config)
if err != nil {
mgr.Close()
return nil, err
}
mgr.reqcic = reqcic
mgr.reqcic.SetUserAgent("IndexRequestHandler")
// Initialize LifecycleMgr.
lifecycleMgr, err := NewLifecycleMgr(mgr.clusterURL)
if err != nil {
mgr.Close()
return nil, err
}
mgr.lifecycleMgr = lifecycleMgr
// Initialize MetadataRepo. This a blocking call until the
// the metadataRepo (including watcher) is operational (e.g.
// finish sync with remote metadata repo master).
//mgr.repo, err = NewMetadataRepo(requestAddr, leaderAddr, config, mgr)
mgr.basepath = config["storage_dir"].String()
os.Mkdir(mgr.basepath, 0755)
mgr.repoName = filepath.Join(mgr.basepath, gometaC.REPOSITORY_NAME)
cinfo := cic.GetClusterInfoCache()
cinfo.RLock()
defer cinfo.RUnlock()
adminPort, err := cinfo.GetLocalServicePort(common.INDEX_ADMIN_SERVICE, true)
if err != nil {
mgr.Close()
return nil, err
}
sleepDur := config["metadata.compaction.sleepDuration"].Int()
threshold := config["metadata.compaction.threshold"].Int()
minFileSize := config["metadata.compaction.minFileSize"].Int()
logging.Infof("Starting metadadta repo: quota %v sleep duration %v threshold %v min file size %v",
mgr.quota, sleepDur, threshold, minFileSize)
mgr.repo, mgr.requestServer, err = NewLocalMetadataRepo(adminPort, mgr.eventMgr, mgr.lifecycleMgr, mgr.repoName, mgr.quota,
uint64(sleepDur), uint8(threshold), uint64(minFileSize))
if err != nil {
mgr.Close()
return nil, err
}
// start lifecycle manager
mgr.lifecycleMgr.Run(mgr.repo, mgr.requestServer)
// coordinator
mgr.coordinator = nil
// monitor keyspace
mgr.monitorKillch = make(chan bool)
go mgr.monitorKeyspace(mgr.monitorKillch)
return mgr, nil
}
func (mgr *IndexManager) RegisterRestEndpoints(mux *http.ServeMux, config common.Config) {
// register request handler
RegisterRequestHandler(mgr, mux, config)
}
func (mgr *IndexManager) StartCoordinator(config string) {
mgr.mutex.Lock()
defer mgr.mutex.Unlock()
// Initialize Coordinator. This is non-blocking. The coordinator
// is operational only after it can syncrhonized with the majority
// of the indexers. Any request made to the coordinator will be
// put in a channel for later processing (once leader election is done).
// Once the coordinator becomes the leader, it will invoke teh stream
// manager.
mgr.coordinator = NewCoordinator(mgr.repo, mgr, mgr.basepath)
go mgr.coordinator.Run(config)
}
func (m *IndexManager) IsClose() bool {
m.mutex.Lock()
defer m.mutex.Unlock()
return m.isClosed
}
//
// Reset Connections
//
func (m *IndexManager) ResetConnections(notifier MetadataNotifier) error {
m.mutex.Lock()
defer m.mutex.Unlock()
if m.isClosed {
return nil
}
logging.Infof("manager ResetConnection: closing metadata repo")
return m.repo.ResetConnections()
}
//
// Clean up the IndexManager
//
func (m *IndexManager) Close() {
m.mutex.Lock()
defer m.mutex.Unlock()
if m.isClosed {
return
}
if m.coordinator != nil {
m.coordinator.Terminate()
}
if m.eventMgr != nil {
m.eventMgr.close()
}
if m.lifecycleMgr != nil {
m.lifecycleMgr.Terminate()
}
if m.repo != nil {
m.repo.Close()
}
if m.cinfoClient != nil {
m.cinfoClient.Close()
}
if m.reqcic != nil {
m.reqcic.Close()
}
if m.monitorKillch != nil {
close(m.monitorKillch)
}
m.isClosed = true
}
func (m *IndexManager) FetchNewClusterInfoCache() (*common.ClusterInfoCache, error) {
return common.FetchNewClusterInfoCache(m.clusterURL, common.DEFAULT_POOL, "IndexMgr")
}
///////////////////////////////////////////////////////
// public function - Metadata Operation
///////////////////////////////////////////////////////
func (m *IndexManager) GetMemoryQuota() uint64 {
return m.quota
}
func (m *IndexManager) RegisterNotifier(notifier MetadataNotifier) {
m.repo.RegisterNotifier(notifier)
m.lifecycleMgr.RegisterNotifier(notifier)
}
func (m *IndexManager) SetLocalValue(key string, value string) error {
return m.repo.SetLocalValue(key, value)
}
func (m *IndexManager) DeleteLocalValue(key string) error {
return m.repo.DeleteLocalValue(key)
}
func (m *IndexManager) GetLocalValue(key string) (string, error) {
return m.repo.GetLocalValue(key)
}
//
// Get an index definiton by id
//
func (m *IndexManager) GetIndexDefnById(id common.IndexDefnId) (*common.IndexDefn, error) {
return m.repo.GetIndexDefnById(id)
}
//
// Get Metadata Iterator for index definition
//
func (m *IndexManager) NewIndexDefnIterator() (*MetaIterator, error) {
return m.repo.NewIterator()
}
//
// Listen to create Index Request
//
func (m *IndexManager) StartListenIndexCreate(id string) (<-chan interface{}, error) {
return m.eventMgr.register(id, EVENT_CREATE_INDEX)
}
//
// Stop Listen to create Index Request
//
func (m *IndexManager) StopListenIndexCreate(id string) {
m.eventMgr.unregister(id, EVENT_CREATE_INDEX)
}
//
// Listen to delete Index Request
//
func (m *IndexManager) StartListenIndexDelete(id string) (<-chan interface{}, error) {
return m.eventMgr.register(id, EVENT_DROP_INDEX)
}
//
// Stop Listen to delete Index Request
//
func (m *IndexManager) StopListenIndexDelete(id string) {
m.eventMgr.unregister(id, EVENT_DROP_INDEX)
}
//
// Listen to update Topology Request
//
func (m *IndexManager) StartListenTopologyUpdate(id string) (<-chan interface{}, error) {
return m.eventMgr.register(id, EVENT_UPDATE_TOPOLOGY)
}
//
// Stop Listen to update Topology Request
//
func (m *IndexManager) StopListenTopologyUpdate(id string) {
m.eventMgr.unregister(id, EVENT_UPDATE_TOPOLOGY)
}
//
// Handle Create Index DDL. This function will block until
// 1) The index defn is persisted durably in the dictionary
// 2) The index defn is applied locally to each "active" indexer
// node. An active node is a running node that is in the same
// network partition as the leader. A leader is always in
// the majority partition.
//
// This function will return an error if the outcome of the
// request is not known (e.g. the node is partitioned
// from the network). It may still mean that the request
// is able to go through (processed by some other nodes).
//
// A Index DDL can be processed by any node. If this node is a leader,
// then the DDL request will be processed by the leader. If it is a
// follower, it will forward the request to the leader.
//
// This function will not be processed until the index manager
// is either a leader or follower. Therefore, if (1) the node is
// in the minority partition after network partition or (2) the leader
// dies, this node will unblock any in-flight request initiated
// by this node (by returning error). The node will run leader
// election again. Until this node has became a leader or follower,
// it will not be able to handle another request.
//
// If this node is partitioned from its leader, it can still recieve
// updates from the dictionary if this node still connects to it.
//
func (m *IndexManager) HandleCreateIndexDDL(defn *common.IndexDefn, isRebalReq bool) error {
key := fmt.Sprintf("%d", defn.DefnId)
content, err := common.MarshallIndexDefn(defn)
if err != nil {
return err
}
if USE_MASTER_REPO {
if !m.coordinator.NewRequest(uint32(OPCODE_ADD_IDX_DEFN), indexDefnIdStr(defn.DefnId), content) {
// TODO: double check if it exists in the dictionary
return NewError(ERROR_MGR_DDL_CREATE_IDX, NORMAL, INDEX_MANAGER, nil,
fmt.Sprintf("Fail to complete processing create index statement for index '%s'", defn.Name))
}
} else {
if isRebalReq {
return m.requestServer.MakeRequest(client.OPCODE_CREATE_INDEX_REBAL, key, content)
} else {
return m.requestServer.MakeRequest(client.OPCODE_CREATE_INDEX, key, content)
}
}
return nil
}
func (m *IndexManager) HandleDeleteIndexDDL(defnId common.IndexDefnId) error {
key := fmt.Sprintf("%d", defnId)
if USE_MASTER_REPO {
if !m.coordinator.NewRequest(uint32(OPCODE_DEL_IDX_DEFN), indexDefnIdStr(defnId), nil) {
// TODO: double check if it exists in the dictionary
return NewError(ERROR_MGR_DDL_DROP_IDX, NORMAL, INDEX_MANAGER, nil,
fmt.Sprintf("Fail to complete processing delete index statement for index id = '%d'", defnId))
}
} else {
return m.requestServer.MakeRequest(client.OPCODE_DROP_INDEX_REBAL, key, []byte(""))
}
return nil
}
// HandleBuildIndexRebalDDL synchronously handles a request to build usually multiple indexes from
// rebalance only. It delegates to gometa using opcode OPCODE_BUILD_INDEX_REBAL.
func (m *IndexManager) HandleBuildIndexRebalDDL(indexIds client.IndexIdList) error {
key := fmt.Sprintf("%d", indexIds.DefnIds[0])
content, _ := client.MarshallIndexIdList(&indexIds)
//TODO handle err
return m.requestServer.MakeRequest(client.OPCODE_BUILD_INDEX_REBAL, key, content)
}
func (m *IndexManager) UpdateIndexInstance(bucket, scope, collection string, defnId common.IndexDefnId, instId common.IndexInstId,
state common.IndexState, streamId common.StreamId, err string, buildTime []uint64, rState common.RebalanceState,
partitions []uint64, versions []int, instVersion int) error {
inst := &topologyChange{
Bucket: bucket,
Scope: scope,
Collection: collection,
DefnId: uint64(defnId),
InstId: uint64(instId),
State: uint32(state),
StreamId: uint32(streamId),
Error: err,
BuildTime: buildTime,
RState: uint32(rState),
Partitions: partitions,
Versions: versions,
InstVersion: instVersion}
buf, e := json.Marshal(&inst)
if e != nil {
return e
}
// Update index instance is an async operation. Since indexer may update index instance during
// callback from MetadataNotifier. By making async, it avoids deadlock.
logging.Debugf("IndexManager.UpdateIndexInstance(): making request for Index instance update")
return m.requestServer.MakeAsyncRequest(client.OPCODE_UPDATE_INDEX_INST, fmt.Sprintf("%v", defnId), buf)
}
func (m *IndexManager) UpdateIndexInstanceSync(bucket, scope, collection string, defnId common.IndexDefnId, instId common.IndexInstId,
state common.IndexState, streamId common.StreamId, err string, buildTime []uint64, rState common.RebalanceState,
partitions []uint64, versions []int, instVersion int) error {
inst := &topologyChange{
Bucket: bucket,
Scope: scope,
Collection: collection,
DefnId: uint64(defnId),
InstId: uint64(instId),
State: uint32(state),
StreamId: uint32(streamId),
Error: err,
BuildTime: buildTime,
RState: uint32(rState),
Partitions: partitions,
Versions: versions,
InstVersion: instVersion}
buf, e := json.Marshal(&inst)
if e != nil {
return e
}
logging.Debugf("IndexManager.UpdateIndexInstanceSync(): making request for Index instance update")
return m.requestServer.MakeRequest(client.OPCODE_UPDATE_INDEX_INST, fmt.Sprintf("%v", defnId), buf)
}
func (m *IndexManager) DropOrPruneInstance(defn common.IndexDefn, notify bool) error {
inst := &dropInstance{
Defn: defn,
Notify: notify,
UpdateStatusOnly: false,
}
buf, e := json.Marshal(&inst)
if e != nil {
return e
}
logging.Debugf("IndexManager.DropInstance(): making request for drop instance")
return m.requestServer.MakeRequest(client.OPCODE_DROP_OR_PRUNE_INSTANCE, fmt.Sprintf("%v", defn.DefnId), buf)
}
func (m *IndexManager) CleanupPartition(defn common.IndexDefn, updateStatusOnly bool) error {
inst := &dropInstance{
Defn: defn,
Notify: false,
UpdateStatusOnly: updateStatusOnly,
}
buf, e := json.Marshal(&inst)
if e != nil {
return e
}
logging.Debugf("IndexManager.CleanupPartition(): making request for cleanup partition")
return m.requestServer.MakeRequest(client.OPCODE_CLEANUP_PARTITION, fmt.Sprintf("%v", defn.DefnId), buf)
}
func (m *IndexManager) MergePartition(defnId common.IndexDefnId, srcInstId common.IndexInstId, srcRState common.RebalanceState,
tgtInstId common.IndexInstId, tgtInstVersion uint64, tgtPartitions []common.PartitionId, tgtVersions []int) error {
partitions := make([]uint64, len(tgtPartitions))
for i, partnId := range tgtPartitions {
partitions[i] = uint64(partnId)
}
inst := &mergePartition{
DefnId: uint64(defnId),
SrcInstId: uint64(srcInstId),
SrcRState: uint64(srcRState),
TgtInstId: uint64(tgtInstId),
TgtPartitions: partitions,
TgtVersions: tgtVersions,
TgtInstVersion: tgtInstVersion,
}
buf, e := json.Marshal(&inst)
if e != nil {
return e
}
logging.Debugf("IndexManager.MergePartition(): making request for merge partition")
return m.requestServer.MakeRequest(client.OPCODE_MERGE_PARTITION, fmt.Sprintf("%v", defnId), buf)
}
func (m *IndexManager) ResetIndex(index common.IndexInst) error {
index.Pc = nil
content, err := common.MarshallIndexInst(&index)
if err != nil {
return err
}
logging.Debugf("IndexManager.ResetIndex(): making request for Index reset")
return m.requestServer.MakeRequest(client.OPCODE_RESET_INDEX, fmt.Sprintf("%v", index.InstId), content)
}
func (m *IndexManager) ResetIndexOnRollback(index common.IndexInst) error {
index.Pc = nil
content, err := common.MarshallIndexInst(&index)
if err != nil {
return err
}
logging.Debugf("IndexManager.ResetIndexOnRollback(): making request for Index reset")
return m.requestServer.MakeRequest(client.OPCODE_RESET_INDEX_ON_ROLLBACK, fmt.Sprintf("%v", index.InstId), content)
}
func (m *IndexManager) DeleteIndexForBucket(bucket string, streamId common.StreamId) error {
logging.Debugf("IndexManager.DeleteIndexForBucket(): making request for deleting index for bucket")
return m.requestServer.MakeAsyncRequest(client.OPCODE_DELETE_BUCKET, bucket, []byte{byte(streamId)})
}
func (m *IndexManager) DeleteIndexForCollection(bucket, scope, collection string, streamId common.StreamId) error {
key := bucket + "/" + scope + "/" + collection
logging.Debugf("IndexManager.DeleteIndexForCollection(): making request for deleting index for bucket")
return m.requestServer.MakeAsyncRequest(client.OPCODE_DELETE_COLLECTION, key, []byte{byte(streamId)})
}
func (m *IndexManager) CleanupIndex(index common.IndexInst) error {
index.Pc = nil
content, err := common.MarshallIndexInst(&index)
if err != nil {
return err
}
logging.Debugf("IndexManager.CleanupIndex(): making request for cleaning up index")
return m.requestServer.MakeAsyncRequest(client.OPCODE_CLEANUP_INDEX, fmt.Sprintf("%v", index.InstId), content)
}
func (m *IndexManager) NotifyIndexerReady() error {
logging.Debugf("IndexManager.NotifyIndexerReady(): making request to notify indexer is ready ")
return m.requestServer.MakeAsyncRequest(client.OPCODE_INDEXER_READY, "", []byte{})
}
func (m *IndexManager) RebalanceRunning() error {
logging.Debugf("IndexManager.RebalanceRunning(): making request for rebalance running")
return m.requestServer.MakeAsyncRequest(client.OPCODE_REBALANCE_RUNNING, "", []byte{})
}
func (m *IndexManager) NotifyStats(stats common.Statistics) error {
logging.Debugf("IndexManager.NotifyStats(): making request for new stats")
buf, e := json.Marshal(&stats)
if e != nil {
return e
}
return m.requestServer.MakeAsyncRequest(client.OPCODE_BROADCAST_STATS, "", buf)
}
func (m *IndexManager) NotifyConfigUpdate(config common.Config) error {
logging.Debugf("IndexManager.NotifyConfigUpdate(): making request for new config update")
buf, e := json.Marshal(&config)
if e != nil {
return e
}
return m.requestServer.MakeAsyncRequest(client.OPCODE_CONFIG_UPDATE, "", buf)
}
func (m *IndexManager) GetTopologyByCollection(bucket, scope, collection string) (*IndexTopology, error) {
return m.repo.GetTopologyByCollection(bucket, scope, collection)
}
//
// Get the global topology
//
func (m *IndexManager) GetGlobalTopology() (*GlobalTopology, error) {
return m.repo.GetGlobalTopology()
}
///////////////////////////////////////////////////////
// public function - Keyspace Monitor
///////////////////////////////////////////////////////
func (m *IndexManager) monitorKeyspace(killch chan bool) {
ticker := time.NewTicker(time.Second * 10)
defer ticker.Stop()
for {
select {
case <-ticker.C:
keyspaceList, err := m.getKeyspaceForCleanup()
if err == nil {
for _, keyspace := range keyspaceList {
logging.Infof("IndexManager.MonitorKeyspace(): making request for deleting defered and active MAINT_STREAM index for keyspace %v", keyspace)
// Make sure it is making a synchronous request. So if indexer main loop cannot proceed to delete the indexes
// (e.g. indexer is slow or blocked), it won't keep generating new request.
m.requestServer.MakeRequest(client.OPCODE_INVALID_COLLECTION, keyspace, []byte{})
}
} else {
logging.Errorf("IndexManager.MonitorKeyspace(): Error occurred while getting keyspace list for cleanup %v", err)
}
case <-killch:
return
}
}
}
func (m *IndexManager) getKeyspaceForCleanup() ([]string, error) {
var result []string = nil
// Get Global Topology
globalTop, err := m.GetGlobalTopology()
if err != nil {
return nil, err
}
if globalTop == nil {
return result, nil
}
cinfo := m.cinfoClient.GetClusterInfoCache()
cinfo.RLock()
defer cinfo.RUnlock()
// iterate through each topologey key
for _, key := range globalTop.TopologyKeys {
bucket, scope, collection := getBucketScopeCollectionFromTopologyKey(key)
// Get bucket UUID. Bucket uuid is BUCKET_UUID_NIL for non-existent bucket.
currentUUID := cinfo.GetBucketUUID(bucket)
// Get CollectionID. CollectionID is COLLECTION_ID_NIL for non-existing collection
collectionID := cinfo.GetCollectionID(bucket, scope, collection)
version := cinfo.GetClusterVersion()
topology, err := m.repo.GetTopologyByCollection(bucket, scope, collection)
if err == nil && topology != nil {
definitions := make([]IndexDefnDistribution, len(topology.Definitions))
copy(definitions, topology.Definitions)
for _, defnRef := range definitions {
defn, err := m.repo.GetIndexDefnById(common.IndexDefnId(defnRef.DefnId))
if err == nil && defn != nil {
instances := make([]IndexInstDistribution, len(defnRef.Instances))
copy(instances, defnRef.Instances)
for _, instRef := range instances {
// Check for invalid keyspace
if (defn.BucketUUID != currentUUID || (version >= common.INDEXER_70_VERSION &&
defn.CollectionId != collectionID)) &&
instRef.State != uint32(common.INDEX_STATE_DELETED) {
keyspace := strings.Join([]string{bucket, scope, collection}, ":")
result = append(result, keyspace)
break
}
}
}
}
}
}
return result, nil
}
///////////////////////////////////////////////////////
// package local function
///////////////////////////////////////////////////////
//
// Get MetadataRepo
// Any caller uses MetadatdaRepo should only for read purpose.
// Writer operation should go through LifecycleMgr
//
func (m *IndexManager) getMetadataRepo() *MetadataRepo {
return m.repo
}
//
// Get lifecycle manager
//
func (m *IndexManager) getLifecycleMgr() *LifecycleMgr {
return m.lifecycleMgr
}
//
// Notify new event
//
func (m *IndexManager) notify(evtType EventType, obj interface{}) {
m.eventMgr.notify(evtType, obj)
}
func (m *IndexManager) startMasterService() error {
return nil
}
func (m *IndexManager) stopMasterService() {
}
//Calculate forestdb buffer cache from memory quota
func (m *IndexManager) calcBufCacheFromMemQuota(config common.Config) uint64 {
totalQuota := config["settings.memory_quota"].Uint64()
//calculate queue memory
fracQueueMem := config["mutation_manager.fdb.fracMutationQueueMem"].Float64()
queueMem := uint64(fracQueueMem * float64(totalQuota))
queueMaxMem := config["mutation_manager.maxQueueMem"].Uint64()
if queueMem > queueMaxMem {
queueMem = queueMaxMem
}
overhead := uint64(0.15 * float64(totalQuota))
//max overhead 5GB
if overhead > 5*1024*1024*1024 {
overhead = 5 * 1024 * 1024 * 1024
}
bufcache := totalQuota - queueMem - overhead
//min 256MB
if bufcache < 256*1024*1024 {
bufcache = 256 * 1024 * 1024
}
return bufcache
}