github.com/didip/deis@v1.4.1/deisctl/backend/fleet/utils.go (about) 1 package fleet 2 3 import ( 4 "fmt" 5 "math/rand" 6 "regexp" 7 "sort" 8 "strconv" 9 "strings" 10 "time" 11 ) 12 13 func nextUnitNum(units []string) (num int, err error) { 14 count, err := countUnits(units) 15 if err != nil { 16 return 17 } 18 sort.Ints(count) 19 num = 1 20 for _, i := range count { 21 if num < i { 22 return num, nil 23 } 24 num++ 25 } 26 return num, nil 27 } 28 29 func lastUnitNum(units []string) (num int, err error) { 30 count, err := countUnits(units) 31 if err != nil { 32 return 33 } 34 num = 1 35 sort.Sort(sort.Reverse(sort.IntSlice(count))) 36 if len(count) == 0 { 37 return num, fmt.Errorf("Component not found") 38 } 39 return count[0], nil 40 } 41 42 func countUnits(units []string) (count []int, err error) { 43 for _, unit := range units { 44 _, n, err := splitJobName(unit) 45 if err != nil { 46 return []int{}, err 47 } 48 count = append(count, n) 49 } 50 return 51 } 52 53 func splitJobName(component string) (c string, num int, err error) { 54 r := regexp.MustCompile(`deis\-([a-z-]+)\@([\d]+)\.service`) 55 match := r.FindStringSubmatch(component) 56 if len(match) == 0 { 57 c, err = "", fmt.Errorf("Could not parse component: %v", component) 58 return 59 } 60 c = match[1] 61 num, err = strconv.Atoi(match[2]) 62 if err != nil { 63 return 64 } 65 return 66 } 67 68 func splitTarget(target string) (component string, num int, err error) { 69 // see if we were provided a specific target 70 r := regexp.MustCompile(`^([a-z-]+)(@\d+)?(\.service)?$`) 71 match := r.FindStringSubmatch(target) 72 // check for failed match 73 if len(match) < 3 { 74 err = fmt.Errorf("Could not parse target: %v", target) 75 return 76 } 77 if match[2] == "" { 78 component = match[1] 79 return component, 0, nil 80 } 81 num, err = strconv.Atoi(match[2][1:]) 82 if err != nil { 83 return "", 0, err 84 } 85 return match[1], num, err 86 } 87 88 // expand a target to all installed units 89 func expandTargets(c *FleetClient, targets []string) (expandedTargets []string, err error) { 90 for _, t := range targets { 91 if strings.HasSuffix(t, "@*") { 92 var targets []string 93 targets, err = expandTarget(c, strings.TrimSuffix(t, "@*")) 94 if err != nil { 95 return 96 } 97 expandedTargets = append(expandedTargets, targets...) 98 } else { 99 expandedTargets = append(expandedTargets, t) 100 } 101 102 } 103 return 104 } 105 106 func expandTarget(c *FleetClient, target string) (targets []string, err error) { 107 targets, err = c.Units(target) 108 return 109 } 110 111 // randomValue returns a random string from a slice of string 112 func randomValue(src []string) string { 113 s := rand.NewSource(int64(time.Now().Unix())) 114 r := rand.New(s) 115 idx := r.Intn(len(src)) 116 return src[idx] 117 }