-
Notifications
You must be signed in to change notification settings - Fork 36
/
executor.go
1690 lines (1372 loc) · 51.2 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 (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 planner
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math"
"math/rand"
"os"
"strconv"
"time"
"github.com/couchbase/cbauth/service"
"github.com/couchbase/indexing/secondary/common"
"github.com/couchbase/indexing/secondary/logging"
)
//////////////////////////////////////////////////////////////
// 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
}
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 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
}
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"`
// 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"`
}
//////////////////////////////////////////////////////////////
// Integration with Rebalancer
/////////////////////////////////////////////////////////////
func ExecuteRebalance(clusterUrl string, topologyChange service.TopologyChange, masterId string, ejectOnly bool,
disableReplicaRepair bool, threshold float64, timeout int, cpuProfile bool) (map[string]*common.TransferToken, error) {
runtime := time.Now()
return ExecuteRebalanceInternal(clusterUrl, topologyChange, masterId, false, true, ejectOnly, disableReplicaRepair,
timeout, threshold, cpuProfile, &runtime)
}
func ExecuteRebalanceInternal(clusterUrl string,
topologyChange service.TopologyChange, masterId string, addNode bool, detail bool, ejectOnly bool,
disableReplicaRepair bool, timeout int, threshold float64, cpuProfile bool, runtime *time.Time) (map[string]*common.TransferToken, error) {
plan, err := RetrievePlanFromCluster(clusterUrl, nil)
if err != nil {
return 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, 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, 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
p, _, err := execute(config, CommandRebalance, plan, nil, deleteNodes)
if p != nil && detail {
logging.Infof("************ Indexer Layout *************")
p.Print()
logging.Infof("****************************************")
}
if err != nil {
return nil, err
}
filterSolution(p.Result.Placement)
transferTokens, err := genTransferToken(p.Result, masterId, topologyChange, deleteNodes)
if err != nil {
return nil, err
}
return transferTokens, nil
}
// filterSolution will iterate through the new placement generated
// by planner and filter out all un-necessary movements.
//
// 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 instaces exist on the node before
// and after movement. filterSolution will elimimate 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 destiantion 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
}
}
}
}
}
}
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, indexer.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,
}
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", indexer.NodeUUID)
token, ok := tokens[tokenKey]
if !ok {
token = &common.TransferToken{
MasterId: masterId,
SourceId: "",
DestId: indexer.NodeUUID,
RebalId: topologyChange.ID,
State: common.TransferTokenCreated,
InstId: index.InstId,
IndexInst: *index.Instance,
TransferMode: common.TokenTransferModeCopy,
}
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
}
//////////////////////////////////////////////////////////////
// Integration with Metadata Provider
/////////////////////////////////////////////////////////////
func ExecutePlan(clusterUrl string, indexSpecs []*IndexSpec, nodes []string, override bool) (*Solution, error) {
plan, err := RetrievePlanFromCluster(clusterUrl, nodes)
if err != nil {
return nil, errors.New(fmt.Sprintf("Unable to read index layout from cluster %v. err = %s", clusterUrl, err))
}
if override && len(nodes) != 0 {
for _, indexer := range plan.Placement {
found := false
for _, node := range nodes {
if indexer.NodeId == node {
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)
}
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)
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 {
if index.DefnId == defnId {
replicaNodes = append(replicaNodes, indexer.NodeId)
}
}
}
return replicaNodes, nil
}
func ExecuteReplicaRepair(clusterUrl string, defnId common.IndexDefnId, increment int, nodes []string, override bool) (*Solution, error) {
plan, err := RetrievePlanFromCluster(clusterUrl, nodes)
if err != nil {
return nil, fmt.Errorf("Unable to read index layout from cluster %v. err = %s", clusterUrl, err)
}
if override && len(nodes) != 0 {
for _, indexer := range plan.Placement {
found := false
for _, node := range nodes {
if indexer.NodeId == node {
found = true
break
}
}
if found {
indexer.UnsetExclude()
} else {
indexer.SetExclude("in")
}
}
}
config := DefaultRunConfig()
config.Detail = logging.IsEnabled(logging.Info)
config.Resize = false
p, err := replicaRepair(config, plan, defnId, increment)
if p != nil && config.Detail {
logging.Infof("************ Indexer Layout *************")
p.Print()
logging.Infof("****************************************")
}
if err != nil {
return nil, err
}
return p.Result, nil
}
func ExecuteReplicaDrop(clusterUrl string, defnId common.IndexDefnId, nodes []string, numPartition int, decrement int, dropReplicaId int) (*Solution, []int, error) {
plan, err := RetrievePlanFromCluster(clusterUrl, nodes)
if err != nil {
return nil, nil, fmt.Errorf("Unable to read index layout from cluster %v. err = %s", clusterUrl, err)
}
config := DefaultRunConfig()
config.Detail = logging.IsEnabled(logging.Info)
config.Resize = false
p, original, result, err := replicaDrop(config, plan, defnId, numPartition, decrement, dropReplicaId)
if p != nil && config.Detail {
logging.Infof("************ Indexer Layout *************")
p.Print()
logging.Infof("****************************************")
}
if err != nil {
return nil, nil, err
}
return original, result, nil
}
func ExecuteRetrieve(clusterUrl string, nodes []string, output string) (*Solution, error) {
plan, err := RetrievePlanFromCluster(clusterUrl, nodes)
if err != nil {
return nil, errors.New(fmt.Sprintf("Unable to read index layout from cluster %v. err = %s", clusterUrl, err))
}
config := DefaultRunConfig()
config.Detail = logging.IsEnabled(logging.Info)
config.Resize = false
config.Output = output
return ExecuteRetrieveWithOptions(plan, config)
}
func ExecuteRetrieveWithOptions(plan *Plan, config *RunConfig) (*Solution, error) {
sizing := newGeneralSizingMethod()
solution, constraint, _, _, _ := solutionFromPlan(CommandRebalance, config, sizing, plan)
if config.Output != "" {
if err := savePlan(config.Output, solution, constraint); err != nil {
return nil, err
}
}
return solution, nil
}
//////////////////////////////////////////////////////////////
// Execution
/////////////////////////////////////////////////////////////
func ExecutePlanWithOptions(plan *Plan, indexSpecs []*IndexSpec, detail bool, genStmt string,
output string, addNode int, cpuQuota int, memQuota int64, allowUnpin bool, useLive bool) (*Solution, error) {
resize := false
if plan == nil {
resize = true
}
config := DefaultRunConfig()
config.Detail = detail
config.GenStmt = genStmt
config.Resize = resize
config.Output = output
config.AddNode = addNode
config.MemQuota = memQuota
config.CpuQuota = cpuQuota
config.AllowUnpin = allowUnpin
config.UseLive = useLive
p, _, err := execute(config, CommandPlan, plan, indexSpecs, ([]string)(nil))
if p != nil && detail {
logging.Infof("************ Indexer Layout *************")
p.Print()
logging.Infof("****************************************")
}
if p != nil {
return p.Result, err
}
return nil, err
}
func ExecuteRebalanceWithOptions(plan *Plan, indexSpecs []*IndexSpec, detail bool, genStmt string,
output string, addNode int, cpuQuota int, memQuota int64, allowUnpin bool, deletedNodes []string) (*Solution, error) {
config := DefaultRunConfig()
config.Detail = detail
config.GenStmt = genStmt
config.Resize = false
config.Output = output
config.AddNode = addNode
config.MemQuota = memQuota
config.CpuQuota = cpuQuota
config.AllowUnpin = allowUnpin
p, _, err := execute(config, CommandRebalance, plan, indexSpecs, deletedNodes)
if detail {
logging.Infof("************ Indexer Layout *************")
p.PrintLayout()
logging.Infof("****************************************")
}
if p != nil {
return p.Result, err
}
return nil, err
}
func ExecuteSwapWithOptions(plan *Plan, detail bool, genStmt string,
output string, addNode int, cpuQuota int, memQuota int64, allowUnpin bool, deletedNodes []string) (*Solution, error) {
config := DefaultRunConfig()
config.Detail = detail
config.GenStmt = genStmt
config.Resize = false
config.Output = output
config.AddNode = addNode
config.MemQuota = memQuota
config.CpuQuota = cpuQuota
config.AllowUnpin = allowUnpin
p, _, err := execute(config, CommandSwap, plan, nil, deletedNodes)
if detail {
logging.Infof("************ Indexer Layout *************")
p.PrintLayout()
logging.Infof("****************************************")
}
if p != nil {
return p.Result, err
}
return nil, err
}
func execute(config *RunConfig, command CommandType, p *Plan, indexSpecs []*IndexSpec, deletedNodes []string) (*SAPlanner, *RunStats, error) {
var indexes []*IndexUsage
var err error
sizing := newGeneralSizingMethod()
if command == CommandPlan {
if indexSpecs != nil {
indexes, err = IndexUsagesFromSpec(sizing, indexSpecs)
if err != nil {
return nil, nil, err
}
} else {
return nil, nil, errors.New("missing argument: index spec must be present")
}
return plan(config, p, indexes)
} else if command == CommandRebalance || command == CommandSwap {
if p == nil {
return nil, nil, errors.New("missing argument: either workload or plan must be present")
}
return rebalance(command, config, p, indexes, deletedNodes)
} else {
panic(fmt.Sprintf("uknown command: %v", command))
}
return nil, nil, nil
}
func plan(config *RunConfig, plan *Plan, indexes []*IndexUsage) (*SAPlanner, *RunStats, error) {
var constraint ConstraintMethod
var sizing SizingMethod
var placement PlacementMethod
var cost CostMethod
var solution *Solution
var initialIndexes []*IndexUsage
sizing = newGeneralSizingMethod()
// update runtime stats
s := &RunStats{}
setIndexPlacementStats(s, indexes, false)
// create a solution
if plan != nil {
// create a solution from plan
var movedIndex, movedData uint64
solution, constraint, initialIndexes, movedIndex, movedData = solutionFromPlan(CommandPlan, config, sizing, plan)
setInitialLayoutStats(s, config, constraint, solution, initialIndexes, movedIndex, movedData, false)
} else {
// create an empty solution
solution, constraint = emptySolution(config, sizing, indexes)
}
// create placement method
if plan != nil && config.AllowMove {
// incremental placement with move
total := ([]*IndexUsage)(nil)
total = append(total, initialIndexes...)
total = append(total, indexes...)
total = filterPinnedIndexes(config, total)
placement = newRandomPlacement(total, config.AllowSwap, false)
} else {
// initial placement
indexes = filterPinnedIndexes(config, indexes)
placement = newRandomPlacement(indexes, config.AllowSwap, false)
}
// Compute Index Sizing info and add them to solution
computeNewIndexSizingInfo(solution, indexes)
if err := placement.Add(solution, indexes); err != nil {
return nil, nil, err
}
// run planner
cost = newUsageBasedCostMethod(constraint, config.DataCostWeight, config.CpuCostWeight, config.MemCostWeight)
planner := newSAPlanner(cost, constraint, placement, sizing)
if _, err := planner.Plan(CommandPlan, solution); err != nil {
return planner, s, err
}
// save result
s.MemoryQuota = constraint.GetMemQuota()
s.CpuQuota = constraint.GetCpuQuota()
if config.Output != "" {
if err := savePlan(config.Output, planner.Result, constraint); err != nil {
return nil, nil, err
}
}
if config.GenStmt != "" {
if err := genCreateIndexDDL(config.GenStmt, planner.Result); err != nil {
return nil, nil, err
}
}
return planner, s, nil
}
func rebalance(command CommandType, config *RunConfig, plan *Plan, indexes []*IndexUsage, deletedNodes []string) (*SAPlanner, *RunStats, error) {
var constraint ConstraintMethod
var sizing SizingMethod
var placement PlacementMethod
var cost CostMethod
var solution *Solution
var initialIndexes []*IndexUsage
var outIndexes []*IndexUsage
var err error
s := &RunStats{}
sizing = newGeneralSizingMethod()
// create an initial solution
if plan != nil {
// create an initial solution from plan
var movedIndex, movedData uint64
solution, constraint, initialIndexes, movedIndex, movedData = solutionFromPlan(command, config, sizing, plan)
setInitialLayoutStats(s, config, constraint, solution, initialIndexes, movedIndex, movedData, true)
} else {
// create an initial solution
initialIndexes = indexes
solution, constraint, err = initialSolution(config, sizing, initialIndexes)
if err != nil {
return nil, nil, err
}
setInitialLayoutStats(s, config, constraint, solution, initialIndexes, 0, 0, false)
}
// change topology before rebalancing
outIndexes, err = changeTopology(config, solution, deletedNodes)
if err != nil {
return nil, nil, err
}
//
// create placement method
// 1) Swap rebalancing: If there are any nodes being ejected, only consider those indexes.
// 2) General Rebalancing: If option EjectOnly is true, then this is no-op. Otherwise consider all indexes in all nodes.
//
if len(outIndexes) != 0 {
indexes = outIndexes
} else if !config.EjectOnly {
indexes = initialIndexes
} else {
indexes = nil
}
if command == CommandRebalance && (len(outIndexes) != 0 || solution.findNumEmptyNodes() != 0) {
partitioned := findAllPartitionedIndexExcluding(solution, indexes)
if len(partitioned) != 0 {
indexes = append(indexes, partitioned...)
}
}
// run planner
placement = newRandomPlacement(indexes, config.AllowSwap, command == CommandSwap)
cost = newUsageBasedCostMethod(constraint, config.DataCostWeight, config.CpuCostWeight, config.MemCostWeight)
planner := newSAPlanner(cost, constraint, placement, sizing)
planner.SetTimeout(config.Timeout)
planner.SetRuntime(config.Runtime)
planner.SetVariationThreshold(config.Threshold)
planner.SetCpuProfile(config.CpuProfile)
if config.Detail {
logging.Infof("************ Index Layout Before Rebalance *************")
solution.PrintLayout()
logging.Infof("****************************************")
}
if _, err := planner.Plan(command, solution); err != nil {
return planner, s, err
}
// save result
s.MemoryQuota = constraint.GetMemQuota()
s.CpuQuota = constraint.GetCpuQuota()
if config.Output != "" {
if err := savePlan(config.Output, planner.Result, constraint); err != nil {
return nil, nil, err
}
}
return planner, s, nil
}
func replicaRepair(config *RunConfig, plan *Plan, defnId common.IndexDefnId, increment int) (*SAPlanner, error) {
var constraint ConstraintMethod
var sizing SizingMethod
var placement PlacementMethod
var cost CostMethod
var solution *Solution
// create an initial solution from plan
sizing = newGeneralSizingMethod()
solution, constraint, _, _, _ = solutionFromPlan(CommandRepair, config, sizing, plan)
// run planner
placement = newRandomPlacement(nil, config.AllowSwap, false)
cost = newUsageBasedCostMethod(constraint, config.DataCostWeight, config.CpuCostWeight, config.MemCostWeight)
planner := newSAPlanner(cost, constraint, placement, sizing)
planner.SetTimeout(config.Timeout)
planner.SetRuntime(config.Runtime)
planner.SetVariationThreshold(config.Threshold)
planner.SetCpuProfile(config.CpuProfile)
for _, indexer := range solution.Placement {
for _, index := range indexer.Indexes {
if index.DefnId == defnId {
index.Instance.Defn.NumReplica += uint32(increment)
}
}
}
if config.Detail {
logging.Infof("************ Index Layout Before Rebalance *************")
solution.PrintLayout()
logging.Infof("****************************************")
}
if _, err := planner.Plan(CommandRepair, solution); err != nil {
return planner, err
}
return planner, nil
}
func replicaDrop(config *RunConfig, plan *Plan, defnId common.IndexDefnId, numPartition int, decrement int, dropReplicaId int) (*SAPlanner, *Solution, []int, error) {
var constraint ConstraintMethod
var sizing SizingMethod
var placement PlacementMethod
var cost CostMethod
var solution *Solution
var err error
var result []int
var original *Solution
// create an initial solution from plan
sizing = newGeneralSizingMethod()
solution, constraint, _, _, _ = solutionFromPlan(CommandDrop, config, sizing, plan)
// run planner
placement = newRandomPlacement(nil, config.AllowSwap, false)
cost = newUsageBasedCostMethod(constraint, config.DataCostWeight, config.CpuCostWeight, config.MemCostWeight)
planner := newSAPlanner(cost, constraint, placement, sizing)
planner.SetTimeout(config.Timeout)
planner.SetRuntime(config.Runtime)
planner.SetVariationThreshold(config.Threshold)
planner.SetCpuProfile(config.CpuProfile)
if config.Detail {
logging.Infof("************ Index Layout Before Drop Replica *************")
solution.PrintLayout()
logging.Infof("****************************************")
}
original, result, err = planner.DropReplica(solution, defnId, numPartition, decrement, dropReplicaId)