github.com/didip/deis@v1.4.1/deisctl/backend/fleet/scale.go (about)

     1  package fleet
     2  
     3  import (
     4  	"errors"
     5  	"math"
     6  	"strconv"
     7  	"strings"
     8  	"sync"
     9  )
    10  
    11  // Scale creates or destroys units to match the desired number
    12  func (c *FleetClient) Scale(
    13  	component string, requested int, wg *sync.WaitGroup, outchan chan string, errchan chan error) {
    14  
    15  	if requested < 0 {
    16  		errchan <- errors.New("cannot scale below 0")
    17  	}
    18  	// check how many currently exist
    19  	components, err := c.Units(component)
    20  	if err != nil {
    21  		// skip checking the first time; we just want a tally
    22  		if !strings.Contains(err.Error(), "could not find unit") {
    23  			errchan <- err
    24  			return
    25  		}
    26  	}
    27  
    28  	timesToScale := int(math.Abs(float64(requested - len(components))))
    29  	if timesToScale == 0 {
    30  		return
    31  	}
    32  	if requested-len(components) > 0 {
    33  		scaleUp(c, component, len(components), timesToScale, wg, outchan, errchan)
    34  	} else {
    35  		scaleDown(c, component, len(components), timesToScale, wg, outchan, errchan)
    36  	}
    37  }
    38  
    39  func scaleUp(c *FleetClient, component string, numExistingContainers, numTimesToScale int,
    40  	wg *sync.WaitGroup, outchan chan string, errchan chan error) {
    41  	for i := 0; i < numTimesToScale; i++ {
    42  		target := component + "@" + strconv.Itoa(numExistingContainers+i+1)
    43  		c.Create([]string{target}, wg, outchan, errchan)
    44  	}
    45  	wg.Wait()
    46  	for i := 0; i < numTimesToScale; i++ {
    47  		target := component + "@" + strconv.Itoa(numExistingContainers+i+1)
    48  		c.Start([]string{target}, wg, outchan, errchan)
    49  	}
    50  }
    51  
    52  func scaleDown(c *FleetClient, component string, numExistingContainers, numTimesToScale int,
    53  	wg *sync.WaitGroup, outchan chan string, errchan chan error) {
    54  	for i := 0; i < numTimesToScale; i++ {
    55  		target := component + "@" + strconv.Itoa(numExistingContainers-i)
    56  		c.Destroy([]string{target}, wg, outchan, errchan)
    57  	}
    58  }