forked from couchbase/indexing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lifecycle.go
1830 lines (1481 loc) · 57.3 KB
/
lifecycle.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 manager
import (
"encoding/json"
"errors"
"fmt"
"github.com/couchbase/cbauth/metakv"
c "github.com/couchbase/gometa/common"
"github.com/couchbase/gometa/message"
"github.com/couchbase/gometa/protocol"
"github.com/couchbase/indexing/secondary/common"
fdb "github.com/couchbase/indexing/secondary/fdb"
"github.com/couchbase/indexing/secondary/logging"
"github.com/couchbase/indexing/secondary/manager/client"
"math"
"strings"
"sync/atomic"
"time"
//"runtime/debug"
)
//////////////////////////////////////////////////////////////
// concrete type/struct
//////////////////////////////////////////////////////////////
type LifecycleMgr struct {
repo *MetadataRepo
cinfo *common.ClusterInfoCache
notifier MetadataNotifier
clusterURL string
incomings chan *requestHolder
bootstraps chan *requestHolder
outgoings chan c.Packet
killch chan bool
indexerReady bool
builder *builder
janitor *janitor
updator *updator
requestServer RequestServer
}
type requestHolder struct {
request protocol.RequestMsg
fid string
}
type topologyChange struct {
Bucket string `json:"bucket,omitempty"`
DefnId uint64 `json:"defnId,omitempty"`
State uint32 `json:"state,omitempty"`
StreamId uint32 `json:"steamId,omitempty"`
Error string `json:"error,omitempty"`
BuildTime []uint64 `json:"buildTime,omitempty"`
RState uint32 `json:"rState,omitempty"`
}
type builder struct {
manager *LifecycleMgr
pendings map[string][]uint64
notifych chan *common.IndexDefn
batchSize int32
disable int32
}
type janitor struct {
manager *LifecycleMgr
}
type updator struct {
manager *LifecycleMgr
indexerVersion uint64
serverGroup string
nodeAddr string
clusterVersion uint64
}
//////////////////////////////////////////////////////////////
// Lifecycle Mgr - event processing
//////////////////////////////////////////////////////////////
func NewLifecycleMgr(notifier MetadataNotifier, clusterURL string) (*LifecycleMgr, error) {
cinfo, err := common.FetchNewClusterInfoCache(clusterURL, common.DEFAULT_POOL)
if err != nil {
return nil, err
}
mgr := &LifecycleMgr{repo: nil,
cinfo: cinfo,
notifier: notifier,
clusterURL: clusterURL,
incomings: make(chan *requestHolder, 1000),
outgoings: make(chan c.Packet, 1000),
killch: make(chan bool),
bootstraps: make(chan *requestHolder, 1000),
indexerReady: false}
mgr.builder = newBuilder(mgr)
mgr.janitor = newJanitor(mgr)
mgr.updator = newUpdator(mgr)
return mgr, nil
}
func (m *LifecycleMgr) Run(repo *MetadataRepo, requestServer RequestServer) {
m.repo = repo
m.requestServer = requestServer
go m.processRequest()
}
func (m *LifecycleMgr) RegisterNotifier(notifier MetadataNotifier) {
m.notifier = notifier
}
func (m *LifecycleMgr) Terminate() {
if m.killch != nil {
close(m.killch)
m.killch = nil
}
}
//
// This is the main event processing loop. It is important not to having any blocking
// call in this function (e.g. mutex). If this function is blocked, it will also
// block gometa event processing loop.
//
func (m *LifecycleMgr) OnNewRequest(fid string, request protocol.RequestMsg) {
req := &requestHolder{request: request, fid: fid}
op := c.OpCode(request.GetOpCode())
logging.Debugf("LifecycleMgr.OnNewRequest(): queuing new request. reqId %v opCode %v", request.GetReqId(), op)
if op == client.OPCODE_INDEXER_READY {
// Indexer bootstrap is done
m.indexerReady = true
// check for cleanup periodically in case cleanup fails or
// catching up with delete token from metakv
go m.janitor.run()
// allow background build to go through
go m.builder.run()
// detect if there is any change to indexer info (e.g. serverGroup)
go m.updator.run()
// allow request processing to go through
close(m.bootstraps)
} else if op == client.OPCODE_SERVICE_MAP {
// short cut the connection request by spawn its own go-routine
// This call does not change the state of the repository, so it
// is OK to shortcut.
go m.dispatchRequest(req, message.NewConcreteMsgFactory())
} else {
// if indexer is not yet ready, put them in the bootstrap queue so
// they can get processed. For client side, they will be queued
// up in the regular queue until indexer is ready.
if !m.indexerReady {
if op == client.OPCODE_UPDATE_INDEX_INST ||
op == client.OPCODE_DELETE_BUCKET ||
op == client.OPCODE_CLEANUP_INDEX ||
op == client.OPCODE_RESET_INDEX {
m.bootstraps <- req
return
}
}
// for create/drop/build index, always go to the client queue -- which will wait for
// indexer to be ready.
m.incomings <- req
}
}
func (m *LifecycleMgr) GetResponseChannel() <-chan c.Packet {
return (<-chan c.Packet)(m.outgoings)
}
func (m *LifecycleMgr) processRequest() {
logging.Debugf("LifecycleMgr.processRequest(): LifecycleMgr is ready to proces request")
factory := message.NewConcreteMsgFactory()
// process any requests form the boostrap phase. Once indexer is ready, this channel
// will be closed, and this go-routine will proceed to process regular message.
END_BOOTSTRAP:
for {
select {
case request, ok := <-m.bootstraps:
if ok {
m.dispatchRequest(request, factory)
} else {
logging.Debugf("LifecycleMgr.handleRequest(): closing bootstrap channel")
break END_BOOTSTRAP
}
case <-m.killch:
// server shutdown
logging.Debugf("LifecycleMgr.processRequest(): receive kill signal. Stop boostrap request processing.")
return
}
}
logging.Debugf("LifecycleMgr.processRequest(): indexer is ready to process new client request.")
// Indexer is ready and all bootstrap requests are processed. Proceed to handle regular messages.
for {
select {
case request, ok := <-m.incomings:
if ok {
// TOOD: deal with error
m.dispatchRequest(request, factory)
} else {
// server shutdown.
logging.Debugf("LifecycleMgr.handleRequest(): channel for receiving client request is closed. Terminate.")
return
}
case <-m.killch:
// server shutdown
logging.Debugf("LifecycleMgr.processRequest(): receive kill signal. Stop Client request processing.")
return
}
}
}
func (m *LifecycleMgr) dispatchRequest(request *requestHolder, factory *message.ConcreteMsgFactory) {
reqId := request.request.GetReqId()
op := c.OpCode(request.request.GetOpCode())
key := request.request.GetKey()
content := request.request.GetContent()
fid := request.fid
logging.Debugf("LifecycleMgr.dispatchRequest () : requestId %d, op %d, key %v", reqId, op, key)
var err error = nil
var result []byte = nil
switch op {
case client.OPCODE_CREATE_INDEX:
err = m.handleCreateIndexScheduledBuild(key, content, common.NewUserRequestContext())
case client.OPCODE_UPDATE_INDEX_INST:
err = m.handleTopologyChange(content)
case client.OPCODE_DROP_INDEX:
err = m.handleDeleteIndex(key, common.NewUserRequestContext())
case client.OPCODE_BUILD_INDEX:
err = m.handleBuildIndexes(content, common.NewUserRequestContext(), true)
case client.OPCODE_SERVICE_MAP:
result, err = m.handleServiceMap(content)
case client.OPCODE_DELETE_BUCKET:
err = m.handleDeleteBucket(key, content)
case client.OPCODE_CLEANUP_INDEX:
err = m.handleCleanupIndex(key)
case client.OPCODE_CLEANUP_DEFER_INDEX:
err = m.handleCleanupDeferIndexFromBucket(key)
case client.OPCODE_CREATE_INDEX_REBAL:
err = m.handleCreateIndexScheduledBuild(key, content, common.NewRebalanceRequestContext())
case client.OPCODE_BUILD_INDEX_REBAL:
err = m.handleBuildIndexes(content, common.NewRebalanceRequestContext(), false)
case client.OPCODE_DROP_INDEX_REBAL:
err = m.handleDeleteIndex(key, common.NewRebalanceRequestContext())
case client.OPCODE_BUILD_INDEX_RETRY:
err = m.handleBuildIndexes(content, common.NewUserRequestContext(), true)
case client.OPCODE_BROADCAST_STATS:
m.handleBroadcastStats(content)
case client.OPCODE_RESET_INDEX:
m.handleResetIndex(content)
case client.OPCODE_CONFIG_UPDATE:
m.handleConfigUpdate(content)
}
logging.Debugf("LifecycleMgr.dispatchRequest () : send response for requestId %d, op %d, len(result) %d", reqId, op, len(result))
if fid == "internal" {
return
}
if err == nil {
msg := factory.CreateResponse(fid, reqId, "", result)
m.outgoings <- msg
} else {
msg := factory.CreateResponse(fid, reqId, err.Error(), result)
m.outgoings <- msg
}
}
//////////////////////////////////////////////////////////////
// Lifecycle Mgr - handler functions
//////////////////////////////////////////////////////////////
func (m *LifecycleMgr) handleCreateIndex(key string, content []byte) error {
defn, err := common.UnmarshallIndexDefn(content)
if err != nil {
logging.Errorf("LifecycleMgr.handleCreateIndex() : createIndex fails. Unable to unmarshall index definition. Reason = %v", err)
return err
}
return m.CreateIndex(defn, false, nil)
}
func (m *LifecycleMgr) CreateIndex(defn *common.IndexDefn, scheduled bool,
reqCtx *common.MetadataRequestContext) error {
/*
if !defn.Deferred && !m.canBuildIndex(defn.Bucket) {
logging.Errorf("LifecycleMgr.handleCreateIndex() : Cannot create index %s.%s while another index is being built",
defn.Bucket, defn.Name)
return errors.New(fmt.Sprintf("Cannot create Index %s.%s while another index is being built.",
defn.Bucket, defn.Name))
}
*/
if common.GetBuildMode() != common.ENTERPRISE {
if defn.NumReplica != 0 {
err := errors.New("Index Replica not supported in non-Enterprise Edition")
logging.Errorf("LifecycleMgr.handleCreateIndex() : createIndex fails. Reason = %v", err)
return err
}
}
existDefn, err := m.repo.GetIndexDefnByName(defn.Bucket, defn.Name)
if err != nil {
logging.Errorf("LifecycleMgr.handleCreateIndex() : createIndex fails. Reason = %v", err)
return err
}
if existDefn != nil {
topology, err := m.repo.GetTopologyByBucket(existDefn.Bucket)
if err != nil {
logging.Errorf("LifecycleMgr.handleCreateIndex() : fails to find index instance. Reason = %v", err)
return err
}
// Allow index creation even if there is an existing index defn with the same name and bucket, as long
// as the index state is NIL (index instance non-existent) or DELETED state.
// If an index is in CREATED state, it will be repaired during indexer bootstrap:
// 1) For non-deferred index, it removed by the indexer.
// 2) For deferred index, it will be moved to READY state.
if topology != nil {
state, _ := topology.GetStatusByDefn(existDefn.DefnId)
if state != common.INDEX_STATE_NIL && state != common.INDEX_STATE_DELETED {
return errors.New(fmt.Sprintf("Index %s.%s already exists", defn.Bucket, defn.Name))
}
}
}
// Fetch bucket UUID. Note that this confirms that the bucket has existed, but it cannot confirm if the bucket
// is still existing in the cluster (due to race condition or network partitioned).
//
// Lifecycle manager is a singleton that ensures all metadata operation is serialized. Therefore, a
// call to verifyBucket() here will also make sure that all existing indexes belong to the same bucket UUID.
// To esnure verifyBucket can succeed, indexes from stale bucket must be cleaned up (eventually).
//
bucketUUID, err := m.verifyBucket(defn.Bucket)
if err != nil || bucketUUID == common.BUCKET_UUID_NIL {
if err == nil {
err = errors.New("Bucket not found")
}
return fmt.Errorf("Bucket does not exist or temporarily unavailable for creating new index."+
" Please retry the operation at a later time (err=%v).", err)
}
defn.BucketUUID = bucketUUID
//if no index_type has been specified
if strings.ToLower(string(defn.Using)) == "gsi" {
if common.GetStorageMode() != common.NOT_SET {
//if there is a storage mode, default to that
defn.Using = common.IndexType(common.GetStorageMode().String())
} else {
//default to plasma
defn.Using = common.PlasmaDB
}
} else {
if common.IsValidIndexType(string(defn.Using)) {
defn.Using = common.IndexType(strings.ToLower(string(defn.Using)))
} else {
err := fmt.Sprintf("Create Index fails. Reason = Unsupported Using Clause %v", string(defn.Using))
logging.Errorf("LifecycleMgr.handleCreateIndex: " + err)
return errors.New(err)
}
}
//
// Figure out the index instance id
var instId common.IndexInstId
if defn.InstId > 0 {
//use already supplied instance id (e.g. rebalance case)
instId = defn.InstId
} else {
// create index id
instId, err = common.NewIndexInstId()
if err != nil {
return err
}
}
defn.InstId = 0
// create replica id
replicaId := defn.ReplicaId
defn.ReplicaId = -1
// Create index definiton. It will fail if there is another index defintion of the same
// index defnition id.
if err := m.repo.CreateIndex(defn); err != nil {
logging.Errorf("LifecycleMgr.handleCreateIndex() : createIndex fails. Reason = %v", err)
return err
}
// Create index instance
// If there is any dangling index instance of the same index name and bucket, this will first
// remove the dangling index instance first.
// If indexer crash during creation of index instance, there could be a dangling index definition.
// It is possible to create index of the same name later, as long as the new index has a different
// definition id, since an index is consider valid only if it has both index definiton and index instance.
// So the dangling index definition is considered invalid.
if err := m.repo.addIndexToTopology(defn, instId, replicaId, !defn.Deferred && scheduled); err != nil {
logging.Errorf("LifecycleMgr.handleCreateIndex() : createIndex fails. Reason = %v", err)
m.repo.DropIndexById(defn.DefnId)
return err
}
// At this point, an index is created successfully with state=CREATED. If indexer crashes now,
// indexer will repair the index upon bootstrap (either cleanup or move to READY state).
// If indexer returns an error when creating index, then cleanup metadata now. During metadata cleanup,
// errors are ignored. This means the following:
// 1) Index Definition is not deleted due to error from metadata repository. The index will be repaired
// during indexer bootstrap or implicit dropIndex.
// 2) Index definition is deleted. This effectively "delete index".
if m.notifier != nil {
if err := m.notifier.OnIndexCreate(defn, instId, replicaId, reqCtx); err != nil {
logging.Errorf("LifecycleMgr.handleCreateIndex() : createIndex fails. Reason = %v", err)
m.DeleteIndex(defn.DefnId, false, nil)
return err
}
}
// If cannot move the index to READY state, then abort create index by cleaning up the metadata.
// Metadata cleanup is not atomic. The index is effectively "deleted" if it is able to drop
// the index definition from repository. If drop index is not successful during cleanup,
// the index will be repaired upon bootstrap or cleanup by janitor.
if err := m.updateIndexState(defn.Bucket, defn.DefnId, common.INDEX_STATE_READY); err != nil {
logging.Errorf("LifecycleMgr.handleCreateIndex() : createIndex fails. Reason = %v", err)
m.DeleteIndex(defn.DefnId, true, reqCtx)
return err
}
// Run index build
if !defn.Deferred {
if m.notifier != nil {
logging.Debugf("LifecycleMgr.handleCreateIndex() : start Index Build")
retryList, skipList, errList := m.BuildIndexes([]common.IndexDefnId{defn.DefnId}, reqCtx, false)
if len(retryList) != 0 {
return errors.New("Fail to build index. Index build will retry in background.")
}
if len(errList) != 0 {
logging.Errorf("LifecycleMgr.hanaleCreateIndex() : build index fails. Reason = %v", errList[0])
m.DeleteIndex(defn.DefnId, true, reqCtx)
return errList[0]
}
if len(skipList) != 0 {
logging.Errorf("LifecycleMgr.hanaleCreateIndex() : build index fails due to internal errors.")
m.DeleteIndex(defn.DefnId, true, reqCtx)
return errors.New("Fail to create index due to internal build error. Please retry the operation.")
}
}
}
logging.Debugf("LifecycleMgr.handleCreateIndex() : createIndex completes")
return nil
}
func (m *LifecycleMgr) handleBuildIndexes(content []byte, reqCtx *common.MetadataRequestContext, retry bool) error {
list, err := client.UnmarshallIndexIdList(content)
if err != nil {
logging.Errorf("LifecycleMgr.handleBuildIndexes() : buildIndex fails. Unable to unmarshall index list. Reason = %v", err)
return err
}
input := make([]common.IndexDefnId, len(list.DefnIds))
for i, id := range list.DefnIds {
input[i] = common.IndexDefnId(id)
}
retryList, skipList, errList := m.BuildIndexes(input, reqCtx, retry)
if len(retryList) != 0 || len(skipList) != 0 || len(errList) != 0 {
msg := "Build index fails."
if len(retryList) == 1 {
inst, err := m.FindLocalIndexInst(retryList[0].Bucket, retryList[0].DefnId)
if inst != nil && err == nil {
msg += fmt.Sprintf(" Index %v will retry building in the background for reason: %v.", retryList[0].Name, inst.Error)
}
}
if len(errList) == 1 {
msg += fmt.Sprintf(" %v.", errList[0])
}
if len(retryList) > 1 {
msg += " Some index will be retried building in the background."
}
if len(errList) > 1 {
msg += " Some index cannot be built due to errors."
}
if len(skipList) != 0 {
msg += " Some index cannot be built since it may not exist. Please check if the list of indexes are valid."
}
if len(errList) > 1 || len(retryList) > 1 {
msg += " For more details, please check index status."
}
return errors.New(msg)
}
return nil
}
func (m *LifecycleMgr) BuildIndexes(ids []common.IndexDefnId,
reqCtx *common.MetadataRequestContext, retry bool) ([]*common.IndexDefn, []common.IndexDefnId, []error) {
retryList := ([]*common.IndexDefn)(nil)
errList := ([]error)(nil)
skipList := ([]common.IndexDefnId)(nil)
instIdList := []common.IndexInstId(nil)
buckets := []string(nil)
inst2DefnMap := make(map[common.IndexInstId]common.IndexDefnId)
for _, id := range ids {
defn, err := m.repo.GetIndexDefnById(id)
if err != nil {
logging.Errorf("LifecycleMgr.handleBuildIndexes() : buildIndex fails. Reason = %v. Skip this index.", err)
skipList = append(skipList, id)
continue
}
if defn == nil {
logging.Warnf("LifecycleMgr.handleBuildIndexes() : index %v does not exist. Skip this index.", id)
skipList = append(skipList, id)
continue
}
inst, err := m.FindLocalIndexInst(defn.Bucket, id)
if inst == nil || err != nil {
logging.Errorf("LifecycleMgr.handleBuildIndexes: Fail to find index instance (%v, %v). Skip this index.", defn.Name, defn.Bucket)
skipList = append(skipList, id)
continue
}
if inst.State != uint32(common.INDEX_STATE_READY) {
logging.Warnf("LifecycleMgr.handleBuildIndexes: index instance (%v, %v) is not in ready state. Skip this index.", defn.Name, defn.Bucket)
continue
}
//Schedule the build
if err := m.SetScheduledFlag(defn.Bucket, id, true); err != nil {
msg := fmt.Sprintf("LifecycleMgr.handleBuildIndexes: Unable to set scheduled flag in index instance (%v, %v).", defn.Name, defn.Bucket)
logging.Warnf("%v Will try to build index now, but it will not be able to retry index build upon server restart.", msg)
}
// Reset any previous error
m.UpdateIndexInstance(defn.Bucket, id, common.INDEX_STATE_NIL, common.NIL_STREAM, "", nil, inst.RState)
found := false
for _, bucket := range buckets {
if bucket == defn.Bucket {
found = true
}
}
if !found {
buckets = append(buckets, defn.Bucket)
}
instIdList = append(instIdList, common.IndexInstId(inst.InstId))
inst2DefnMap[common.IndexInstId(inst.InstId)] = defn.DefnId
}
if m.notifier != nil && len(instIdList) != 0 {
if errMap := m.notifier.OnIndexBuild(instIdList, buckets, reqCtx); len(errMap) != 0 {
logging.Errorf("LifecycleMgr.hanaleBuildIndexes() : buildIndex fails. Reason = %v", errMap)
for instId, build_err := range errMap {
defnId, ok := inst2DefnMap[instId]
if !ok {
logging.Warnf("LifecycleMgr.handleBuildIndexes() : Cannot find index defn for index inst %v when processing build error.")
continue
}
defn, err := m.repo.GetIndexDefnById(defnId)
if err != nil || defn == nil {
logging.Warnf("LifecycleMgr.handleBuildIndexes() : Cannot find index defn for index inst %v when processing build error.")
continue
}
inst, err := m.FindLocalIndexInst(defn.Bucket, defnId)
if inst != nil && err == nil {
if m.canRetryError(inst, build_err, retry) {
build_err = errors.New(fmt.Sprintf("%v. Indexer will retry building index at later time.", build_err.Error()))
}
m.UpdateIndexInstance(defn.Bucket, defnId, common.INDEX_STATE_NIL, common.NIL_STREAM, build_err.Error(), nil, inst.RState)
} else {
logging.Infof("LifecycleMgr.handleBuildIndexes() : Fail to persist error in index instance (%v, %v).",
defn.Bucket, defn.Name)
}
if m.canRetryError(inst, build_err, retry) {
logging.Infof("LifecycleMgr.handleBuildIndexes() : Encounter build error. Retry building index (%v, %v) at later time.",
defn.Bucket, defn.Name)
if inst != nil && !inst.Scheduled {
if err := m.SetScheduledFlag(defn.Bucket, defnId, true); err != nil {
msg := fmt.Sprintf("LifecycleMgr.handleBuildIndexes: Unable to set scheduled flag in index instance (%v, %v).",
defn.Name, defn.Bucket)
logging.Warnf("%v Will try to build index now, but it will not be able to retry index build upon server restart.", msg)
}
}
retryList = append(retryList, defn)
} else {
errList = append(errList, errors.New(fmt.Sprintf("Index %v fails to build for reason: %v", defn.Name, build_err)))
}
}
// schedule index for retry
for _, defn := range retryList {
m.builder.notifych <- defn
}
}
}
logging.Debugf("LifecycleMgr.handleBuildIndexes() : buildIndex completes")
return retryList, skipList, errList
}
func (m *LifecycleMgr) handleDeleteIndex(key string, reqCtx *common.MetadataRequestContext) error {
id, err := indexDefnId(key)
if err != nil {
logging.Errorf("LifecycleMgr.handleDeleteIndex() : deleteIndex fails. Reason = %v", err)
return err
}
return m.DeleteIndex(id, true, reqCtx)
}
func (m *LifecycleMgr) handleCleanupIndex(key string) error {
id, err := indexDefnId(key)
if err != nil {
logging.Errorf("LifecycleMgr.handleCleanupIndex() : deleteIndex fails. Reason = %v", err)
return err
}
return m.DeleteIndex(id, false, nil)
}
func (m *LifecycleMgr) DeleteIndex(id common.IndexDefnId, notify bool,
reqCtx *common.MetadataRequestContext) error {
defn, err := m.repo.GetIndexDefnById(id)
if err != nil {
logging.Errorf("LifecycleMgr.DeleteIndex() : drop index fails for index defn %v. Error = %v.", id, err)
return err
}
if defn == nil {
logging.Infof("LifecycleMgr.DeleteIndex() : index %v does not exist.", id)
return nil
}
// updateIndexState will not return an error if there is no index inst
if err := m.updateIndexState(defn.Bucket, defn.DefnId, common.INDEX_STATE_DELETED); err != nil {
logging.Errorf("LifecycleMgr.handleDeleteIndex() : deleteIndex fails. Reason = %v", err)
return err
}
if notify && m.notifier != nil {
inst, err := m.FindLocalIndexInst(defn.Bucket, id)
if err != nil {
// Cannot read bucket topology. Likely a transient error. But without index inst, we cannot
// proceed without letting indexer to clean up.
logging.Warnf("LifecycleMgr.handleDeleteIndex() : Encounter error during delete index. Error = %v", err)
return err
}
// If we cannot find the local index inst, then skip notifying the indexer, but proceed to delete the
// index definition. Lifecycle manager create index definition before index instance. It also delete
// index defintion before deleting index instance. So if an index definition exists, but there is no
// index instance, then it means the index has never succesfully created.
//
if inst != nil {
// Can call index delete again even after indexer has cleaned up -- if indexer crashes after
// this point but before it can delete the index definition.
if err := m.notifier.OnIndexDelete(common.IndexInstId(inst.InstId), defn.Bucket, reqCtx); err != nil {
// Do not remove index defnition if indexer is unable to delete the index. This is to ensure the
// the client can call DeleteIndex again and free up indexer resource.
indexerErr, ok := err.(*common.IndexerError)
if ok && indexerErr.Code != common.IndexNotExist {
logging.Errorf("LifecycleMgr.handleDeleteIndex(): Encounter error when dropping index: %v. Drop index will retry in background",
indexerErr.Reason)
return nil
} else if !strings.Contains(err.Error(), "Unknown Index Instance") {
logging.Errorf("LifecycleMgr.handleDeleteIndex(): Encounter error when dropping index: %v. Drop index will retry in background",
err.Error())
return nil
}
}
}
}
m.repo.DropIndexById(defn.DefnId)
// If indexer crashes at this point, there is a chance topology may leave a orphan index
// instance. But this index will consider invalid (state=DELETED + no index definition).
m.repo.deleteIndexFromTopology(defn.Bucket, defn.DefnId)
logging.Debugf("LifecycleMgr.DeleteIndex() : deleted index: bucket : %v bucket uuid %v name %v",
defn.Bucket, defn.BucketUUID, defn.Name)
return nil
}
func (m *LifecycleMgr) handleTopologyChange(content []byte) error {
change := new(topologyChange)
if err := json.Unmarshal(content, change); err != nil {
return err
}
// Find index defnition
defn, err := m.repo.GetIndexDefnById(common.IndexDefnId(change.DefnId))
if err != nil {
return err
}
if defn == nil {
return nil
}
// Find out the current index instance state
inst, err := m.FindLocalIndexInst(change.Bucket, common.IndexDefnId(change.DefnId))
if err != nil {
return err
}
if inst == nil {
return nil
}
state := inst.State
scheduled := inst.Scheduled
// update the index instance
if err := m.UpdateIndexInstance(change.Bucket, common.IndexDefnId(change.DefnId), common.IndexState(change.State),
common.StreamId(change.StreamId), change.Error, change.BuildTime, change.RState); err != nil {
return err
}
// If the indexer changes the instance state changes from CREATED to READY, then send the index to the builder.
// Lifecycle manager will not come to this code path when changing index state from CREATED to READY.
if common.IndexState(state) == common.INDEX_STATE_CREATED &&
common.IndexState(change.State) == common.INDEX_STATE_READY {
if scheduled {
m.builder.notifych <- defn
}
}
return nil
}
func (m *LifecycleMgr) handleDeleteBucket(bucket string, content []byte) error {
result := error(nil)
if len(content) == 0 {
return errors.New("invalid argument")
}
streamId := common.StreamId(content[0])
topology, err := m.repo.GetTopologyByBucket(bucket)
if err == nil && topology != nil {
/*
// if there is an error getting the UUID, this means that
// the node is not able to connect to pool service in order
// to fetch the bucket UUID. Return an error and skip.
uuid, err := m.getBucketUUID(bucket)
if err != nil {
logging.Errorf("LifecycleMgr.handleDeleteBucket() : Encounter when connecting to pool service = %v", err)
return err
}
*/
// At this point, we are able to connect to pool service. If pool
// does not contain the bucket, then we delete all index defn in
// the bucket. Otherwise, delete index defn that does not have the
// same bucket UUID. Note that any other create index request will
// be blocked while this call is run.
definitions := make([]IndexDefnDistribution, len(topology.Definitions))
copy(definitions, topology.Definitions)
for _, defnRef := range definitions {
if defn, err := m.repo.GetIndexDefnById(common.IndexDefnId(defnRef.DefnId)); err == nil && defn != nil {
logging.Debugf("LifecycleMgr.handleDeleteBucket() : index instance: id %v, streamId %v.",
defn.DefnId, defnRef.Instances[0].StreamId)
// delete index defn from the bucket if bucket uuid is not specified or
// index does *not* belong to bucket uuid
if /* (uuid == common.BUCKET_UUID_NIL || defn.BucketUUID != uuid) && */
streamId == common.NIL_STREAM || (common.StreamId(defnRef.Instances[0].StreamId) == streamId ||
common.StreamId(defnRef.Instances[0].StreamId) == common.NIL_STREAM) {
if err := m.DeleteIndex(common.IndexDefnId(defn.DefnId), false, nil); err != nil {
result = err
}
}
} else {
logging.Debugf("LifecycleMgr.handleDeleteBucket() : Cannot find index instance %v. Skip.", defnRef.DefnId)
}
}
} else if err != fdb.FDB_RESULT_KEY_NOT_FOUND {
result = err
}
return result
}
//
// Cleanup any defer index from invalid bucket.
//
func (m *LifecycleMgr) handleCleanupDeferIndexFromBucket(bucket string) error {
// Get bucket UUID. bucket uuid could be BUCKET_UUID_NIL for non-existent bucket.
currentUUID, err := m.getBucketUUID(bucket)
if err != nil {
// If err != nil, then cannot connect to fetch bucket info. Do not attempt to delete index.
return nil
}
topology, err := m.repo.GetTopologyByBucket(bucket)
if err == nil && topology != nil {
hasValidActiveIndex := false
for _, defnRef := range topology.Definitions {
// Check for index with active stream. If there is any index with active stream, all
// index in the bucket will be deleted when the stream is closed due to bucket delete.
if defnRef.Instances[0].State != uint32(common.INDEX_STATE_DELETED) &&
common.StreamId(defnRef.Instances[0].StreamId) != common.NIL_STREAM {
hasValidActiveIndex = true
break
}
}
if !hasValidActiveIndex {
for _, defnRef := range topology.Definitions {
if defn, err := m.repo.GetIndexDefnById(common.IndexDefnId(defnRef.DefnId)); err == nil && defn != nil {
if defn.BucketUUID != currentUUID && defn.Deferred &&
defnRef.Instances[0].State != uint32(common.INDEX_STATE_DELETED) &&
common.StreamId(defnRef.Instances[0].StreamId) == common.NIL_STREAM {
if err := m.DeleteIndex(common.IndexDefnId(defn.DefnId), true, common.NewUserRequestContext()); err != nil {
return err
}
}
}
}
}
}
return nil
}
func (m *LifecycleMgr) handleCreateIndexScheduledBuild(key string, content []byte,
reqCtx *common.MetadataRequestContext) error {
defn, err := common.UnmarshallIndexDefn(content)
if err != nil {
logging.Errorf("LifecycleMgr.handleCreateIndexScheduledBuild() : createIndex fails. Unable to unmarshall index definition. Reason = %v", err)
return err
}
// Create index with the scheduled flag.
return m.CreateIndex(defn, true, reqCtx)
}
func (m *LifecycleMgr) handleBroadcastStats(buf []byte) {
if len(buf) > 0 {
stats := make(common.Statistics)
if err := json.Unmarshal(buf, &stats); err == nil {
filtered := make(common.Statistics)
for key, value := range stats {
if strings.Contains(key, "num_docs_pending") ||
strings.Contains(key, "num_docs_queued") ||
strings.Contains(key, "last_rollback_time") ||
strings.Contains(key, "progress_stat_time") {
filtered[key] = value
}
}
idxStats := &client.IndexStats{Stats: filtered}
if err := m.repo.BroadcastIndexStats(idxStats); err != nil {
logging.Errorf("lifecycleMgr: fail to send index stats. Error = %v", err)
}
} else {
logging.Errorf("lifecycleMgr: fail to marshall index stats. Error = %v", err)
}
}
}
func (m *LifecycleMgr) handleResetIndex(content []byte) error {
defn, err := common.UnmarshallIndexDefn(content)
if err != nil {
logging.Errorf("LifecycleMgr.handleResetIndex() : Unable to unmarshall index definition. Reason = %v", err)
return err
}
oldDefn, err := m.repo.GetIndexDefnById(defn.DefnId)
if err != nil {
logging.Warnf("LifecycleMgr.handleResetIndex(): Fail to find index definition (%v, %v).", defn.DefnId, defn.Bucket)
return err
}
oldStorageMode := ""
if oldDefn != nil {
oldStorageMode = string(oldDefn.Using)
}
//
// Change storage mode in index definition
//
if err := m.repo.UpdateIndex(defn); err != nil {
logging.Errorf("LifecycleMgr.handleResetIndex() : Fails to upgrade index (%v, %v). Reason = %v", defn.Bucket, defn.Name, err)
return err
}
//
// Restore index instance (as if index is created again)
//
topology, err := m.repo.GetTopologyByBucket(defn.Bucket)
if err != nil {
logging.Errorf("LifecycleMgr.handleResetIndex() : Fails to upgrade index (%v, %v). Reason = %v", defn.Bucket, defn.Name, err)
return err
}
inst, err := m.FindLocalIndexInst(defn.Bucket, defn.DefnId)
if err != nil {
logging.Errorf("LifecycleMgr.handleResetIndex() : Fails to upgrade index (%v, %v). Reason = %v", defn.Bucket, defn.Name, err)
return err
}
if inst == nil {
logging.Errorf("LifecycleMgr.handleResetIndex() : Fails to upgrade index (%v, %v). Index instance does not exist.", defn.Bucket, defn.Name)
return nil
}
if common.IndexState(inst.State) == common.INDEX_STATE_INITIAL ||
common.IndexState(inst.State) == common.INDEX_STATE_CATCHUP ||
common.IndexState(inst.State) == common.INDEX_STATE_ACTIVE {
topology.UpdateScheduledFlagForIndexInstByDefn(defn.DefnId, true)
}
topology.UpdateOldStorageModeForIndexInstByDefn(defn.DefnId, oldStorageMode)
topology.UpdateStorageModeForIndexInstByDefn(defn.DefnId, string(defn.Using))
topology.UpdateStateForIndexInstByDefn(defn.DefnId, common.INDEX_STATE_READY)
topology.SetErrorForIndexInstByDefn(defn.DefnId, "")
topology.UpdateStreamForIndexInstByDefn(defn.DefnId, common.NIL_STREAM)