/
metadata_provider.go
5869 lines (4756 loc) · 167 KB
/
metadata_provider.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 client
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"math"
"math/rand"
"net"
"net/http"
"reflect"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/couchbase/gometa/common"
gometaL "github.com/couchbase/gometa/log"
"github.com/couchbase/gometa/message"
"github.com/couchbase/gometa/protocol"
c "github.com/couchbase/indexing/secondary/common"
"github.com/couchbase/indexing/secondary/common/queryutil"
"github.com/couchbase/indexing/secondary/logging"
mc "github.com/couchbase/indexing/secondary/manager/common"
"github.com/couchbase/indexing/secondary/planner"
"github.com/couchbase/indexing/secondary/security"
"github.com/couchbase/query/expression"
"github.com/couchbase/query/expression/parser"
)
// TODO:
// 1) cleanup on create/build index fails for replica
///////////////////////////////////////////////////////
// Interface
///////////////////////////////////////////////////////
type Settings interface {
NumReplica() int32
NumPartition() int32
StorageMode() string
UsePlanner() bool
AllowPartialQuorum() bool
AllowScheduleCreate() bool
}
///////////////////////////////////////////////////////
// Type Definition
///////////////////////////////////////////////////////
type MetadataProvider struct {
clusterUrl string
providerId string
watchers map[c.IndexerId]*watcher
pendings map[c.IndexerId]chan bool
timeout int64
repo *metadataRepo
mutex sync.RWMutex
watcherCount int
metaNotifyCh chan bool
numExpectedWatcher int32
numFailedNode int32
numUnhealthyNode int32
numAddNode int32
numWatcher int32
settings Settings
indexerVersion uint64
clusterVersion uint64
statsNotifyCh chan map[c.IndexInstId]map[c.PartitionId]c.Statistics
}
//
// 1) Each index definition has a logical identifer (IndexDefnId).
// 2) The logical definition can have multiple instances or replica.
// Each index instance is identified by IndexInstId.
// 3) Each instance may reside in different nodes for HA or
// load balancing purpose.
// 4) Each instance can have different version. Many versions can
// co-exist in the cluster at a given time, but only one version can be
// active (State == active) and valid (RState = active).
// 5) In steady state, there should be only one version for each instance, but
// during rebalance, index can be moved from one node to another, with
// multiple versions representing the same index instance being "in-transit"
// (occupying both source and destination nodes during rebalancing).
// 6) A definition can have multiple physical identical copies, residing
// along with each instance. The physical copies will have the same
// definition id as well as definition/structure.
// 7) An observer (metadataRepo) can only determine the "consistent" state of
// metadata with a full participation. Full participation means that the obsever
// see the local metadata state of each indexer node.
// 8) At full participation, if an index definiton does not have any instance, the
// index definition is considered as deleted. The side effect is an index
// could be implicitly dropped if it loses all its replica.
// 9) For partitioned index, each index instance will be distributed across many
// nodes. An index instance is well-formed if the observer can account for
// all the partitions for the instance.
// 10) For partitioned index, each partition will have its own version. Each
// partition will be rebalanced separately.
//
type metadataRepo struct {
provider *MetadataProvider
definitions map[c.IndexDefnId]*c.IndexDefn
instances map[c.IndexDefnId]map[c.IndexInstId]map[c.PartitionId]map[uint64]*mc.IndexInstDistribution
indices map[c.IndexDefnId]*IndexMetadata
topology map[c.IndexerId]map[c.IndexDefnId]bool
version uint64
mutex sync.RWMutex
notifiers map[c.IndexDefnId]*event
}
type watcher struct {
provider *MetadataProvider
leaderAddr string
factory protocol.MsgFactory
pendings map[common.Txnid]protocol.LogEntryMsg
killch chan bool
alivech chan bool
pingch chan bool
mutex sync.Mutex
timerKillCh chan bool
isClosed bool
serviceMap *ServiceMap
lastSeenTxid common.Txnid
incomingReqs chan *protocol.RequestHandle
pendingReqs map[uint64]*protocol.RequestHandle // key : request id
loggedReqs map[common.Txnid]*protocol.RequestHandle
clientStats IndexStats2Holder
}
// With partitioning, index instance is distributed among indexer nodes.
// IndexMetadata can contain instances that do not have all the partitions,
// even though each instance is eventually consistent if there is no network
// partition.
type IndexMetadata struct {
Definition *c.IndexDefn
Instances []*InstanceDefn
InstsInRebalance []*InstanceDefn
State c.IndexState
Error string
Scheduled bool
ScheduleFailed bool
}
type InstanceDefn struct {
DefnId c.IndexDefnId
InstId c.IndexInstId
State c.IndexState
Error string
IndexerId map[c.PartitionId]c.IndexerId
Versions map[c.PartitionId]uint64
RState uint32
ReplicaId uint64
StorageMode string
NumPartitions uint32
}
type event struct {
defnId c.IndexDefnId
status []c.IndexState
topology map[int]map[c.PartitionId]c.IndexerId
notifyCh chan error
}
type IndexerStatus struct {
Adminport string
Connected bool
}
type watcherCallback func(string, c.IndexerId, c.IndexerId)
var REQUEST_CHANNEL_COUNT = 1000
var VALID_PARAM_NAMES = []string{"nodes", "defer_build", "retain_deleted_xattr",
"num_partition", "num_replica", "docKeySize", "secKeySize", "arrSize", "numDoc", "residentRatio"}
var ErrWaitScheduleTimeout = fmt.Errorf("Timeout in checking for schedule create token.")
///////////////////////////////////////////////////////
// Public function : MetadataProvider
///////////////////////////////////////////////////////
func NewMetadataProvider(cluster string, providerId string, changeCh chan bool, statsCh chan map[c.IndexInstId]map[c.PartitionId]c.Statistics,
settings Settings) (s *MetadataProvider, err error) {
s = new(MetadataProvider)
s.clusterUrl = cluster
s.watchers = make(map[c.IndexerId]*watcher)
s.pendings = make(map[c.IndexerId]chan bool)
s.repo = newMetadataRepo(s)
s.timeout = int64(time.Second) * 120
s.metaNotifyCh = changeCh
s.statsNotifyCh = statsCh
s.settings = settings
s.providerId = providerId
if err != nil {
return nil, err
}
logging.Debugf("MetadataProvider.NewMetadataProvider(): MetadataProvider follower ID %s", s.providerId)
cinfo, err := c.FetchNewClusterInfoCache(cluster, c.DEFAULT_POOL, "NewMetaDataProvider")
if err != nil {
return nil, err
}
s.clusterVersion = cinfo.GetClusterVersion()
return s, nil
}
func (o *MetadataProvider) SetTimeout(timeout int64) {
o.timeout = timeout
}
func (o *MetadataProvider) SetClusterStatus(numExpectedWatcher int, numFailedNode int, numUnhealthyNode int, numAddNode int) {
if (numExpectedWatcher > -1 && int32(numExpectedWatcher) != atomic.LoadInt32(&o.numExpectedWatcher)) ||
(numFailedNode > -1 && int32(numFailedNode) != atomic.LoadInt32(&o.numFailedNode)) ||
(numUnhealthyNode > -1 && int32(numUnhealthyNode) != atomic.LoadInt32(&o.numUnhealthyNode)) ||
(numAddNode > -1 && int32(numAddNode) != atomic.LoadInt32(&o.numAddNode)) {
logging.Infof("MetadataProvider.SetClusterStatus(): healthy nodes %v failed node %v unhealthy node %v add node %v",
numExpectedWatcher, numFailedNode, numUnhealthyNode, numAddNode)
}
if numExpectedWatcher != -1 {
atomic.StoreInt32(&o.numExpectedWatcher, int32(numExpectedWatcher))
}
if numFailedNode != -1 {
atomic.StoreInt32(&o.numFailedNode, int32(numFailedNode))
}
if numUnhealthyNode != -1 {
atomic.StoreInt32(&o.numUnhealthyNode, int32(numUnhealthyNode))
}
if numAddNode != -1 {
atomic.StoreInt32(&o.numAddNode, int32(numAddNode))
}
}
func (o *MetadataProvider) GetMetadataVersion() uint64 {
return o.repo.getVersion()
}
func (o *MetadataProvider) IncrementMetadataVersion() {
o.repo.incrementVersion()
}
func (o *MetadataProvider) WatchMetadata(indexAdminPort string, callback watcherCallback, numExpectedWatcher int) c.IndexerId {
o.mutex.Lock()
defer o.mutex.Unlock()
logging.Infof("MetadataProvider.WatchMetadata(): indexer %v", indexAdminPort)
atomic.StoreInt32(&o.numExpectedWatcher, int32(numExpectedWatcher))
for _, watcher := range o.watchers {
if watcher.getAdminAddr() == indexAdminPort {
return watcher.getIndexerId()
}
}
// start a watcher to the indexer admin
watcher, readych := o.startWatcher(indexAdminPort)
// wait for indexer to connect
success, _ := watcher.waitForReady(readych, 1000, nil)
if success {
// if successfully connected, retrieve indexerId
success, _ = watcher.notifyReady(indexAdminPort, 0, nil)
if success {
logging.Infof("WatchMetadata(): successfully reach indexer at %v.", indexAdminPort)
// watcher succesfully initialized, add it to MetadataProvider
o.addWatcherNoLock(watcher, c.INDEXER_ID_NIL)
return watcher.getIndexerId()
} else {
// watcher is ready, but no able to read indexerId
readych = nil
}
}
logging.Infof("WatchMetadata(): unable to reach indexer at %v. Retry in background.", indexAdminPort)
// watcher is not connected to indexer or fail to get indexer id,
// create a temporary index id
o.watcherCount = o.watcherCount + 1
tempIndexerId := c.IndexerId(fmt.Sprintf("%v_Indexer_Id_%d", indexAdminPort, o.watcherCount))
killch := make(chan bool, 1)
o.pendings[tempIndexerId] = killch
// retry it in the background. Return a temporary indexerId for book-keeping.
go o.retryHelper(watcher, readych, indexAdminPort, tempIndexerId, killch, callback)
return tempIndexerId
}
func (o *MetadataProvider) UnwatchMetadata(indexerId c.IndexerId, numExpectedWatcher int) {
o.mutex.Lock()
defer o.mutex.Unlock()
logging.Infof("UnwatchMetadata(): indexer %v", indexerId)
defer logging.Infof("UnwatchMetadata(): finish for indexer %v", indexerId)
atomic.StoreInt32(&o.numExpectedWatcher, int32(numExpectedWatcher))
watcher, ok := o.watchers[indexerId]
if !ok {
killch, ok := o.pendings[indexerId]
if ok {
delete(o.pendings, indexerId)
// notify retryHelper to terminate. This is for
// watcher that is still waiting to complete
// handshake with indexer.
killch <- true
}
return
}
delete(o.watchers, indexerId)
if watcher != nil {
// must update the number of watcher before cleanupIndices
atomic.StoreInt32(&o.numWatcher, int32(len(o.watchers)))
watcher.close()
watcher.cleanupIndices(o.repo)
}
// increment version when unwatch metadata
o.repo.incrementVersion()
}
//
// Since this function holds the lock, it ensure that
// neither WatchMetadata or UnwatchMetadata is being called.
// It also ensure safety of calling CheckIndexerStatusNoLock.
//
func (o *MetadataProvider) CheckIndexerStatus() []IndexerStatus {
o.mutex.Lock()
defer o.mutex.Unlock()
return o.CheckIndexerStatusNoLock()
}
//
// It is important the caller of this function holds a lock to ensure
// this function is mutual exclusive.
//
func (o *MetadataProvider) CheckIndexerStatusNoLock() []IndexerStatus {
status := make([]IndexerStatus, len(o.watchers))
i := 0
for _, watcher := range o.watchers {
status[i].Adminport = watcher.leaderAddr
status[i].Connected = watcher.isAliveNoLock()
logging.Infof("MetadataProvider.CheckIndexerStatus(): adminport=%v connected=%v", status[i].Adminport, status[i].Connected)
i++
}
return status
}
// scope, collection params are ignored for now
func (o *MetadataProvider) CreateIndexWithPlan(
name, bucket, scope, collection, using, exprType, whereExpr string,
secExprs []string, desc []bool, isPrimary bool,
scheme c.PartitionScheme, partitionKeys []string,
plan map[string]interface{}) (c.IndexDefnId, error, bool) {
// FindIndexByName will only return valid index
if o.findIndexByName(name, bucket, scope, collection) != nil {
return c.IndexDefnId(0), errors.New(fmt.Sprintf("Index %s already exists.", name)), false
}
// Create index definition
idxDefn, err, retry := o.PrepareIndexDefn(name, bucket, scope, collection,
using, exprType, whereExpr, secExprs, desc, isPrimary, scheme,
partitionKeys, plan)
if err != nil {
return c.IndexDefnId(0), err, retry
}
clusterVersion := o.GetClusterVersion()
if clusterVersion < c.INDEXER_70_VERSION {
if collection != c.DEFAULT_COLLECTION || scope != c.DEFAULT_SCOPE {
err := errors.New("Fails to create index. Creation of an index on non-default collection" +
"is enabled only after cluster is fully upgraded and there is no failed node.")
return c.IndexDefnId(0), err, false
}
}
if clusterVersion < c.INDEXER_55_VERSION || (!o.settings.UsePlanner() && !c.IsPartitioned(idxDefn.PartitionScheme)) {
if err := o.createIndex(idxDefn, plan); err != nil {
return c.IndexDefnId(0), err, false
}
} else {
scheduleOnFailure := o.settings.AllowScheduleCreate()
if err := o.recoverableCreateIndex(idxDefn, plan, scheduleOnFailure); err != nil {
return c.IndexDefnId(0), err, false
}
}
return idxDefn.DefnId, nil, false
}
//
// This function makes a call to create index using new protocol (vulcan).
//
func (o *MetadataProvider) makePrepareIndexRequest(defnId c.IndexDefnId, name string,
bucket, scope, collection string, nodes []string, partitionScheme c.PartitionScheme,
numReplica int, checkDuplicateIndex bool) (map[c.IndexerId]int, error, bool) {
// do a preliminary check
watchers, err, _ := o.findWatchersWithRetry(nodes, numReplica, c.IsPartitioned(partitionScheme), false)
if err != nil {
return nil, err, false
}
if len(nodes) == 0 {
// Get the full list of healthy watcher. Unhealthy watcher could be unwatched.
watchers = o.getAllAvailWatchers()
}
request := &PrepareCreateRequest{
Op: PREPARE,
DefnId: defnId,
RequesterId: o.providerId,
Timeout: int64(time.Duration(3) * time.Minute),
}
if checkDuplicateIndex {
request.Bucket = bucket
request.Name = name
request.Scope = scope
request.Collection = collection
}
requestMsg, err := MarshallPrepareCreateRequest(request)
if err != nil {
return nil, err, false
}
var wg *sync.WaitGroup = new(sync.WaitGroup)
var accept uint32
var schedule uint32
var duplicate uint32
watcherMap := make(map[c.IndexerId]int)
// Send prepare command to healthy watchers. During network partitioning, if there are 2 concurrent create requests
// from 2 different cbq nodes:
// 1) If both cbq nodes see overlapping indexers, then one of them will succeed.
// 2) If the cbq nodes see a non-overlapping subset of indexers, then both will succeed. But for each cbq node, the
// planner will only use its subset of nodes for planning.
//
key := fmt.Sprintf("%d", defnId)
for _, w := range watchers {
wg.Add(1)
watcherMap[w.getIndexerId()] = 1
go func(w *watcher) {
logging.Infof("send prepare create request to watcher %v", w.getAdminAddr())
defer wg.Done()
// if there is a network partitioning between the metadata provider and indexer, makeRequest would not return until timeout.
content, err := w.makeRequest(OPCODE_PREPARE_CREATE_INDEX, key, requestMsg)
if err != nil {
logging.Errorf("Fail to process prepare request on %v. Error: %v", w.getAdminAddr(), err)
return
}
response, err := UnmarshallPrepareCreateResponse(content)
if err != nil {
logging.Errorf("Fail to process prepare request on %v. Error: %v", w.getAdminAddr(), err)
return
}
if response != nil && response.Accept {
logging.Infof("Indexer %v accept prepare request. Index (%v, %v, %v, %v)",
w.getAdminAddr(), bucket, scope, collection, name)
atomic.AddUint32(&accept, 1)
return
}
if response != nil {
logging.Infof("Indexer %v rejected request for index (%v, %v, %v, %v) with reason %v",
w.getAdminAddr(), bucket, scope, collection, name, response.Msg)
if response.Msg == RespAnotherIndexCreation {
atomic.AddUint32(&schedule, 1)
return
}
if response.Msg == RespDuplicateIndex {
atomic.AddUint32(&duplicate, 1)
return
}
}
}(w)
}
wg.Wait()
if accept < uint32(len(watcherMap)) {
if atomic.LoadUint32(&duplicate) > 0 {
errStr := "Create index cannot proceed due to presence of duplicate index name."
return watcherMap, errors.New(errStr), false
} else if (atomic.LoadUint32(&schedule) + accept) < uint32(len(watcherMap)) {
errStr := "Create index or Alter replica cannot proceed due to rebalance in progress, " +
"network partition, node failover or indexer failure."
return watcherMap, errors.New(errStr), false
} else {
errStr := "Create index or Alter replica cannot proceed due to another concurrent create index request."
return watcherMap, errors.New(errStr), true
}
}
return watcherMap, nil, false
}
//
// This function clean up prepare index request
//
func (o *MetadataProvider) cancelPrepareIndexRequest(defnId c.IndexDefnId, watcherMap map[c.IndexerId]int) {
request := &PrepareCreateRequest{
Op: CANCEL_PREPARE,
DefnId: defnId,
RequesterId: o.providerId,
}
content, err := MarshallPrepareCreateRequest(request)
if err != nil {
logging.Errorf("Fail to cancel prepare index creation on indexerId. Error: %v", err)
return
}
key := fmt.Sprintf("%d", defnId)
for indexerId, _ := range watcherMap {
go func(indexerId c.IndexerId) {
watcher, err := o.findWatcherByIndexerId(indexerId)
if err != nil {
logging.Errorf("Fail to cancel prepare index creation. Cannot find watcher for indexerId %v. Error: %v", indexerId, err)
return
}
logging.Infof("send cancel create request to watcher %v", watcher.getAdminAddr())
_, err = watcher.makeRequest(OPCODE_PREPARE_CREATE_INDEX, key, content)
if err != nil {
logging.Errorf("Fail to cancel prepare index creation on %v. Error: %v", watcher.getAdminAddr(), err)
return
}
}(indexerId)
}
}
//
// This function makes a call to create index using new protocol (vulcan).
//
func (o *MetadataProvider) makeCommitIndexRequest(op CommitCreateRequestOp, idxDefn *c.IndexDefn, requestId uint64,
definitions map[c.IndexerId][]c.IndexDefn, watcherMap map[c.IndexerId]int) error {
request := &CommitCreateRequest{
Op: op,
DefnId: idxDefn.DefnId,
RequesterId: o.providerId,
Definitions: definitions,
RequestId: requestId,
}
requestMsg, err := MarshallCommitCreateRequest(request)
if err != nil {
return fmt.Errorf("Unable to send commit request. Reason: %v", err)
}
var mutex sync.Mutex
var cond *sync.Cond = sync.NewCond(&mutex)
var accept bool
var count int32
errorMap := make(map[string]bool)
key := fmt.Sprintf("%d", idxDefn.DefnId)
for indexerId, _ := range watcherMap {
w, err := o.findWatcherByIndexerId(indexerId)
if err != nil {
logging.Errorf("Fail to cancel prepare index creation. Cannot find watcher for indexerId %v", indexerId)
continue
}
atomic.AddInt32(&count, 1)
go func(w *watcher) {
defer func() {
atomic.AddInt32(&count, -1)
cond.L.Lock()
defer cond.L.Unlock()
cond.Signal()
}()
logging.Infof("send commit create request to watcher %v", w.getAdminAddr())
// if there is a network partitioning between the metadata provider and indexer,
// makeRequest would not return until timeout.
content, err := w.makeRequest(OPCODE_COMMIT_CREATE_INDEX, key, requestMsg)
if err != nil {
logging.Errorf("Encountered error during create index. Error: %v", err)
mutex.Lock()
errorMap[err.Error()] = true
mutex.Unlock()
}
response, err := UnmarshallCommitCreateResponse(content)
if err != nil {
logging.Errorf("Encountered error during create index. Error: %v", err)
}
mutex.Lock()
if response != nil {
accept = response.Accept || accept
}
mutex.Unlock()
}(w)
}
// wait for result
var success bool
for {
cond.L.Lock()
cond.Wait()
success = accept
cond.L.Unlock()
if success {
break
}
if atomic.LoadInt32(&count) == 0 {
break
}
}
var createErr error
if len(errorMap) != 0 {
var errStr string
for errStr2, _ := range errorMap {
errStr += errStr2 + "\n"
}
createErr = errors.New(errStr)
}
//result is ready
if success {
if createErr != nil {
return fmt.Errorf("Encountered transient error. Index creation will be retried in background. Error: %v", createErr)
}
return nil
}
// There is no indexer has replied to this request. Check to see if the token has created.
time.Sleep(time.Duration(10) * time.Second)
exist, err := mc.CreateCommandTokenExist(idxDefn.DefnId)
if exist {
if createErr != nil {
return fmt.Errorf("Encountered transient error. Index creation will be retried in background. Error: %v", createErr)
}
return nil
}
if createErr == nil {
errStr := "Fail to create index due to rebalancing, another concurrent request, network partition, or node failed. " +
"The operation may have succeed. If not, please retry the operation at later time."
createErr = errors.New(errStr)
}
return createErr
}
func (o *MetadataProvider) verifyDuplicateScheduleToken(idxDefn *c.IndexDefn) error {
tokens, err := mc.ListAllScheduleCreateTokens()
if err != nil {
logging.Errorf("verifyDuplicateScheduleToken:: error %v in ListAllScheduleCreateTokens", err)
return err
}
for _, token := range tokens {
defn := token.Definition
if defn.Bucket == idxDefn.Bucket &&
defn.Scope == idxDefn.Scope &&
defn.Collection == idxDefn.Collection &&
defn.Name == idxDefn.Name {
exists, err := mc.StopScheduleCreateTokenExist(defn.DefnId)
if err != nil {
logging.Errorf("verifyDuplicateScheduleToken:: error %v in StopScheduleCreateTokenExist", err)
return err
}
if exists {
continue
}
return fmt.Errorf("Duplicate index id %v is already scheduled for creation.", defn.DefnId)
}
}
return nil
}
func (o *MetadataProvider) scheduleIndexCreation(idxDefn *c.IndexDefn,
plan map[string]interface{}) error {
err := o.verifyDuplicateScheduleToken(idxDefn)
if err != nil {
return err
}
//
// choose one indexer and let it post the token
//
nodes := make(map[string]*watcher)
watchers := o.getAllWatchers()
for _, w := range watchers {
if w.serviceMap.ExcludeNode == "in" ||
w.serviceMap.ExcludeNode == "inout" {
continue
}
nodes[strings.ToLower(w.getNodeAddr())] = w
}
if len(nodes) <= 0 {
return fmt.Errorf("No candidate indexer node found for posting schedule create token "+
"for index (%v, %v, %v, %v)", idxDefn.Bucket, idxDefn.Scope, idxDefn.Collection, idxDefn.Name)
}
//
// validate availability of input nodes, if any.
//
for _, n := range idxDefn.Nodes {
_, ok := nodes[strings.ToLower(n)]
if !ok {
return fmt.Errorf("Indexer node (%v) not found. The node may be failed or "+
"under rebalance or network partitioned from query process.", n)
}
}
var indexer *watcher
if len(idxDefn.Nodes) != 0 {
n := idxDefn.Nodes[0]
for addr, node := range nodes {
if addr == n {
indexer = node
break
}
}
}
if indexer == nil {
if len(idxDefn.Nodes) != 0 {
logging.Warnf("Cannot find the candidate indexer node to post schedule create token, "+
"which belongs in the user-specified list of nodes, for index (%v, %v, %v, %v)",
idxDefn.Bucket, idxDefn.Scope, idxDefn.Collection, idxDefn.Name)
}
for _, node := range nodes {
indexer = node
break
}
}
if indexer == nil {
return fmt.Errorf("No candidate indexer node found for posting schedule create token.")
}
return o.makeScheduleCreateRequest(idxDefn, plan, indexer)
}
func (o *MetadataProvider) makeScheduleCreateRequest(idxDefn *c.IndexDefn,
plan map[string]interface{}, indexer *watcher) error {
addr := indexer.getHttpAddr()
url := addr + "/postScheduleCreateRequest"
req := &ScheduleCreateRequest{
Definition: *idxDefn,
Plan: plan,
IndexerId: indexer.getIndexerId(),
}
buf, err := json.Marshal(req)
if err != nil {
return err
}
bytesBuf := bytes.NewBuffer(buf)
params := &security.RequestParams{Timeout: time.Duration(10) * time.Second}
var resp *http.Response
resp, err = security.PostWithAuth(url, "application/json", bytesBuf, params)
if err != nil {
logging.Errorf("MetadataProvider::makeScheduleCreateRequest: error in PostWithAuth: %v, for index (%v, %v, %v, %v)",
err, idxDefn.Bucket, idxDefn.Scope, idxDefn.Collection, idxDefn.Name)
return err
}
if resp.StatusCode != http.StatusOK {
logging.Errorf("MetadataProvider::makeScheduleCreateRequest: unexpected http status: %v, for index (%v, %v, %v, %v)",
resp.StatusCode, idxDefn.Bucket, idxDefn.Scope, idxDefn.Collection, idxDefn.Name)
var msg interface{}
buf := new(bytes.Buffer)
if _, err := buf.ReadFrom(resp.Body); err != nil {
logging.Errorf("MetadataProvider::makeScheduleCreateRequest: error in reading response body: %v, for index (%v, %v, %v, %v)",
err, idxDefn.Bucket, idxDefn.Scope, idxDefn.Collection, idxDefn.Name)
return err
}
if err := json.Unmarshal(buf.Bytes(), msg); err != nil {
logging.Errorf("MetadataProvider::makeScheduleCreateRequest: error in unmarshalling response body: %v, for index (%v, %v, %v, %v)",
err, idxDefn.Bucket, idxDefn.Scope, idxDefn.Collection, idxDefn.Name)
return err
}
return fmt.Errorf("Error in posting schedule create request %v", msg)
}
err = o.waitForScheduleCreateToken(idxDefn.DefnId)
if err != nil {
return err
}
logging.Infof("Indexer %v has posted schedule create token for index (%v, %v, %v, %v)",
indexer.getIndexerId(), idxDefn.Bucket, idxDefn.Scope, idxDefn.Collection, idxDefn.Name)
return nil
}
func (o *MetadataProvider) waitForScheduleCreateToken(defnId c.IndexDefnId) error {
tries := 20
for i := 0; i < tries; i++ {
exists, err := mc.ScheduleCreateTokenExist(defnId)
if err != nil || !exists {
time.Sleep(3 * time.Second)
continue
}
return nil
}
return ErrWaitScheduleTimeout
}
// This should be called for the defn, that is not yet persisted in index metadata.
func (o *MetadataProvider) CreateIndexWithDefnAndPlan(idxDefn *c.IndexDefn,
plan map[string]interface{}) error {
// TODO: Check for existing idxDefn.DefnId.
// This will be called from metadata_provider.
return o.recoverableCreateIndex(idxDefn, plan, false)
}
//
// This function create index using new protocol (vulcan).
//
func (o *MetadataProvider) recoverableCreateIndex(idxDefn *c.IndexDefn,
plan map[string]interface{}, scheduleOnFailure bool) error {
//
// Prepare Phase. This is to seek full quorum from all the indexers.
//
// This operation will fail if
// 1) Any indexer is unreachable
// 2) Any indexer is serving another create index request
//
// Once the full quorum is achieved, the indexer will not accept any other create index request until:
// 1) This create index request has completed
// 2) This create index request has been explicity canceled
// 3) Indexer has timed out
//
// Note: Even in case of plan having with "nodes" clause, a full quorum will be sought.
// This can be disabled with the help of AllowPartialQuorum setting.
useNodes := ([]string)(nil)
if o.settings.AllowPartialQuorum() {
if len(idxDefn.Nodes) != 0 {
logging.Infof("As per the setting, allowing partial quorum for creation "+
"of the index name=%v, bucket=%v, scope=%v, collection=%v",
idxDefn.Name, idxDefn.Bucket, idxDefn.Scope, idxDefn.Collection)
}
useNodes = idxDefn.Nodes
}
watcherMap, err, canSchedule := o.makePrepareIndexRequest(idxDefn.DefnId, idxDefn.Name,
idxDefn.Bucket, idxDefn.Scope, idxDefn.Collection, useNodes,
idxDefn.PartitionScheme, int(idxDefn.NumReplica), true)
if err != nil {
o.cancelPrepareIndexRequest(idxDefn.DefnId, watcherMap)
msg := fmt.Sprintf("Index creation for index %v, bucket %v, scope %v, collection %v"+
" cannot start. Reason: %v", idxDefn.Name, idxDefn.Bucket, idxDefn.Scope, idxDefn.Collection, err)
clusterVersion := o.GetClusterVersion()
if scheduleOnFailure && canSchedule && clusterVersion >= c.INDEXER_70_VERSION {
scheduleErr := o.scheduleIndexCreation(idxDefn, plan)
if scheduleErr == nil {
msg += "\n\t Scheduled the index creation in the background."
logging.Warnf("%v", msg)
return fmt.Errorf("%v", msg)
} else {
if scheduleErr.Error() == ErrWaitScheduleTimeout.Error() {
msg += fmt.Sprintf("\n\t Scheduling of index creation was attempted. Please check for index status later.")
} else {
msg += fmt.Sprintf("\n\t Could not schedule index creation in the background. Reason: %v", scheduleErr)
logging.Errorf("%v", msg)
}
}
}
logging.Errorf("Fail to create index: %v", err)
return err
}
//
// Validate idxDefn.Nodes
//
if len(idxDefn.Nodes) != 0 {
// If specified, validate if all the input nodes are available.
// Since makePrepareIndexRequest is called with empty nodes list,
// it gets list of all available nodes, ignoring the input nodes
// list. So, explicit validation is needed.
valid, err := o.validateNodes(idxDefn.Nodes, watcherMap)
if !valid {
o.cancelPrepareIndexRequest(idxDefn.DefnId, watcherMap)
return err
}
if err != nil {
o.cancelPrepareIndexRequest(idxDefn.DefnId, watcherMap)
return err
}
}
//
// Plan Phase.
// The planner will use nodes that metadta provider sees for planning. All inactive_failed, inactive_new and unhealthy
// nodes will be excluded from planning. If the user provides a specific node list, those nodes will be used.
//
layout, definitions, err := o.plan(idxDefn, plan, watcherMap)
if err != nil && strings.Contains(err.Error(), "Index already exist") {
o.cancelPrepareIndexRequest(idxDefn.DefnId, watcherMap)
return err
}
if err != nil {
logging.Errorf("Encounter planner error. Use round robin strategy for planning. Error: %v", err)
indexerIds := make([]c.IndexerId, 0, len(watcherMap))
for indexerId, _ := range watcherMap {
indexerIds = append(indexerIds, indexerId)
}
layout = o.createLayoutWithRoundRobin(idxDefn, indexerIds)
definitions, err = o.getDefinitionsFromLayout(layout, idxDefn)
if err != nil {
logging.Errorf("Fail to create index: %v", err)
return err
}
}
//
// Commit Phase. Metadata Provider will send a commit request to at least one indexer. If at least one indexer
// responds with success, then it means there won't be another concurrent create index request. Even though
// the metadata provider may not have full quorum, this create index request can roll forward.
//
// The first indexer that responds with success will create a token so that it can roll forward even if this