forked from couchbase/indexing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cluster_manager_agent.go
656 lines (476 loc) · 15.4 KB
/
cluster_manager_agent.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
// 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 (
"errors"
"github.com/couchbase/indexing/secondary/common"
"github.com/couchbase/indexing/secondary/logging"
"github.com/couchbase/indexing/secondary/manager"
"net"
"sync/atomic"
"time"
)
//ClustMgrAgent provides the mechanism to talk to Index Coordinator
type ClustMgrAgent interface {
}
type clustMgrAgent struct {
supvCmdch MsgChannel //supervisor sends commands on this channel
supvRespch MsgChannel //channel to send any message to supervisor
mgr *manager.IndexManager //handle to index manager
config common.Config
metaNotifier manager.MetadataNotifier
stats IndexerStatsHolder
statsCount uint64
}
func NewClustMgrAgent(supvCmdch MsgChannel, supvRespch MsgChannel, cfg common.Config) (
ClustMgrAgent, Message) {
//Init the clustMgrAgent struct
c := &clustMgrAgent{
supvCmdch: supvCmdch,
supvRespch: supvRespch,
config: cfg,
}
mgr, err := manager.NewIndexManager(cfg)
if err != nil {
logging.Errorf("ClustMgrAgent::NewClustMgrAgent Error In Init %v", err)
return nil, &MsgError{
err: Error{code: ERROR_CLUSTER_MGR_AGENT_INIT,
severity: FATAL,
category: CLUSTER_MGR,
cause: err}}
}
c.mgr = mgr
metaNotifier := NewMetaNotifier(supvRespch, cfg, c)
if metaNotifier == nil {
logging.Errorf("ClustMgrAgent::NewClustMgrAgent Error In Init %v", err)
return nil, &MsgError{
err: Error{code: ERROR_CLUSTER_MGR_AGENT_INIT,
severity: FATAL,
category: CLUSTER_MGR}}
}
mgr.RegisterNotifier(metaNotifier)
c.metaNotifier = metaNotifier
//start clustMgrAgent loop which listens to commands from its supervisor
go c.run()
//register with Index Manager for notification of metadata updates
return c, &MsgSuccess{}
}
//run starts the clustmgrAgent loop which listens to messages
//from it supervisor(indexer)
func (c *clustMgrAgent) run() {
//main ClustMgrAgent loop
defer c.mgr.Close()
defer c.panicHandler()
loop:
for {
select {
case cmd, ok := <-c.supvCmdch:
if ok {
if cmd.GetMsgType() == CLUST_MGR_AGENT_SHUTDOWN {
logging.Infof("ClusterMgrAgent: Shutting Down")
c.supvCmdch <- &MsgSuccess{}
break loop
}
c.handleSupvervisorCommands(cmd)
} else {
//supervisor channel closed. exit
break loop
}
}
}
}
func (c *clustMgrAgent) handleSupvervisorCommands(cmd Message) {
switch cmd.GetMsgType() {
case CLUST_MGR_INDEXER_READY:
c.handleIndexerReady(cmd)
case CLUST_MGR_UPDATE_TOPOLOGY_FOR_INDEX:
c.handleUpdateTopologyForIndex(cmd)
case CLUST_MGR_RESET_INDEX:
c.handleResetIndex(cmd)
case CLUST_MGR_GET_GLOBAL_TOPOLOGY:
c.handleGetGlobalTopology(cmd)
case CLUST_MGR_GET_LOCAL:
c.handleGetLocalValue(cmd)
case CLUST_MGR_SET_LOCAL:
c.handleSetLocalValue(cmd)
case CLUST_MGR_DEL_LOCAL:
c.handleDelLocalValue(cmd)
case CLUST_MGR_DEL_BUCKET:
c.handleDeleteBucket(cmd)
case CLUST_MGR_CLEANUP_INDEX:
c.handleCleanupIndex(cmd)
case UPDATE_INDEX_INSTANCE_MAP:
c.handleIndexMap(cmd)
case INDEX_STATS_DONE:
c.handleStats(cmd)
case CONFIG_SETTINGS_UPDATE:
c.handleConfigUpdate(cmd)
default:
logging.Errorf("ClusterMgrAgent::handleSupvervisorCommands Unknown Message %v", cmd)
}
}
func (c *clustMgrAgent) handleUpdateTopologyForIndex(cmd Message) {
logging.Infof("ClustMgr:handleUpdateTopologyForIndex %v", cmd)
indexList := cmd.(*MsgClustMgrUpdate).GetIndexList()
updatedFields := cmd.(*MsgClustMgrUpdate).GetUpdatedFields()
syncUpdate := cmd.(*MsgClustMgrUpdate).GetIsSyncUpdate()
respCh := cmd.(*MsgClustMgrUpdate).GetRespCh()
updatedState := common.INDEX_STATE_NIL
updatedStream := common.NIL_STREAM
updatedError := ""
//TODO is this ok?
updatedRState := common.REBAL_ACTIVE
for _, index := range indexList {
if updatedFields.state {
updatedState = index.State
}
if updatedFields.stream {
updatedStream = index.Stream
}
if updatedFields.err {
updatedError = index.Error
}
if updatedFields.rstate {
updatedRState = index.RState
}
updatedBuildTs := index.BuildTs
var err error
if syncUpdate {
go func() {
err = c.mgr.UpdateIndexInstanceSync(index.Defn.Bucket, index.Defn.DefnId,
updatedState, updatedStream, updatedError, updatedBuildTs, updatedRState)
respCh <- err
}()
} else {
err = c.mgr.UpdateIndexInstance(index.Defn.Bucket, index.Defn.DefnId,
updatedState, updatedStream, updatedError, updatedBuildTs, updatedRState)
}
common.CrashOnError(err)
}
c.supvCmdch <- &MsgSuccess{}
}
func (c *clustMgrAgent) handleResetIndex(cmd Message) {
logging.Infof("ClustMgr:handleResetIndex %v", cmd)
index := cmd.(*MsgClustMgrResetIndex).GetIndex()
if err := c.mgr.ResetIndex(index); err != nil {
common.CrashOnError(err)
}
c.supvCmdch <- &MsgSuccess{}
}
func (c *clustMgrAgent) handleIndexMap(cmd Message) {
logging.Infof("ClustMgr:handleIndexMap %v", cmd)
statsObj := cmd.(*MsgUpdateInstMap).GetStatsObject()
if statsObj != nil {
c.stats.Set(statsObj)
}
c.supvCmdch <- &MsgSuccess{}
}
func (c *clustMgrAgent) handleStats(cmd Message) {
logging.Infof("ClustMgr:handleStats %v", cmd)
c.supvCmdch <- &MsgSuccess{}
c.handleStatsInternal()
atomic.AddUint64(&c.statsCount, 1)
}
func (c *clustMgrAgent) handleStatsInternal() {
stats := c.stats.Get()
if stats != nil {
c.mgr.NotifyStats(stats.GetStats())
}
}
func (c *clustMgrAgent) handleConfigUpdate(cmd Message) {
logging.Infof("ClustMgr:handleConfigUpdate")
c.supvCmdch <- &MsgSuccess{}
cfgUpdate := cmd.(*MsgConfigUpdate)
config := cfgUpdate.GetConfig()
c.mgr.NotifyConfigUpdate(config)
}
func (c *clustMgrAgent) handleGetGlobalTopology(cmd Message) {
logging.Infof("ClustMgr:handleGetGlobalTopology %v", cmd)
//get the latest topology from manager
metaIter, err := c.mgr.NewIndexDefnIterator()
if err != nil {
common.CrashOnError(err)
}
defer metaIter.Close()
indexInstMap := make(common.IndexInstMap)
for _, defn, err := metaIter.Next(); err == nil; _, defn, err = metaIter.Next() {
var idxDefn common.IndexDefn
idxDefn = *defn
t, e := c.mgr.GetTopologyByBucket(idxDefn.Bucket)
if e != nil {
common.CrashOnError(e)
}
if t == nil {
logging.Warnf("ClustMgr:handleGetGlobalTopology Index Instance Not "+
"Found For Index Definition %v. Ignored.", idxDefn)
continue
}
inst := t.GetIndexInstByDefn(idxDefn.DefnId)
if inst == nil {
logging.Warnf("ClustMgr:handleGetGlobalTopology Index Instance Not "+
"Found For Index Definition %v. Ignored.", idxDefn)
continue
}
//init Desc for pre-Spock indexes
if idxDefn.Desc == nil {
idxDefn.Desc = make([]bool, len(idxDefn.SecExprs))
}
idxInst := common.IndexInst{InstId: common.IndexInstId(inst.InstId),
Defn: idxDefn,
State: common.IndexState(inst.State),
Stream: common.StreamId(inst.StreamId),
ReplicaId: int(inst.ReplicaId),
Version: int(inst.Version),
RState: common.RebalanceState(inst.RState),
Scheduled: inst.Scheduled,
StorageMode: inst.StorageMode,
OldStorageMode: inst.OldStorageMode,
}
indexInstMap[idxInst.InstId] = idxInst
}
c.supvCmdch <- &MsgClustMgrTopology{indexInstMap: indexInstMap}
}
func (c *clustMgrAgent) handleGetLocalValue(cmd Message) {
key := cmd.(*MsgClustMgrLocal).GetKey()
logging.Infof("ClustMgr:handleGetLocalValue Key %v", key)
val, err := c.mgr.GetLocalValue(key)
c.supvCmdch <- &MsgClustMgrLocal{
mType: CLUST_MGR_GET_LOCAL,
key: key,
value: val,
err: err,
}
}
func (c *clustMgrAgent) handleSetLocalValue(cmd Message) {
key := cmd.(*MsgClustMgrLocal).GetKey()
val := cmd.(*MsgClustMgrLocal).GetValue()
logging.Infof("ClustMgr:handleSetLocalValue Key %v Value %v", key, val)
err := c.mgr.SetLocalValue(key, val)
c.supvCmdch <- &MsgClustMgrLocal{
mType: CLUST_MGR_SET_LOCAL,
key: key,
value: val,
err: err,
}
}
func (c *clustMgrAgent) handleDelLocalValue(cmd Message) {
key := cmd.(*MsgClustMgrLocal).GetKey()
logging.Infof("ClustMgr:handleDelLocalValue Key %v", key)
err := c.mgr.DeleteLocalValue(key)
c.supvCmdch <- &MsgClustMgrLocal{
mType: CLUST_MGR_DEL_LOCAL,
key: key,
err: err,
}
}
func (c *clustMgrAgent) handleDeleteBucket(cmd Message) {
logging.Infof("ClustMgr:handleDeleteBucket %v", cmd)
bucket := cmd.(*MsgClustMgrUpdate).GetBucket()
streamId := cmd.(*MsgClustMgrUpdate).GetStreamId()
err := c.mgr.DeleteIndexForBucket(bucket, streamId)
common.CrashOnError(err)
c.supvCmdch <- &MsgSuccess{}
}
func (c *clustMgrAgent) handleCleanupIndex(cmd Message) {
logging.Infof("ClustMgr:handleCleanupIndex %v", cmd)
index := cmd.(*MsgClustMgrUpdate).GetIndexList()[0]
err := c.mgr.CleanupIndex(index.Defn.DefnId)
common.CrashOnError(err)
c.supvCmdch <- &MsgSuccess{}
}
func (c *clustMgrAgent) handleIndexerReady(cmd Message) {
logging.Infof("ClustMgr:handleIndexerReady %v", cmd)
err := c.mgr.NotifyIndexerReady()
common.CrashOnError(err)
c.supvCmdch <- &MsgSuccess{}
}
//panicHandler handles the panic from index manager
func (c *clustMgrAgent) panicHandler() {
//panic recovery
if rc := recover(); rc != nil {
var err error
switch x := rc.(type) {
case string:
err = errors.New(x)
case error:
err = x
default:
err = errors.New("Unknown panic")
}
logging.Fatalf("ClusterMgrAgent Panic Err %v", err)
logging.Fatalf("%s", logging.StackTrace())
//panic, propagate to supervisor
msg := &MsgError{
err: Error{code: ERROR_INDEX_MANAGER_PANIC,
severity: FATAL,
category: CLUSTER_MGR,
cause: err}}
c.supvRespch <- msg
}
}
type metaNotifier struct {
adminCh MsgChannel
config common.Config
mgr *clustMgrAgent
}
func NewMetaNotifier(adminCh MsgChannel, config common.Config, mgr *clustMgrAgent) *metaNotifier {
if adminCh == nil {
return nil
}
return &metaNotifier{
adminCh: adminCh,
config: config,
mgr: mgr,
}
}
func (meta *metaNotifier) OnIndexCreate(indexDefn *common.IndexDefn, instId common.IndexInstId,
replicaId int, reqCtx *common.MetadataRequestContext) error {
logging.Infof("clustMgrAgent::OnIndexCreate Notification "+
"Received for Create Index %v %v", indexDefn, reqCtx)
pc := meta.makeDefaultPartitionContainer()
idxInst := common.IndexInst{InstId: instId,
Defn: *indexDefn,
State: common.INDEX_STATE_CREATED,
Pc: pc,
ReplicaId: replicaId,
}
if idxInst.Defn.InstVersion != 0 {
idxInst.RState = common.REBAL_PENDING
}
respCh := make(MsgChannel)
meta.adminCh <- &MsgCreateIndex{mType: CLUST_MGR_CREATE_INDEX_DDL,
indexInst: idxInst,
respCh: respCh,
reqCtx: reqCtx}
//wait for response
if res, ok := <-respCh; ok {
switch res.GetMsgType() {
case MSG_SUCCESS:
logging.Infof("clustMgrAgent::OnIndexCreate Success "+
"for Create Index %v", indexDefn)
return nil
case MSG_ERROR:
logging.Errorf("clustMgrAgent::OnIndexCreate Error "+
"for Create Index %v. Error %v.", indexDefn, res)
err := res.(*MsgError).GetError()
return err.cause
default:
logging.Fatalf("clustMgrAgent::OnIndexCreate Unknown Response "+
"Received for Create Index %v. Response %v", indexDefn, res)
common.CrashOnError(errors.New("Unknown Response"))
}
} else {
logging.Fatalf("clustMgrAgent::OnIndexCreate Unexpected Channel Close "+
"for Create Index %v", indexDefn)
common.CrashOnError(errors.New("Unknown Response"))
}
return nil
}
func (meta *metaNotifier) OnIndexBuild(indexInstList []common.IndexInstId,
buckets []string, reqCtx *common.MetadataRequestContext) map[common.IndexInstId]error {
logging.Infof("clustMgrAgent::OnIndexBuild Notification "+
"Received for Build Index %v %v", indexInstList, reqCtx)
respCh := make(MsgChannel)
meta.adminCh <- &MsgBuildIndex{indexInstList: indexInstList,
respCh: respCh,
bucketList: buckets,
reqCtx: reqCtx}
//wait for response
if res, ok := <-respCh; ok {
switch res.GetMsgType() {
case CLUST_MGR_BUILD_INDEX_DDL_RESPONSE:
errMap := res.(*MsgBuildIndexResponse).GetErrorMap()
logging.Infof("clustMgrAgent::OnIndexBuild returns "+
"for Build Index %v", indexInstList)
return errMap
case MSG_ERROR:
logging.Errorf("clustMgrAgent::OnIndexBuild Error "+
"for Build Index %v. Error %v.", indexInstList, res)
err := res.(*MsgError).GetError()
errMap := make(map[common.IndexInstId]error)
for _, instId := range indexInstList {
errMap[instId] = &common.IndexerError{Reason: err.String(), Code: err.convertError()}
}
return errMap
default:
logging.Fatalf("clustMgrAgent::OnIndexBuild Unknown Response "+
"Received for Build Index %v. Response %v", indexInstList, res)
common.CrashOnError(errors.New("Unknown Response"))
}
} else {
logging.Fatalf("clustMgrAgent::OnIndexBuild Unexpected Channel Close "+
"for Create Index %v", indexInstList)
common.CrashOnError(errors.New("Unknown Response"))
}
return nil
}
func (meta *metaNotifier) OnIndexDelete(instId common.IndexInstId,
bucket string, reqCtx *common.MetadataRequestContext) error {
logging.Infof("clustMgrAgent::OnIndexDelete Notification "+
"Received for Drop IndexId %v %v", instId, reqCtx)
respCh := make(MsgChannel)
//Treat DefnId as InstId for now
meta.adminCh <- &MsgDropIndex{mType: CLUST_MGR_DROP_INDEX_DDL,
indexInstId: instId,
respCh: respCh,
bucket: bucket,
reqCtx: reqCtx}
//wait for response
if res, ok := <-respCh; ok {
switch res.GetMsgType() {
case MSG_SUCCESS:
logging.Infof("clustMgrAgent::OnIndexDelete Success "+
"for Drop IndexId %v", instId)
return nil
case MSG_ERROR:
logging.Errorf("clustMgrAgent::OnIndexDelete Error "+
"for Drop IndexId %v. Error %v", instId, res)
err := res.(*MsgError).GetError()
return &common.IndexerError{Reason: err.String(), Code: err.convertError()}
default:
logging.Fatalf("clustMgrAgent::OnIndexDelete Unknown Response "+
"Received for Drop IndexId %v. Response %v", instId, res)
common.CrashOnError(errors.New("Unknown Response"))
}
} else {
logging.Fatalf("clustMgrAgent::OnIndexDelete Unexpected Channel Close "+
"for Drop IndexId %v", instId)
common.CrashOnError(errors.New("Unknown Response"))
}
return nil
}
func (meta *metaNotifier) OnFetchStats() error {
go meta.fetchStats()
return nil
}
func (meta *metaNotifier) fetchStats() {
ticker := time.NewTicker(time.Millisecond * 500)
defer ticker.Stop()
startTime := time.Now()
for range ticker.C {
if meta.mgr.stats.Get() != nil && atomic.LoadUint64(&meta.mgr.statsCount) != 0 {
meta.mgr.handleStatsInternal()
logging.Infof("Fetch new stats upon request by life cycle manager")
return
}
if time.Now().Sub(startTime) > time.Minute {
return
}
}
}
func (meta *metaNotifier) makeDefaultPartitionContainer() common.PartitionContainer {
pc := common.NewKeyPartitionContainer()
//Add one partition for now
addr := net.JoinHostPort("", meta.config["streamMaintPort"].String())
endpt := []common.Endpoint{common.Endpoint(addr)}
partnDefn := common.KeyPartitionDefn{Id: common.PartitionId(1),
Endpts: endpt}
pc.AddPartition(common.PartitionId(1), partnDefn)
return pc
}