-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
117 lines (107 loc) · 2.43 KB
/
utils.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
package fleet
import (
"fmt"
"math/rand"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
func nextUnitNum(units []string) (num int, err error) {
count, err := countUnits(units)
if err != nil {
return
}
sort.Ints(count)
num = 1
for _, i := range count {
if num < i {
return num, nil
}
num++
}
return num, nil
}
func lastUnitNum(units []string) (num int, err error) {
count, err := countUnits(units)
if err != nil {
return
}
num = 1
sort.Sort(sort.Reverse(sort.IntSlice(count)))
if len(count) == 0 {
return num, fmt.Errorf("Component not found")
}
return count[0], nil
}
func countUnits(units []string) (count []int, err error) {
for _, unit := range units {
_, n, err := splitJobName(unit)
if err != nil {
return []int{}, err
}
count = append(count, n)
}
return
}
func splitJobName(component string) (c string, num int, err error) {
r := regexp.MustCompile(`deis\-([a-z-]+)\@([\d]+)\.service`)
match := r.FindStringSubmatch(component)
if len(match) == 0 {
c, err = "", fmt.Errorf("Could not parse component: %v", component)
return
}
c = match[1]
num, err = strconv.Atoi(match[2])
if err != nil {
return
}
return
}
func splitTarget(target string) (component string, num int, err error) {
// see if we were provided a specific target
r := regexp.MustCompile(`^([a-z-]+)(@\d+)?(\.service)?$`)
match := r.FindStringSubmatch(target)
// check for failed match
if len(match) < 3 {
err = fmt.Errorf("Could not parse target: %v", target)
return
}
if match[2] == "" {
component = match[1]
return component, 0, nil
}
num, err = strconv.Atoi(match[2][1:])
if err != nil {
return "", 0, err
}
return match[1], num, err
}
// expand a target to all installed units
func expandTargets(c *FleetClient, targets []string) (expandedTargets []string, err error) {
for _, t := range targets {
if strings.HasSuffix(t, "@*") {
var targets []string
targets, err = expandTarget(c, strings.TrimSuffix(t, "@*"))
if err != nil {
return
}
expandedTargets = append(expandedTargets, targets...)
} else {
expandedTargets = append(expandedTargets, t)
}
}
return
}
func expandTarget(c *FleetClient, target string) (targets []string, err error) {
targets, err = c.Units(target)
return
}
// randomValue returns a random string from a slice of string
func randomValue(src []string) string {
s := rand.NewSource(int64(time.Now().Unix()))
r := rand.New(s)
idx := r.Intn(len(src))
return src[idx]
}