github.com/misfo/deis@v1.0.1-0.20141111224634-e0eee0392b8a/deisctl/backend/fleet/utils.go (about)

     1  package fleet
     2  
     3  import (
     4  	"fmt"
     5  	"math/rand"
     6  	"regexp"
     7  	"sort"
     8  	"strconv"
     9  	"time"
    10  )
    11  
    12  func nextUnitNum(units []string) (num int, err error) {
    13  	count, err := countUnits(units)
    14  	if err != nil {
    15  		return
    16  	}
    17  	sort.Ints(count)
    18  	num = 1
    19  	for _, i := range count {
    20  		if num < i {
    21  			return num, nil
    22  		}
    23  		num++
    24  	}
    25  	return num, nil
    26  }
    27  
    28  func lastUnitNum(units []string) (num int, err error) {
    29  	count, err := countUnits(units)
    30  	if err != nil {
    31  		return
    32  	}
    33  	num = 1
    34  	sort.Sort(sort.Reverse(sort.IntSlice(count)))
    35  	if len(count) == 0 {
    36  		return num, fmt.Errorf("Component not found")
    37  	}
    38  	return count[0], nil
    39  }
    40  
    41  func countUnits(units []string) (count []int, err error) {
    42  	for _, unit := range units {
    43  		_, n, err := splitJobName(unit)
    44  		if err != nil {
    45  			return []int{}, err
    46  		}
    47  		count = append(count, n)
    48  	}
    49  	return
    50  }
    51  
    52  func splitJobName(component string) (c string, num int, err error) {
    53  	r := regexp.MustCompile(`deis\-([a-z-]+)\@([\d]+)\.service`)
    54  	match := r.FindStringSubmatch(component)
    55  	if len(match) == 0 {
    56  		c, err = "", fmt.Errorf("Could not parse component: %v", component)
    57  		return
    58  	}
    59  	c = match[1]
    60  	num, err = strconv.Atoi(match[2])
    61  	if err != nil {
    62  		return
    63  	}
    64  	return
    65  }
    66  
    67  func splitTarget(target string) (component string, num int, err error) {
    68  	// see if we were provided a specific target
    69  	r := regexp.MustCompile(`^([a-z-]+)(@\d+)?$`)
    70  	match := r.FindStringSubmatch(target)
    71  	// check for failed match
    72  	if len(match) != 3 {
    73  		err = fmt.Errorf("Could not parse target: %v", target)
    74  		return
    75  	}
    76  	if match[2] == "" {
    77  		component = match[1]
    78  		return component, 0, nil
    79  	}
    80  	num, err = strconv.Atoi(match[2][1:])
    81  	if err != nil {
    82  		return "", 0, err
    83  	}
    84  	return match[1], num, err
    85  }
    86  
    87  // randomValue returns a random string from a slice of string
    88  func randomValue(src []string) string {
    89  	s := rand.NewSource(int64(time.Now().Unix()))
    90  	r := rand.New(s)
    91  	idx := r.Intn(len(src))
    92  	return src[idx]
    93  }