-
Notifications
You must be signed in to change notification settings - Fork 36
/
planner.go
6559 lines (5355 loc) · 171 KB
/
planner.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 (
"errors"
"fmt"
"math"
"math/rand"
"sort"
"strconv"
"sync"
"time"
"github.com/couchbase/indexing/secondary/common"
"github.com/couchbase/indexing/secondary/logging"
)
//TODO
// - retry proxy when there is transient netowrk error
// - tuning parameter (spock)
// - generate cpu usage stats for index (spock)
// - generate move index statement (spock)
// - handle cloned index in proxy (spock)
// - provide an option to find out index that violates HA property
// - support saving plan in utility
//////////////////////////////////////////////////////////////
// Constant
//////////////////////////////////////////////////////////////
// constant - simulated annealing
const (
IterationPerTemp int = 1000
ResizePerIteration int = 1000
RunPerPlan int = 12
MaxTemperature float64 = 1.0
MinTemperature float64 = 0.00001
Alpha float64 = 0.90
MinNumMove int64 = 1
MinNumPositiveMove int64 = 1
)
// constant - index sizing - MOI
const (
MOIMutationRatePerCore uint64 = 25000
MOIScanRatePerCore = 5000
MOIScanTimeout = 120
)
// constant - command
type CommandType string
const (
CommandPlan CommandType = "plan"
CommandRebalance = "rebalance"
CommandSwap = "swap"
CommandRepair = "repair"
CommandDrop = "drop"
)
// constant - violation code
type ViolationCode string
const (
NoViolation ViolationCode = "NoViolation"
MemoryViolation = "MemoryViolation"
CpuViolation = "CpuViolation"
ReplicaViolation = "ReplicaViolation"
EquivIndexViolation = "EquivIndexViolation"
ServerGroupViolation = "ServerGroupViolation"
DeleteNodeViolation = "DeleteNodeViolation"
ExcludeNodeViolation = "ExcludeNodeViolation"
)
const (
EMPTY_INDEX_DATASIZE = 8
EMPTY_INDEX_MEMUSAGE = 8
)
//////////////////////////////////////////////////////////////
// Interface
//////////////////////////////////////////////////////////////
type Planner interface {
Plan(indexers []*IndexerNode, indexes []*IndexUsage) *Solution
Print()
}
type CostMethod interface {
Cost(s *Solution) float64
Print()
Validate(s *Solution) error
GetMemMean() float64
GetCpuMean() float64
GetDataMean() float64
GetDiskMean() float64
GetScanMean() float64
GetDrainMean() float64
ComputeResourceVariation() float64
}
type PlacementMethod interface {
Move(s *Solution) (bool, bool, bool)
Add(s *Solution, indexes []*IndexUsage) error
InitialPlace(s *Solution, indexes []*IndexUsage) error
Validate(s *Solution) error
GetEligibleIndexes() map[*IndexUsage]bool
IsEligibleIndex(*IndexUsage) bool
AddOptionalIndexes([]*IndexUsage)
AddRequiredIndexes([]*IndexUsage)
RemoveOptionalIndexes() []*IndexUsage
HasOptionalIndexes() bool
RemoveEligibleIndex([]*IndexUsage)
Print()
}
type ConstraintMethod interface {
GetMemQuota() uint64
GetCpuQuota() uint64
SatisfyClusterResourceConstraint(s *Solution) bool
SatisfyNodeResourceConstraint(s *Solution, n *IndexerNode) bool
SatisfyNodeHAConstraint(s *Solution, n *IndexerNode, eligibles map[*IndexUsage]bool) bool
SatisfyIndexHAConstraint(s *Solution, n *IndexerNode, index *IndexUsage, eligibles map[*IndexUsage]bool) bool
SatisfyClusterConstraint(s *Solution, eligibles map[*IndexUsage]bool) bool
SatisfyNodeConstraint(s *Solution, n *IndexerNode, eligibles map[*IndexUsage]bool) bool
SatisfyServerGroupConstraint(s *Solution, n *IndexUsage, group string) bool
CanAddIndex(s *Solution, n *IndexerNode, u *IndexUsage) ViolationCode
CanSwapIndex(s *Solution, n *IndexerNode, t *IndexUsage, i *IndexUsage) ViolationCode
CanAddNode(s *Solution) bool
Print()
Validate(s *Solution) error
GetViolations(s *Solution, indexes map[*IndexUsage]bool) *Violations
}
type SizingMethod interface {
ComputeIndexSize(u *IndexUsage)
ComputeIndexerOverhead(n *IndexerNode)
ComputeIndexerSize(n *IndexerNode)
ComputeIndexOverhead(idx *IndexUsage) uint64
ComputeMinQuota(u []*IndexUsage, useLive bool) (uint64, uint64)
Validate(s *Solution) error
}
//////////////////////////////////////////////////////////////
// Concrete Type/Struct
//////////////////////////////////////////////////////////////
type ServerGroupMap map[common.IndexDefnId]map[common.PartitionId]map[int]string
type ReplicaMap map[common.IndexDefnId]map[common.PartitionId]map[int]*IndexUsage
type UsedReplicaIdMap map[common.IndexDefnId]map[int]bool
type IndexerNode struct {
// input: node identification
NodeId string `json:"nodeId"`
NodeUUID string `json:"nodeUUID"`
IndexerId string `json:"indexerId"`
RestUrl string `json:"restUrl"`
ServerGroup string `json:"serverGroup,omitempty"`
StorageMode string `json:"storageMode,omitempty"`
// input/output: resource consumption (from sizing)
MemUsage uint64 `json:"memUsage"`
CpuUsage float64 `json:"cpuUsage"`
DiskUsage uint64 `json:"diskUsage,omitempty"`
MemOverhead uint64 `json:"memOverhead"`
DataSize uint64 `json:"dataSize"`
// input/output: resource consumption (from live cluster)
ActualMemUsage uint64 `json:"actualMemUsage"`
ActualMemOverhead uint64 `json:"actualMemOverhead"`
ActualCpuUsage float64 `json:"actualCpuUsage"`
ActualDataSize uint64 `json:"actualDataSize"`
ActualDiskUsage uint64 `json:"actualDiskUsage"`
ActualDrainRate uint64 `json:"actualDrainRate"`
ActualScanRate uint64 `json:"actualScanRate"`
ActualMemMin uint64 `json:"actualMemMin"`
// input: index residing on the node
Indexes []*IndexUsage `json:"indexes"`
// input: node status
isDelete bool
isNew bool
exclude string
// intput/output: planning
meetConstraint bool
numEmptyIndex int
hasEligible bool
totalData uint64
totalIndex uint64
dataMovedIn uint64
indexMovedIn uint64
}
type IndexUsage struct {
// input: index identification
DefnId common.IndexDefnId `json:"defnId"`
InstId common.IndexInstId `json:"instId"`
PartnId common.PartitionId `json:"partnId"`
Name string `json:"name"`
Bucket string `json:"bucket"`
Scope string `json:"scope"`
Collection string `json:"collection"`
Hosts []string `json:"host"`
// input: index sizing
IsPrimary bool `json:"isPrimary,omitempty"`
StorageMode string `json:"storageMode,omitempty"`
AvgSecKeySize uint64 `json:"avgSecKeySize"`
AvgDocKeySize uint64 `json:"avgDocKeySize"`
AvgArrSize uint64 `json:"avgArrSize"`
AvgArrKeySize uint64 `json:"avgArrKeySize"`
NumOfDocs uint64 `json:"numOfDocs"`
ResidentRatio float64 `json:"residentRatio,omitempty"`
MutationRate uint64 `json:"mutationRate"`
DrainRate uint64 `json:"drainRate"`
ScanRate uint64 `json:"scanRate"`
// input: resource consumption (from sizing equation)
MemUsage uint64 `json:"memUsage"`
CpuUsage float64 `json:"cpuUsage"`
DiskUsage uint64 `json:"diskUsage,omitempty"`
MemOverhead uint64 `json:"memOverhead,omitempty"`
DataSize uint64 `json:"dataSize,omitempty"`
// input: resource consumption (from live cluster)
ActualMemUsage uint64 `json:"actualMemUsage"`
ActualMemOverhead uint64 `json:"actualMemOverhead"`
ActualKeySize uint64 `json:"actualKeySize"`
ActualCpuUsage float64 `json:"actualCpuUsage"`
ActualBuildPercent uint64 `json:"actualBuildPercent"`
ActualResidentPercent uint64 `json:"actualResidentPercent"`
ActualDataSize uint64 `json:"actualDataSize"`
ActualNumDocs uint64 `json:"actualNumDocs"`
ActualDiskUsage uint64 `json:"actualDiskUsage"`
ActualMemStats uint64 `json:"actualMemStats"`
ActualDrainRate uint64 `json:"actualDrainRate"`
ActualScanRate uint64 `json:"actualScanRate"`
ActualMemMin uint64 `json:"actualMemMin"`
// input: resource consumption (estimated sizing)
NoUsageInfo bool `json:"NoUsageInfo"`
EstimatedMemUsage uint64 `json:"estimatedMemUsage"`
EstimatedDataSize uint64 `json:"estimatedDataSize"`
NeedsEstimate bool `json:"NeedsEstimate"`
// input: index definition (optional)
Instance *common.IndexInst `json:"instance,omitempty"`
// input: node where index initially placed (optional)
// for new indexes to be placed on an existing topology (e.g. live cluster), this must not be set.
initialNode *IndexerNode
// The node to which planner moves this index from initialNode
// Equals "initialNode" if planner does not move the index
destNode *IndexerNode
// input: flag to indicate if the index in delete or create token
pendingDelete bool // true if there is a delete token associated with this index
pendingCreate bool // true if there is a create token associated with this index
pendingBuild bool // true if there is a build token associated with this index
// mutable: hint for placement / constraint
suppressEquivIdxCheck bool
// Copy of the index state from the corresponding index instance.
state common.IndexState
// Miscellaneous fields
partnStatPrefix string
instStatPrefix string
eligible bool
}
type Solution struct {
command CommandType
constraint ConstraintMethod
sizing SizingMethod
cost CostMethod
place PlacementMethod
isLiveData bool
useLiveData bool
disableRepair bool
initialPlan bool
numServerGroup int
numDeletedNode int
numNewNode int
// for size estimation
estimatedIndexSize uint64
estimate bool
numEstimateRun int
// for rebalance
enableExclude bool
// for resource utilization
memMean float64
cpuMean float64
dataMean float64
diskMean float64
drainMean float64
scanMean float64
// placement of indexes in nodes
Placement []*IndexerNode `json:"placement,omitempty"`
// maps for non-eligible indexes
indexSGMap ServerGroupMap
replicaMap ReplicaMap
usedReplicaIdMap UsedReplicaIdMap
// maps for eligible indexes
// with large number of indexes, cloning these maps after every planner
// iteration becomes a bottleneck. As planner only moves the list of
// eligible indexes, maps of non-eligible indexes will not change and
// clone method can just copy the reference to the existing map.
eligIndexSGMap ServerGroupMap
eligReplicaMap ReplicaMap
eligUsedReplicaIdMap UsedReplicaIdMap
// constraint check
enforceConstraint bool
}
type Violations struct {
Violations []*Violation
MemQuota uint64
CpuQuota uint64
}
type Violation struct {
Name string
Bucket string
Scope string
Collection string
NodeId string
CpuUsage float64
MemUsage uint64
Details []string
}
//////////////////////////////////////////////////////////////
// Interface Implementation - Planner
//////////////////////////////////////////////////////////////
type SAPlanner struct {
placement PlacementMethod
cost CostMethod
constraint ConstraintMethod
sizing SizingMethod
// config
timeout int
runtime *time.Time
threshold float64
cpuProfile bool
// result
Result *Solution `json:"result,omitempty"`
Score float64 `json:"score,omitempty"`
ElapseTime uint64 `json:"elapsedTime,omitempty"`
ConvergenceTime uint64 `json:"convergenceTime,omitempty"`
Iteration uint64 `json:"iteration,omitempty"`
Move uint64 `json:"move,omitempty"`
PositiveMove uint64 `json:"positiveMove,omitempty"`
StartTemp float64 `json:"startTemp,omitempty"`
StartScore float64 `json:"startScore,omitempty"`
Try uint64 `json:"try,omitempty"`
}
//////////////////////////////////////////////////////////////
// Interface Implementation - CostMethod
//////////////////////////////////////////////////////////////
type UsageBasedCostMethod struct {
MemMean float64 `json:"memMean,omitempty"`
MemStdDev float64 `json:"memStdDev,omitempty"`
CpuMean float64 `json:"cpuMean,omitempty"`
CpuStdDev float64 `json:"cpuStdDev,omitempty"`
DiskMean float64 `json:"diskMean,omitempty"`
DiskStdDev float64 `json:"diskStdDev,omitempty"`
DrainMean float64 `json:"drainMean,omitempty"`
DrainStdDev float64 `json:"drainStdDev,omitempty"`
ScanMean float64 `json:"scanMean,omitempty"`
ScanStdDev float64 `json:"scanStdDev,omitempty"`
DataSizeMean float64 `json:"dataSizeMean,omitempty"`
DataSizeStdDev float64 `json:"dataSizeStdDev,omitempty"`
TotalData uint64 `json:"totalData,omitempty"`
DataMoved uint64 `json:"dataMoved,omitempty"`
TotalIndex uint64 `json:"totalIndex,omitempty"`
IndexMoved uint64 `json:"indexMoved,omitempty"`
constraint ConstraintMethod
dataCostWeight float64
cpuCostWeight float64
memCostWeight float64
}
//////////////////////////////////////////////////////////////
// Interface Implementation - PlacementMethod
//////////////////////////////////////////////////////////////
type RandomPlacement struct {
rs *rand.Rand
indexes map[*IndexUsage]bool
eligibles []*IndexUsage
optionals []*IndexUsage
allowSwap bool
swapDeletedOnly bool
// stats
totalIteration int
randomSwapCnt int
randomSwapDur int64
randomSwapRetry int
randomMoveCnt int
randomMoveEmptyCnt int
randomMoveDur int64
exhaustSwapCnt int
exhaustSwapDur int64
exhaustMoveCnt int
exhaustMoveDur int64
}
//////////////////////////////////////////////////////////////
// Interface Implementation - SizingMethod
//////////////////////////////////////////////////////////////
type GeneralSizingMethod struct {
MOI *MOISizingMethod
Plasma *PlasmaSizingMethod
}
type MOISizingMethod struct {
}
type PlasmaSizingMethod struct {
}
//////////////////////////////////////////////////////////////
// Interface Implementation - ConstraintMethod
//////////////////////////////////////////////////////////////
type IndexerConstraint struct {
// system level constraint
MemQuota uint64 `json:"memQuota,omitempty"`
CpuQuota uint64 `json:"cpuQuota,omitempty"`
MaxMemUse int64 `json:"maxMemUse,omitempty"`
MaxCpuUse int64 `json:"maxCpuUse,omitempty"`
canResize bool
maxNumNode uint64
}
//////////////////////////////////////////////////////////////
// Sync pool
//////////////////////////////////////////////////////////////
type SolutionPool struct {
pool *sync.Pool
}
func newSolutionPool() *SolutionPool {
fn := func() interface{} {
return &Solution{}
}
return &SolutionPool{
pool: &sync.Pool{
New: fn,
},
}
}
func (p *SolutionPool) Get() *Solution {
return p.pool.Get().(*Solution)
}
func (p *SolutionPool) Put(buf *Solution) {
p.pool.Put(buf)
}
type IndexerNodePool struct {
pool *sync.Pool
}
func newIndexerNodePool() *IndexerNodePool {
fn := func() interface{} {
return &IndexerNode{}
}
return &IndexerNodePool{
pool: &sync.Pool{
New: fn,
},
}
}
func (p *IndexerNodePool) Get() *IndexerNode {
return p.pool.Get().(*IndexerNode)
}
func (p *IndexerNodePool) Put(buf *IndexerNode) {
p.pool.Put(buf)
}
var solutionPool *SolutionPool
var indexerNodePool *IndexerNodePool
func init() {
solutionPool = newSolutionPool()
indexerNodePool = newIndexerNodePool()
}
//////////////////////////////////////////////////////////////
// SAPlanner
//////////////////////////////////////////////////////////////
//
// Constructor
//
func newSAPlanner(cost CostMethod, constraint ConstraintMethod, placement PlacementMethod, sizing SizingMethod) *SAPlanner {
return &SAPlanner{
cost: cost,
constraint: constraint,
placement: placement,
sizing: sizing,
}
}
//
// Given a solution, this function use simulated annealing
// to find an alternative solution with a lower cost.
//
func (p *SAPlanner) Plan(command CommandType, solution *Solution) (*Solution, error) {
if p.cpuProfile {
startCPUProfile("planner.pprof")
defer stopCPUProfile()
}
var result *Solution
var err error
var violations *Violations
solution.command = command
solution = p.adjustInitialSolutionIfNecessary(solution)
solution.enforceConstraint = true
for i := 0; i < RunPerPlan; i++ {
p.Try++
startTime := time.Now()
solution.runSizeEstimation(p.placement)
solution.evaluateNodes()
err = p.Validate(solution)
if err == nil {
result, err, violations = p.planSingleRun(command, solution)
if violations == nil {
return result, err
}
err = errors.New(violations.Error())
// copy estimation information
if result != nil {
solution.copyEstimationFrom(result)
}
}
logging.Infof("Planner::Fail to create plan satisyfig constraint. Re-planning. Num of Try=%v. Elapsed Time=%v",
p.Try, formatTimeStr(uint64(time.Now().Sub(startTime).Nanoseconds())))
// reduce minimum memory for each round
solution.reduceMinimumMemory()
// If planner get to this point, it means we see violation errors.
// If planner has retries 3 times, then remove any optional indexes.
if i > 3 && p.placement.HasOptionalIndexes() {
logging.Infof("Cannot rebuild lost replica due to resource constraint in cluster. Will not rebuild lost replica.")
logging.Warnf(err.Error())
optionals := p.placement.RemoveOptionalIndexes()
solution.demoteEligIndexes(optionals)
solution.removeIndexes(optionals)
}
// After 6 tries, disable resource constraint check needed
if i == 5 && solution.enforceConstraint {
// can relax constraint if there is deleted node or it is not rebalancing
solution.enforceConstraint = !(solution.numDeletedNode > 0 || solution.command == CommandPlan || solution.command == CommandRepair)
if !solution.enforceConstraint {
logging.Warnf("Unable to find a solution with rersource costraint. Relax resource constraint check.")
}
}
// If cannot find a solution after 9 tries and there are deleted nodes, then disable exclude flag.
if i == 9 && solution.numDeletedNode != 0 {
solution.enableExclude = false
}
}
// Ignore error for rebalancing error when there is no deleted node
if err != nil && (solution.command == CommandRebalance || solution.command == CommandSwap) {
if solution.numDeletedNode == 0 {
err = nil
p.Result = solution
result = solution
}
}
if err != nil {
logging.Errorf(err.Error())
}
return result, err
}
//
// Given a solution, this function finds a replica to drop while
// maintaining HA constraint.
//
func (p *SAPlanner) DropReplica(solution *Solution, defnId common.IndexDefnId, numPartition int, decrement int, dropReplicaId int) (*Solution, []int, error) {
// setup
if p.cpuProfile {
startCPUProfile("planner.pprof")
defer stopCPUProfile()
}
solution.command = CommandDrop
solution = p.adjustInitialSolutionIfNecessary(solution)
// set eligible index
var eligibles []*IndexUsage
for _, indexer := range solution.Placement {
for _, index := range indexer.Indexes {
if index.DefnId == defnId {
index.eligible = true
eligibles = append(eligibles, index)
}
}
}
p.placement.AddRequiredIndexes(eligibles)
// find all replicaId for the definition
// healthy replica -- replica with all partitions
// unhealthy replica -- replica with missing partitions
allReplicaIds := solution.getReplicas(defnId)
replicaPartitionMap := make(map[int]map[common.PartitionId]bool)
for partitionId, replicaIds := range allReplicaIds {
for replicaId, _ := range replicaIds {
if _, ok := replicaPartitionMap[replicaId]; !ok {
replicaPartitionMap[replicaId] = make(map[common.PartitionId]bool)
}
replicaPartitionMap[replicaId][partitionId] = true
}
}
// if a specific replicaId is specified, then drop that one.
if dropReplicaId != -1 {
if _, ok := replicaPartitionMap[dropReplicaId]; ok {
return solution, []int{dropReplicaId}, nil
} else {
msg1 := fmt.Sprintf("Fail to drop replica. Replica (%v) does not exist.", dropReplicaId)
msg2 := "If the replica has been rebalanced out of the cluster, it will be repaired when a new indexer node is rebalanced in."
msg3 := "Use alter index to lower the replica count to avoid repair during next rebalance."
return nil, nil, fmt.Errorf("%v %v %v", msg1, msg2, msg3)
}
}
if len(eligibles) != 0 {
u := eligibles[0]
if u.Instance != nil {
// If cluster has already fewer replica than requested, then just return.
if int(u.Instance.Defn.NumReplica)-decrement+1 >= len(replicaPartitionMap) {
return solution, []int{}, nil
}
}
}
var unhealthy []int
var healthy []int
for replicaId, partitionIds := range replicaPartitionMap {
if len(partitionIds) == numPartition {
healthy = append(healthy, replicaId)
} else {
unhealthy = append(unhealthy, replicaId)
}
}
if len(healthy)+len(unhealthy)-decrement <= 0 {
return nil, nil, fmt.Errorf("Index only has %v replica. Cannot satsify request to drop %v copy", len(healthy)+len(unhealthy)-1, decrement)
}
reverse := func(arr []int) {
sort.Ints(arr)
for i := 0; i < len(arr)/2; i++ {
tmp := arr[i]
arr[i] = arr[len(arr)-1-i]
arr[len(arr)-1-i] = tmp
}
}
// try to drop the unhealthy replica first
var result []int
numDrop := 0
current := solution.clone()
current.evaluateNodes()
reverse(unhealthy)
for _, replicaId := range unhealthy {
if numDrop == decrement {
p.Result = current
return solution, result, nil
}
current.removeReplicas(defnId, replicaId)
numDrop++
result = append(result, replicaId)
}
// Have we dropped enough replica yet?
if numDrop == decrement {
p.Result = current
return solution, result, nil
}
// try to drop the healthy replica
// make sure constraint is enforced
reverse(healthy)
for _, replicaId := range healthy {
if numDrop == decrement {
p.Result = current
return solution, result, nil
}
current.removeReplicas(defnId, replicaId)
if !p.constraint.SatisfyClusterConstraint(current, p.placement.GetEligibleIndexes()) {
logging.Warnf("Dropping replica %v for index %v. Cluster may not follow server group constraint after drop.",
replicaId, defnId)
}
numDrop++
result = append(result, replicaId)
}
if numDrop == decrement {
p.Result = current
return solution, result, nil
}
return nil, nil, fmt.Errorf("Unsable to drop %v replica without violating availability constraint", decrement)
}
//
// Given a solution, this function use simulated annealing
// to find an alternative solution with a lower cost.
//
func (p *SAPlanner) planSingleRun(command CommandType, solution *Solution) (*Solution, error, *Violations) {
current := solution.clone()
initialPlan := solution.initialPlan
logging.Tracef("Planner: memQuota %v (%v) cpuQuota %v",
p.constraint.GetMemQuota(), formatMemoryStr(p.constraint.GetMemQuota()), p.constraint.GetCpuQuota())
rs := rand.New(rand.NewSource(time.Now().UnixNano()))
old_cost := p.cost.Cost(current)
current.updateCost()
startScore := old_cost
startTime := time.Now()
lastUpdateTime := time.Now()
move := uint64(0)
iteration := uint64(0)
positiveMove := uint64(0)
temperature := p.initialTemperature(command, old_cost)
startTemp := temperature
done := false
eligibles := p.placement.GetEligibleIndexes()
if !p.constraint.SatisfyClusterConstraint(current, eligibles) {
temperature = MaxTemperature
startTemp = temperature
}
for temperature > MinTemperature && !done {
lastMove := move
lastPositiveMove := positiveMove
for i := 0; i < IterationPerTemp; i++ {
new_solution, force, final := p.findNeighbor(current)
if new_solution != nil {
new_cost := p.cost.Cost(new_solution)
prob := p.getAcceptProbability(old_cost, new_cost, temperature)
logging.Tracef("Planner::old_cost-new_cost %v new_cost % v temp %v prob %v force %v",
old_cost-new_cost, new_cost, temperature, prob, force)
if old_cost-new_cost > 0 {
positiveMove++
}
// if force=true, then jsut accept the new solution. Do
// not need to change the temperature since new solution
// could have higher score.
if force || prob > rs.Float64() {
current.free()
current = new_solution
current.updateCost()
old_cost = new_cost
lastUpdateTime = time.Now()
move++
logging.Tracef("Planner::accept solution: new_cost %v temp %v", new_cost, temperature)
} else {
new_solution.free()
}
iteration++
}
if final {
done = true
break
}
}
if int64(move-lastMove) < MinNumMove && int64(positiveMove-lastPositiveMove) < MinNumPositiveMove {
done = true
}
if p.threshold > 0 && current.cost.ComputeResourceVariation() <= p.threshold {
done = true
}
temperature = temperature * Alpha
if command == CommandPlan && initialPlan {
// adjust temperature based on score for faster convergence
temperature = temperature * old_cost
}
if p.timeout > 0 && p.runtime != nil {
elapsed := time.Now().Sub(*p.runtime).Seconds()
if elapsed >= float64(p.timeout) {
logging.Infof("Planner::stop planner due to timeout. Elapsed %vs", elapsed)
break
}
}
}
p.ElapseTime = uint64(time.Now().Sub(startTime).Nanoseconds())
p.ConvergenceTime = uint64(lastUpdateTime.Sub(startTime).Nanoseconds())
p.Result = current
p.Score = old_cost
p.StartTemp = startTemp
p.StartScore = startScore
p.Move = move
p.PositiveMove = positiveMove
p.Iteration = iteration
eligibles = p.placement.GetEligibleIndexes()
if !p.constraint.SatisfyClusterConstraint(p.Result, eligibles) {
return current, nil, p.constraint.GetViolations(p.Result, eligibles)
}
p.cost.Cost(p.Result)
return current, nil, nil
}
func (p *SAPlanner) SetTimeout(timeout int) {
p.timeout = timeout
}
func (p *SAPlanner) SetRuntime(runtime *time.Time) {
p.runtime = runtime
}
func (p *SAPlanner) SetVariationThreshold(threshold float64) {
p.threshold = threshold
}
func (p *SAPlanner) SetCpuProfile(cpuProfile bool) {
p.cpuProfile = cpuProfile
}
//
// Validate the solution
//
func (p *SAPlanner) Validate(s *Solution) error {
if err := p.sizing.Validate(s); err != nil {
return err
}
if err := p.cost.Validate(s); err != nil {
return err
}
if err := p.constraint.Validate(s); err != nil {
return err
}
if err := p.placement.Validate(s); err != nil {
return err
}
return nil
}
//
// This function prints the result of evaluation
//
func (p *SAPlanner) PrintRunSummary() {
logging.Infof("Score: %v", p.Score)
logging.Infof("variation: %v", p.cost.ComputeResourceVariation())
logging.Infof("ElapsedTime: %v", formatTimeStr(p.ElapseTime))
logging.Infof("ConvergenceTime: %v", formatTimeStr(p.ConvergenceTime))
logging.Infof("Iteration: %v", p.Iteration)
logging.Infof("Move: %v", p.Move)
}
//
// This function prints the result of evaluation
//
func (p *SAPlanner) Print() {
p.PrintRunSummary()
logging.Infof("----------------------------------------")
if p.Result != nil {
p.cost.Print()
logging.Infof("----------------------------------------")
p.Result.PrintStats()
logging.Infof("----------------------------------------")
p.constraint.Print()
logging.Infof("----------------------------------------")
p.placement.Print()
logging.Infof("----------------------------------------")
p.Result.PrintLayout()
}
}
//
// This function prints the result of evaluation
//
func (p *SAPlanner) PrintLayout() {
if p.Result != nil {
logging.Infof("----------------------------------------")
logging.Infof("Memory Quota: %v (%v)", p.constraint.GetMemQuota(),
formatMemoryStr(p.constraint.GetMemQuota()))
logging.Infof("CPU Quota: %v", p.constraint.GetCpuQuota())
logging.Infof("----------------------------------------")
p.cost.Print()
logging.Infof("----------------------------------------")
p.Result.PrintLayout()
} else {
logging.Infof("No result is available")
}
}
//
// This function prints the result of evaluation
//
func (p *SAPlanner) PrintCost() {
if p.Result != nil {
logging.Infof("Score: %v", p.Score)
logging.Infof("Memory Quota: %v (%v)", p.constraint.GetMemQuota(),
formatMemoryStr(p.constraint.GetMemQuota()))
logging.Infof("CPU Quota: %v", p.constraint.GetCpuQuota())
p.cost.Print()
} else {
logging.Infof("No result is available")
}
}
//
// This function finds a neigbhor placement layout using