-
Notifications
You must be signed in to change notification settings - Fork 36
/
executor.go
4196 lines (3457 loc) · 130 KB
/
executor.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 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 planner
import (
"encoding/json"
"errors"
"fmt"
"math"
"math/rand"
"os"
"sort"
"strconv"
"time"
"github.com/couchbase/cbauth/service"
"github.com/couchbase/indexing/secondary/common"
"github.com/couchbase/indexing/secondary/common/collections"
"github.com/couchbase/indexing/secondary/iowrap"
"github.com/couchbase/indexing/secondary/logging"
"github.com/couchbase/indexing/secondary/security"
)
//////////////////////////////////////////////////////////////
// Concrete Type/Struct
/////////////////////////////////////////////////////////////
type RunConfig struct {
Detail bool
GenStmt string
MemQuotaFactor float64
CpuQuotaFactor float64
Resize bool
MaxNumNode int
Output string
Shuffle int
AllowMove bool
AllowSwap bool
AllowUnpin bool
AddNode int
DeleteNode int
MaxMemUse int
MaxCpuUse int
MemQuota int64
CpuQuota int
DataCostWeight float64
CpuCostWeight float64
MemCostWeight float64
EjectOnly bool
DisableRepair bool
Timeout int
UseLive bool
Runtime *time.Time
Threshold float64
CpuProfile bool
MinIterPerTemp int
MaxIterPerTemp int
UseGreedyPlanner bool
}
type RunStats struct {
AvgIndexSize float64
StdDevIndexSize float64
AvgIndexCpu float64
StdDevIndexCpu float64
MemoryQuota uint64
CpuQuota uint64
IndexCount uint64
Initial_score float64
Initial_indexCount uint64
Initial_indexerCount uint64
Initial_avgIndexSize float64
Initial_stdDevIndexSize float64
Initial_avgIndexCpu float64
Initial_stdDevIndexCpu float64
Initial_avgIndexerSize float64
Initial_stdDevIndexerSize float64
Initial_avgIndexerCpu float64
Initial_stdDevIndexerCpu float64
Initial_movedIndex uint64
Initial_movedData uint64
}
type SubCluster []*IndexerNode
type Plan struct {
// placement of indexes in nodes
Placement []*IndexerNode `json:"placement,omitempty"`
MemQuota uint64 `json:"memQuota,omitempty"`
CpuQuota uint64 `json:"cpuQuota,omitempty"`
IsLive bool `json:"isLive,omitempty"`
UsedReplicaIdMap map[common.IndexDefnId]map[int]bool
SubClusters []SubCluster
UsageThreshold *UsageThreshold `json:usageThreshold,omitempty"`
DeletedNodes []string `json:deletedNodes,omitempty` //used only for unit testing
}
type IndexSpec struct {
// definition
Name string `json:"name,omitempty"`
Bucket string `json:"bucket,omitempty"`
Scope string `json:"scope,omitempty"`
Collection string `json:"collection,omitempty"`
DefnId common.IndexDefnId `json:"defnId,omitempty"`
IsPrimary bool `json:"isPrimary,omitempty"`
SecExprs []string `json:"secExprs,omitempty"`
WhereExpr string `json:"where,omitempty"`
Deferred bool `json:"deferred,omitempty"`
Immutable bool `json:"immutable,omitempty"`
IsArrayIndex bool `json:"isArrayIndex,omitempty"`
RetainDeletedXATTR bool `json:"retainDeletedXATTR,omitempty"`
NumPartition uint64 `json:"numPartition,omitempty"`
PartitionScheme string `json:"partitionScheme,omitempty"`
HashScheme uint64 `json:"hashScheme,omitempty"`
PartitionKeys []string `json:"partitionKeys,omitempty"`
Replica uint64 `json:"replica,omitempty"`
Desc []bool `json:"desc,omitempty"`
Using string `json:"using,omitempty"`
ExprType string `json:"exprType,omitempty"`
IndexMissingLeadingKey bool `json:"indexMissingLeadingKey,omitempty"`
// usage
NumDoc uint64 `json:"numDoc,omitempty"`
DocKeySize uint64 `json:"docKeySize,omitempty"`
SecKeySize uint64 `json:"secKeySize,omitempty"`
ArrKeySize uint64 `json:"arrKeySize,omitempty"`
ArrSize uint64 `json:"arrSize,omitempty"`
ResidentRatio float64 `json:"residentRatio,omitempty"`
MutationRate uint64 `json:"mutationRate,omitempty"`
ScanRate uint64 `json:"scanRate,omitempty"`
}
//Resource Usage Thresholds for serverless model
type UsageThreshold struct {
MemHighThreshold int32 `json:memHighThreshold,omitempty"`
MemLowThreshold int32 `json:memLowThreshold,omitempty"`
UnitsHighThreshold int32 `json:unitsHighThreshold,omitempty"`
UnitsLowThreshold int32 `json:unitsLowThreshold,omitempty"`
MemQuota uint64 `json:memQuota,omitempty"`
UnitsQuota uint64 `json:unitsQuota,omitempty"`
}
type TenantUsage struct {
SourceId string
TenantId string
MemoryUsage uint64
UnitsUsage uint64
}
//////////////////////////////////////////////////////////////
// Integration with Rebalancer
/////////////////////////////////////////////////////////////
func ExecuteRebalance(clusterUrl string, topologyChange service.TopologyChange, masterId string, ejectOnly bool,
disableReplicaRepair bool, threshold float64, timeout int, cpuProfile bool, minIterPerTemp int,
maxIterPerTemp int) (map[string]*common.TransferToken, map[string]map[common.IndexDefnId]*common.IndexDefn, error) {
runtime := time.Now()
return ExecuteRebalanceInternal(clusterUrl, topologyChange, masterId, false, true, ejectOnly, disableReplicaRepair,
timeout, threshold, cpuProfile, minIterPerTemp, maxIterPerTemp, &runtime)
}
func ExecuteRebalanceInternal(clusterUrl string,
topologyChange service.TopologyChange, masterId string, addNode bool, detail bool, ejectOnly bool,
disableReplicaRepair bool, timeout int, threshold float64, cpuProfile bool, minIterPerTemp, maxIterPerTemp int,
runtime *time.Time) (map[string]*common.TransferToken, map[string]map[common.IndexDefnId]*common.IndexDefn, error) {
plan, err := RetrievePlanFromCluster(clusterUrl, nil, true)
if err != nil {
return nil, nil, errors.New(fmt.Sprintf("Unable to read index layout from cluster %v. err = %s", clusterUrl, err))
}
nodes := make(map[string]string)
for _, node := range plan.Placement {
nodes[node.NodeUUID] = node.NodeId
}
deleteNodes := make([]string, len(topologyChange.EjectNodes))
for i, node := range topologyChange.EjectNodes {
if _, ok := nodes[string(node.NodeID)]; !ok {
return nil, nil, errors.New(fmt.Sprintf("Unable to find indexer node with node UUID %v", node.NodeID))
}
deleteNodes[i] = nodes[string(node.NodeID)]
}
// make sure we have all the keep nodes
for _, node := range topologyChange.KeepNodes {
if _, ok := nodes[string(node.NodeInfo.NodeID)]; !ok {
return nil, nil, errors.New(fmt.Sprintf("Unable to find indexer node with node UUID %v", node.NodeInfo.NodeID))
}
}
var numNode int
if addNode {
numNode = len(deleteNodes)
}
config := DefaultRunConfig()
config.Detail = detail
config.Resize = false
config.AddNode = numNode
config.EjectOnly = ejectOnly
config.DisableRepair = disableReplicaRepair
config.Timeout = timeout
config.Runtime = runtime
config.Threshold = threshold
config.CpuProfile = cpuProfile
config.MinIterPerTemp = minIterPerTemp
config.MaxIterPerTemp = maxIterPerTemp
p, _, hostToIndexToRemove, err := executeRebal(config, CommandRebalance, plan, nil, deleteNodes, true)
if p != nil && detail {
logging.Infof("************ Indexer Layout *************")
p.Print()
logging.Infof("****************************************")
}
if err != nil {
return nil, nil, err
}
filterSolution(p.Result.Placement)
transferTokens, err := genTransferToken(p.Result, masterId, topologyChange, deleteNodes)
if err != nil {
return nil, nil, err
}
return transferTokens, hostToIndexToRemove, nil
}
// filterSolution will iterate through the new placement generated by planner and filter out all
// un-necessary movements. (It is also actually required to be called to remove circular replica
// movements Planner may otherwise leave in the plan, which would trigger Rebalance failures.)
//
// E.g. if for an index, there exists 3 replicas on nodes n1 (replica 0),
// n2 (replica 1), n3 (replica 2) in a 4 node cluster (n1,n2,n3,n4) and
// if planner has generated a placement to move replica 0 from n1->n2,
// replica 1 from n2->n3 and replica 3 from n3->n4, the movement of replicas
// from n2 and n3 are unnecessary as replica instances exist on the node before
// and after movement. filterSolution will eliminate all such movements and
// update the solution to have one final movement from n1->n4
//
// Similarly, if there are any cyclic movements i.e. n1->n2,n2->n3,n3->n1,
// all such movements will be avoided
func filterSolution(placement []*IndexerNode) {
indexDefnMap := make(map[common.IndexDefnId]map[common.PartitionId][]*IndexUsage)
indexerMap := make(map[string]*IndexerNode)
// Group the index based on replica, partition. This grouping
// will help to identify if multiple replicas are being moved
// between nodes
for _, indexer := range placement {
indexerMap[indexer.NodeId] = indexer
for _, index := range indexer.Indexes {
// Update destNode for each of the index as planner has
// finished the run and generated a tentative placement.
// A transfer token will not be generated if initialNode
// and destNode are same.
index.destNode = indexer
if _, ok := indexDefnMap[index.DefnId]; !ok {
indexDefnMap[index.DefnId] = make(map[common.PartitionId][]*IndexUsage)
}
indexDefnMap[index.DefnId][index.PartnId] = append(indexDefnMap[index.DefnId][index.PartnId], index)
}
}
for _, defnMap := range indexDefnMap {
for _, indexes := range defnMap {
if len(indexes) == 1 {
continue
}
transferMap := make(map[string]string)
// Generate a map of all transfers between nodes for this replica instance
for _, index := range indexes {
if index.initialNode != nil && index.initialNode.NodeId != index.destNode.NodeId {
transferMap[index.initialNode.NodeId] = index.destNode.NodeId
} else if index.initialNode == nil {
// Create a dummy source node for replica repair. This is to
// address scenarios like lost_replica -> n0, n0 -> n1
key := fmt.Sprintf("ReplicaRepair_%v_%v", index.InstId, index.PartnId)
transferMap[key] = index.destNode.NodeId
}
}
if len(transferMap) == 0 {
continue
}
loop:
// Search the transferMap in Depth-First fashion and find the appropriate
// source and destination
for src, dst := range transferMap {
if newDest, ok := transferMap[dst]; ok {
delete(transferMap, dst)
if newDest != src {
transferMap[src] = newDest
} else { // Delete src to avoid cyclic transfers (n0 -> n1, n1 -> n0)
delete(transferMap, src)
}
goto loop
}
}
// Filter out un-necessary movements from based on transferMap
// and update the solution to have only valid movements
for _, index := range indexes {
var initialNodeId string
var replicaRepair bool
if index.initialNode == nil {
initialNodeId = fmt.Sprintf("ReplicaRepair_%v_%v", index.InstId, index.PartnId)
replicaRepair = true
} else {
initialNodeId = index.initialNode.NodeId
}
if destNodeId, ok := transferMap[initialNodeId]; ok {
// Inst. is moved to a different node after filtering the solution
if destNodeId != index.destNode.NodeId {
destIndexer := indexerMap[destNodeId]
preFilterDest := index.destNode
index.destNode = destIndexer
fmsg := "Planner::filterSolution - Planner intended to move the inst: %v, " +
"partn: %v from node %v to node %v. Instead the inst is moved to node: %v " +
"after eliminating the un-necessary replica movements"
if replicaRepair { // initialNode would be nil incase of replica repair
logging.Infof(fmsg, index.InstId, index.PartnId,
"", preFilterDest.NodeId, index.destNode.NodeId)
} else {
logging.Infof(fmsg, index.InstId, index.PartnId,
index.initialNode.NodeId, preFilterDest.NodeId, index.destNode.NodeId)
}
} else {
// Initial destination and final destination are same. No change
// in placement required
}
} else {
// Planner initially planned a movement for this index but after filtering the
// solution, the movement is deemed un-necessary
if index.initialNode != nil && index.destNode.NodeId != index.initialNode.NodeId {
logging.Infof("Planner::filterSolution - Planner intended to move the inst: %v, "+
"partn: %v from node %v to node %v. This movement is deemed un-necessary as node: %v "+
"already has a replica partition", index.InstId, index.PartnId, index.initialNode.NodeId,
index.destNode.NodeId, index.destNode.NodeId)
index.destNode = index.initialNode
}
}
}
}
}
}
// genTransferToken generates transfer tokens for the plan. Since the addition of the filterSolution
// plan post-processing, the destination node of an IndexUsage at this point is explicitly kept in
// IndexUsage.destNode.NodeUUID (index.destNode.NodeUUID in code below). filterSolution does NOT
// move the IndexUsages to their new destination Indexers in the plan (which are the implicit
// destinations as understood by Planner before filterSolution was called), thus the
// IndexerNode.NodeUUID (indexer.NodeUUID) field should NEVER be used in genTransferToken anymore.
func genTransferToken(solution *Solution, masterId string, topologyChange service.TopologyChange,
deleteNodes []string) (map[string]*common.TransferToken, error) {
tokens := make(map[string]*common.TransferToken)
for _, indexer := range solution.Placement {
for _, index := range indexer.Indexes {
if index.initialNode != nil && index.initialNode.NodeId != index.destNode.NodeId && !index.pendingCreate {
// one token for every index replica between a specific source and destination
tokenKey := fmt.Sprintf("%v %v %v %v", index.DefnId, index.Instance.ReplicaId,
index.initialNode.NodeUUID, index.destNode.NodeUUID)
token, ok := tokens[tokenKey]
if !ok {
token = &common.TransferToken{
MasterId: masterId,
SourceId: index.initialNode.NodeUUID,
DestId: index.destNode.NodeUUID,
RebalId: topologyChange.ID,
State: common.TransferTokenCreated,
InstId: index.InstId,
IndexInst: *index.Instance,
TransferMode: common.TokenTransferModeMove,
SourceHost: index.initialNode.NodeId,
DestHost: index.destNode.NodeId,
}
token.IndexInst.Defn.InstVersion = token.IndexInst.Version + 1
token.IndexInst.Defn.ReplicaId = token.IndexInst.ReplicaId
token.IndexInst.Defn.Using = common.IndexType(indexer.StorageMode)
token.IndexInst.Defn.Partitions = []common.PartitionId{index.PartnId}
token.IndexInst.Defn.Versions = []int{token.IndexInst.Version + 1}
token.IndexInst.Defn.NumPartitions = uint32(token.IndexInst.Pc.GetNumPartitions())
token.IndexInst.Pc = nil
// reset defn id and instance id as if it is a new index.
if common.IsPartitioned(token.IndexInst.Defn.PartitionScheme) {
instId, err := common.NewIndexInstId()
if err != nil {
return nil, fmt.Errorf("Fail to generate transfer token. Reason: %v", err)
}
token.RealInstId = token.InstId
token.InstId = instId
}
// if there is a build token for the definition, set index STATE to active so the
// index will be built as part of rebalancing.
if index.pendingBuild && !index.PendingDelete {
if token.IndexInst.State == common.INDEX_STATE_CREATED || token.IndexInst.State == common.INDEX_STATE_READY {
token.IndexInst.State = common.INDEX_STATE_ACTIVE
}
}
tokens[tokenKey] = token
} else {
// Token exist for the same index replica between the same source and target. Add partition to token.
token.IndexInst.Defn.Partitions = append(token.IndexInst.Defn.Partitions, index.PartnId)
token.IndexInst.Defn.Versions = append(token.IndexInst.Defn.Versions, index.Instance.Version+1)
if token.IndexInst.Defn.InstVersion < index.Instance.Version+1 {
token.IndexInst.Defn.InstVersion = index.Instance.Version + 1
}
}
} else if index.initialNode == nil || index.pendingCreate {
// There is no source node (index is added during rebalance).
// one token for every index replica between a specific source and destination
tokenKey := fmt.Sprintf("%v %v %v %v", index.DefnId, index.Instance.ReplicaId,
"N/A", index.destNode.NodeUUID)
token, ok := tokens[tokenKey]
if !ok {
token = &common.TransferToken{
MasterId: masterId,
SourceId: "",
DestId: index.destNode.NodeUUID,
RebalId: topologyChange.ID,
State: common.TransferTokenCreated,
InstId: index.InstId,
IndexInst: *index.Instance,
TransferMode: common.TokenTransferModeCopy,
DestHost: index.destNode.NodeId,
}
token.IndexInst.Defn.InstVersion = 1
token.IndexInst.Defn.ReplicaId = token.IndexInst.ReplicaId
token.IndexInst.Defn.Using = common.IndexType(indexer.StorageMode)
token.IndexInst.Defn.Partitions = []common.PartitionId{index.PartnId}
token.IndexInst.Defn.Versions = []int{1}
token.IndexInst.Defn.NumPartitions = uint32(token.IndexInst.Pc.GetNumPartitions())
token.IndexInst.Pc = nil
// reset defn id and instance id as if it is a new index.
if common.IsPartitioned(token.IndexInst.Defn.PartitionScheme) {
instId, err := common.NewIndexInstId()
if err != nil {
return nil, fmt.Errorf("Fail to generate transfer token. Reason: %v", err)
}
token.RealInstId = token.InstId
token.InstId = instId
}
tokens[tokenKey] = token
} else {
// Token exist for the same index replica between the same source and target. Add partition to token.
token.IndexInst.Defn.Partitions = append(token.IndexInst.Defn.Partitions, index.PartnId)
token.IndexInst.Defn.Versions = append(token.IndexInst.Defn.Versions, 1)
if token.IndexInst.Defn.InstVersion < index.Instance.Version+1 {
token.IndexInst.Defn.InstVersion = index.Instance.Version + 1
}
}
}
}
}
result := make(map[string]*common.TransferToken)
for _, token := range tokens {
ustr, _ := common.NewUUID()
ttid := fmt.Sprintf("TransferToken%s", ustr.Str())
result[ttid] = token
if len(token.SourceId) != 0 {
logging.Infof("Generating Transfer Token (%v) for rebalance (%v)", ttid, token)
} else {
logging.Infof("Generating Transfer Token (%v) for rebuilding lost replica (%v)", ttid, token)
}
}
return result, nil
}
func genShardTransferToken(solution *Solution, masterId string, topologyChange service.TopologyChange,
deleteNodes []string) (map[string]*common.TransferToken, error) {
getInstIds := func(index *IndexUsage) (common.IndexInstId /* instId*/, common.IndexInstId /*realInstId*/, error) {
if common.IsPartitioned(index.Instance.Defn.PartitionScheme) {
instId, err := common.NewIndexInstId()
if err != nil {
return 0, 0, fmt.Errorf("Fail to generate transfer token. Reason: %v", err)
}
return instId, index.InstId, nil
}
return index.InstId, 0, nil
}
initInstInToken := func(token *common.TransferToken, index *IndexUsage) error {
token.IndexInsts = append(token.IndexInsts, *index.Instance)
instId, realInstId, err := getInstIds(index)
if err != nil {
return err
}
token.InstIds = append(token.InstIds, instId)
token.RealInstIds = append(token.RealInstIds, realInstId)
return nil
}
tokens := make(map[string]*common.TransferToken)
initToken := func(index *IndexUsage) (*common.TransferToken, error) {
token := &common.TransferToken{
MasterId: masterId,
DestId: index.destNode.NodeUUID,
RebalId: topologyChange.ID,
ShardTransferTokenState: common.ShardTokenCreated,
TransferMode: common.TokenTransferModeMove,
DestHost: index.destNode.NodeId,
Version: common.MULTI_INST_SHARD_TRANSFER,
ShardIds: index.ShardIds,
}
if index.initialNode != nil {
token.SourceHost = index.initialNode.NodeId
token.SourceId = index.initialNode.NodeUUID
}
if err := initInstInToken(token, index); err != nil {
return nil, err
}
return token, nil
}
addIndexToToken := func(tokenKey string, index *IndexUsage, indexer *IndexerNode) error {
token, ok := tokens[tokenKey]
if !ok {
var err error
if token, err = initToken(index); err != nil {
return err
}
tokens[tokenKey] = token
}
if token != nil {
sliceIndex := len(token.InstIds) - 1
found := false
instIds := token.InstIds
if common.IsPartitioned(index.Instance.Defn.PartitionScheme) {
// For partitioned index, use realInstIds. If it is the first
// time this partition index is being processed, it will be
// added due to !found becoming true
instIds = token.RealInstIds
}
for i, instId := range instIds {
if instId == index.InstId {
sliceIndex = i
found = true
break
}
}
if !found { // Instance not already appended to list. Add now
if err := initInstInToken(token, index); err != nil {
return err
}
sliceIndex = len(token.InstIds) - 1
}
token.IndexInsts[sliceIndex].Defn.InstVersion = token.IndexInst.Version + 1
token.IndexInsts[sliceIndex].Defn.ReplicaId = token.IndexInsts[sliceIndex].ReplicaId
token.IndexInsts[sliceIndex].Defn.Using = common.IndexType(indexer.StorageMode)
if token.IndexInsts[sliceIndex].Pc != nil {
token.IndexInsts[sliceIndex].Defn.NumPartitions = uint32(token.IndexInsts[sliceIndex].Pc.GetNumPartitions())
}
token.IndexInsts[sliceIndex].Pc = nil
// Token exist for the same index replica between the same source and target. Add partition to token.
token.IndexInsts[sliceIndex].Defn.Partitions = append(token.IndexInsts[sliceIndex].Defn.Partitions, index.PartnId)
token.IndexInsts[sliceIndex].Defn.Versions = append(token.IndexInsts[sliceIndex].Defn.Versions, index.Instance.Version+1)
if token.IndexInsts[sliceIndex].Defn.InstVersion < index.Instance.Version+1 {
token.IndexInsts[sliceIndex].Defn.InstVersion = index.Instance.Version + 1
}
}
return nil
}
for _, indexer := range solution.Placement {
for _, index := range indexer.Indexes {
// Primary index contians only one shard. Process primary
// index shard after all secondary index tokens are generated
// so that it can be added to one of the existing token for
// the shard
if len(index.ShardIds) == 1 {
continue
}
// one token for every pair of shard movements of a bucket between
// a specific source and destination
sort.Slice(index.ShardIds, func(i, j int) bool {
return index.ShardIds[i] < index.ShardIds[j]
})
// one token for every pair of shard movements of a bucket between
// a specific source and destination
var tokenKey string
if index.initialNode != nil && index.initialNode.NodeId != index.destNode.NodeId && !index.pendingCreate {
tokenKey = fmt.Sprintf("%v %v %v %v", index.Bucket, index.ShardIds, index.initialNode.NodeUUID, index.destNode.NodeUUID)
} else if index.initialNode == nil || index.pendingCreate {
// There is no source node (index is added during rebalance).
tokenKey = fmt.Sprintf("%v %v %v %v", index.Bucket, index.ShardIds, "N/A", index.destNode.NodeUUID)
}
if len(tokenKey) > 0 {
if err := addIndexToToken(tokenKey, index, indexer); err != nil {
return nil, err
}
}
}
}
// Process primary indexes only
for _, indexer := range solution.Placement {
for _, index := range indexer.Indexes {
if len(index.ShardIds) != 1 {
continue
}
// Find a token key that contains the shard of this index
// Note: Since tokens are grouped based on shardId's, it is
// expected to have only one token matching the shardId of
// primary index
found := false
for tokenKey, token := range tokens {
if index.Bucket != token.IndexInsts[0].Defn.Bucket {
continue
}
if index.destNode.NodeUUID != token.DestId {
continue
}
if index.initialNode == nil && token.SourceId != "" {
continue
}
if index.initialNode != nil && index.initialNode.NodeUUID != token.SourceId {
continue
}
for _, shardId := range token.ShardIds {
if index.ShardIds[0] == shardId {
// Add index to this token
addIndexToToken(tokenKey, index, indexer)
found = true
break
}
}
}
// Could be only primary indexes in this shard
// Generate a new token and add it to the group
if !found {
var tokenKey string
if index.initialNode != nil && index.initialNode.NodeId != index.destNode.NodeId && !index.pendingCreate {
tokenKey = fmt.Sprintf("%v %v %v %v", index.Bucket, index.ShardIds, index.initialNode.NodeUUID, index.destNode.NodeUUID)
} else if index.initialNode == nil || index.pendingCreate {
// There is no source node (index is added during rebalance).
tokenKey = fmt.Sprintf("%v %v %v %v", index.Bucket, index.ShardIds, "N/A", index.destNode.NodeUUID)
}
if len(tokenKey) > 0 {
if err := addIndexToToken(tokenKey, index, indexer); err != nil {
return nil, err
}
}
}
}
}
result := make(map[string]*common.TransferToken)
for _, token := range tokens {
ustr, _ := common.NewUUID()
ttid := fmt.Sprintf("TransferToken%s", ustr.Str())
result[ttid] = token
}
var err error
result, err = populateSiblingTokenId(solution, result)
if err != nil {
return nil, err
}
logTransferTokens := func(logErr bool) {
for ttid, token := range result {
if len(token.SourceId) != 0 {
if logErr {
logging.Errorf("Generating Shard Transfer Token (%v) for rebalance (%v)", ttid, token)
} else {
logging.Infof("Generating Shard Transfer Token (%v) for rebalance (%v)", ttid, token)
}
} else {
if logErr {
logging.Errorf("Generating Shard Transfer Token (%v) for rebuilding lost replica (%v)", ttid, token)
} else {
logging.Infof("Generating Shard Transfer Token (%v) for rebalance (%v)", ttid, token)
}
}
}
}
if err := validateSiblingTokenId(result); err != nil {
logging.Errorf(err.Error())
logTransferTokens(true)
return nil, err
}
logTransferTokens(false)
return result, nil
}
func validateSiblingTokenId(transferTokens map[string]*common.TransferToken) error {
for ttid, token := range transferTokens {
if token.TransferMode != common.TokenTransferModeMove {
continue
}
if token.SiblingTokenId == "" {
return fmt.Errorf("validateSiblingTokenId: Sibling tokenId empty for ttid: %v, token: %v", ttid, token)
}
if sibling, ok := transferTokens[token.SiblingTokenId]; !ok {
return fmt.Errorf("validateSiblingTokenId: Sibling token not found in list for ttid: %v, token: %v", ttid, token)
} else if sibling.SiblingTokenId != ttid {
return fmt.Errorf("validateSiblingTokenId: Invalid token Id for sibling. ttid: %v, siblingTokenId: %v, token: %v, siblingToken: %v", ttid, sibling.SiblingTokenId, token, sibling)
}
}
return nil
}
func populateSiblingTokenId(solution *Solution, transferTokens map[string]*common.TransferToken) (map[string]*common.TransferToken, error) {
// It is ok to ignore the error here as this method is only called
// after err == nil is seen the same solution
subClusters, _ := groupIndexNodesIntoSubClusters(solution.Placement)
// Group transfer tokens moving from one sub cluster to another cluster
subClusterTokenIdMap := make(map[string][]string)
for ttid, token := range transferTokens {
if token.TransferMode != common.TokenTransferModeMove { // Ignore for replica repair
continue
}
srcSubClusterPos := getSubClusterPosForNode(subClusters, token.SourceId)
destSubClusterPos := getSubClusterPosForNode(subClusters, token.DestId)
// Group all tokens of a bucket moving from a source subcluster to a
// destination subcluster
groupKey := fmt.Sprintf("%v %v %v", srcSubClusterPos, destSubClusterPos, token.IndexInsts[0].Defn.Bucket)
subClusterTokenIdMap[groupKey] = append(subClusterTokenIdMap[groupKey], ttid)
}
allPartitionsMatch := func(inst1, inst2 []common.PartitionId) bool {
if len(inst1) != len(inst2) {
return false
}
sort.Slice(inst1, func(i, j int) bool {
return inst1[i] < inst1[j]
})
sort.Slice(inst2, func(i, j int) bool {
return inst2[i] < inst2[j]
})
for i := range inst1 {
if inst1[i] != inst2[i] {
return false
}
}
return true
}
areTokensMatchingAllInsts := func(tid1, tid2 string) bool {
token1, _ := transferTokens[tid1]
token2, _ := transferTokens[tid2]
for i, inst1 := range token1.IndexInsts {
foundInst := false
for j, inst2 := range token2.IndexInsts {
if inst1.Defn.DefnId == inst2.Defn.DefnId { // Defn ID will be same for replica index instances
// As partitions can be spread across multiple nodes, they share the same defnId and instId
// Do not compare partitions belonging to same instances. Only compare partitions
// of replicas
if common.IsPartitioned(inst1.Defn.PartitionScheme) && token1.RealInstIds[i] == token2.RealInstIds[j] {
continue
}
inst1Partns := inst1.Defn.Partitions
inst2Partns := inst2.Defn.Partitions
foundInst = allPartitionsMatch(inst1Partns, inst2Partns)
break
}
}
if !foundInst {
return false
}
}
return true
}
for _, tokens := range subClusterTokenIdMap {
for i, _ := range tokens {
for j, _ := range tokens {
if i != j {
if areTokensMatchingAllInsts(tokens[i], tokens[j]) {
transferTokens[tokens[i]].SiblingTokenId = tokens[j]
transferTokens[tokens[j]].SiblingTokenId = tokens[i]
continue
}
}
}
}
}
return transferTokens, nil
}
//////////////////////////////////////////////////////////////
// Integration with Metadata Provider
/////////////////////////////////////////////////////////////
func ExecutePlan(clusterUrl string, indexSpecs []*IndexSpec, nodes []string, override bool, useGreedyPlanner bool, enforceLimits bool) (*Solution, error) {
plan, err := RetrievePlanFromCluster(clusterUrl, nodes, false)
if err != nil {
return nil, errors.New(fmt.Sprintf("Unable to read index layout from cluster %v. err = %s", clusterUrl, err))
}
if enforceLimits {
scopeSet := make(map[string]bool)
for _, indexSpec := range indexSpecs {
if _, found := scopeSet[indexSpec.Bucket+":"+indexSpec.Scope]; !found {
scopeSet[indexSpec.Bucket+":"+indexSpec.Scope] = true
scopeLimit, err := GetIndexScopeLimit(clusterUrl, indexSpec.Bucket, indexSpec.Scope)
if err != nil {
return nil, err
}
if scopeLimit != collections.NUM_INDEXES_NIL {
numIndexes := GetNumIndexesPerScope(plan, indexSpec.Bucket, indexSpec.Scope)
// GetNewIndexesPerScope will be called only once per Bucket+Scope
newIndexes := GetNewIndexesPerScope(indexSpecs, indexSpec.Bucket, indexSpec.Scope)
if numIndexes+newIndexes > scopeLimit {
errMsg := fmt.Sprintf("%v Limit : %v", common.ErrIndexScopeLimitReached.Error(), scopeLimit)
return nil, errors.New(errMsg)
}
}
}
}
}
if override && len(nodes) != 0 {
for _, indexer := range plan.Placement {
found := false
for _, node := range nodes {
encryptedNodeAddr, _ := security.EncryptPortInAddr(node)
if indexer.NodeId == node ||
indexer.NodeId == encryptedNodeAddr {
found = true
break
}
}
if found {
indexer.UnsetExclude()
} else {
indexer.SetExclude("in")
}
}
}
if err = verifyDuplicateIndex(plan, indexSpecs); err != nil {
return nil, err
}
detail := logging.IsEnabled(logging.Info)
return ExecutePlanWithOptions(plan, indexSpecs, detail, "", "", -1, -1, -1, false, true, useGreedyPlanner)
}
func GetNumIndexesPerScope(plan *Plan, Bucket string, Scope string) uint32 {
var numIndexes uint32 = 0
for _, indexernode := range plan.Placement {
for _, index := range indexernode.Indexes {
if index.Bucket == Bucket && index.Scope == Scope {
numIndexes = numIndexes + 1
}
}
}
return numIndexes
}
func GetNewIndexesPerScope(indexSpecs []*IndexSpec, bucket string, scope string) uint32 {
var newIndexes uint32 = 0
for _, indexSpec := range indexSpecs {
if indexSpec.Bucket == bucket && indexSpec.Scope == scope {
newIndexes = newIndexes + uint32(indexSpec.NumPartition*indexSpec.Replica)
}
}
return newIndexes
}
// Alternate approach: Get Scope Limit from clusterInfoClient from proxy.go
// But in order to get Scope limit only bucket and scope name is required and multiple calls need
// not be made to fetch bucket list, pool etc. For future use of this function this Implementation
// removes the dependency on Fetching ClusterInfoCache and uses only one API call.
func GetIndexScopeLimit(clusterUrl, bucket, scope string) (uint32, error) {
clusterURL, err := common.ClusterAuthUrl(clusterUrl)
if err != nil {
return 0, err
}
cinfo, err := common.NewClusterInfoCache(clusterURL, "default")
if err != nil {
return 0, err
}
cinfo.Lock()
defer cinfo.Unlock()
cinfo.SetUserAgent("Planner:Executor:GetIndexScopeLimit")
return cinfo.GetIndexScopeLimit(bucket, scope)
}
func verifyDuplicateIndex(plan *Plan, indexSpecs []*IndexSpec) error {
for _, spec := range indexSpecs {
for _, indexer := range plan.Placement {
for _, index := range indexer.Indexes {
if index.Name == spec.Name && index.Bucket == spec.Bucket &&
index.Scope == spec.Scope && index.Collection == spec.Collection {
errMsg := fmt.Sprintf("%v. Fail to create %v in bucket %v, scope %v, collection %v",
common.ErrIndexAlreadyExists.Error(), spec.Name, spec.Bucket, spec.Scope, spec.Collection)
return errors.New(errMsg)
}
}
}
}
return nil
}
func FindIndexReplicaNodes(clusterUrl string, nodes []string, defnId common.IndexDefnId) ([]string, error) {
plan, err := RetrievePlanFromCluster(clusterUrl, nodes, false)
if err != nil {
return nil, fmt.Errorf("Unable to read index layout from cluster %v. err = %s", clusterUrl, err)
}
replicaNodes := make([]string, 0, len(plan.Placement))
for _, indexer := range plan.Placement {
for _, index := range indexer.Indexes {