forked from coreos/fleet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
215 lines (188 loc) · 5.32 KB
/
util.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
// Copyright 2014 CoreOS, 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 util
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"strings"
"time"
"github.com/pborman/uuid"
)
var fleetctlBinPath string
func init() {
fleetctlBinPath = os.Getenv("FLEETCTL_BIN")
if fleetctlBinPath == "" {
fmt.Println("FLEETCTL_BIN environment variable must be set")
os.Exit(1)
} else if _, err := os.Stat(fleetctlBinPath); err != nil {
fmt.Printf("%v\n", err)
os.Exit(1)
}
if os.Getenv("SSH_AUTH_SOCK") == "" {
fmt.Println("SSH_AUTH_SOCK environment variable must be set")
os.Exit(1)
}
}
type fleetfunc func(args ...string) (string, string, error)
func RunFleetctl(args ...string) (string, string, error) {
log.Printf("%s %s", fleetctlBinPath, strings.Join(args, " "))
var stdoutBytes, stderrBytes bytes.Buffer
cmd := exec.Command(fleetctlBinPath, args...)
cmd.Stdout = &stdoutBytes
cmd.Stderr = &stderrBytes
err := cmd.Run()
return stdoutBytes.String(), stderrBytes.String(), err
}
func RunFleetctlWithInput(input string, args ...string) (string, string, error) {
log.Printf("%s %s", fleetctlBinPath, strings.Join(args, " "))
var stdoutBytes, stderrBytes bytes.Buffer
cmd := exec.Command(fleetctlBinPath, args...)
cmd.Stdout = &stdoutBytes
cmd.Stderr = &stderrBytes
stdin, err := cmd.StdinPipe()
if err != nil {
return "", "", err
}
if err = cmd.Start(); err != nil {
return "", "", err
}
stdin.Write([]byte(input))
stdin.Close()
err = cmd.Wait()
return stdoutBytes.String(), stderrBytes.String(), err
}
// ActiveToSingleStates takes a map of active states (such as that returned by
// WaitForNActiveUnits) and ensures that each unit has at most a single active
// state. It returns a mapping of unit name to a single UnitState.
func ActiveToSingleStates(active map[string][]UnitState) (map[string]UnitState, error) {
states := make(map[string]UnitState)
for name, us := range active {
if len(us) != 1 {
return nil, fmt.Errorf("unit %s running in multiple locations: %v", name, us)
}
states[name] = us[0]
}
return states, nil
}
type UnitState struct {
Name string
ActiveState string
Machine string
}
type UnitFileState struct {
Name string
DesiredState string
State string
}
func ParseUnitStates(units []string) (states []UnitState) {
for _, unit := range units {
cols := strings.Fields(unit)
if len(cols) == 3 {
machine := strings.SplitN(cols[2], "/", 2)[0]
states = append(states, UnitState{cols[0], cols[1], machine})
}
}
return states
}
func ParseUnitFileStates(units []string) (states []UnitFileState) {
for _, unit := range units {
cols := strings.Fields(unit)
if len(cols) == 3 {
states = append(states, UnitFileState{cols[0], cols[1], cols[2]})
}
}
return states
}
func FilterActiveUnits(states []UnitState) (filtered []UnitState) {
for _, state := range states {
if state.ActiveState == "active" {
filtered = append(filtered, state)
}
}
return
}
// tempUnit creates a local unit file with the given contents, returning
// the name of the file
func TempUnit(contents string) (string, error) {
tmp, err := ioutil.TempFile(os.TempDir(), "fleet-test-unit-")
if err != nil {
return "", err
}
tmp.Write([]byte(contents))
tmp.Close()
svc := fmt.Sprintf("%s.service", tmp.Name())
err = os.Rename(tmp.Name(), svc)
if err != nil {
os.Remove(tmp.Name())
return "", err
}
return svc, nil
}
func WaitForState(stateCheckFunc func() bool) (time.Duration, error) {
timeout := 15 * time.Second
alarm := time.After(timeout)
ticker := time.Tick(250 * time.Millisecond)
for {
select {
case <-alarm:
// Generic message. Callers can build more specific ones using the returned timeout value.
return timeout, fmt.Errorf("Failed to reach expected state within %v.", timeout)
case <-ticker:
if stateCheckFunc() {
return timeout, nil
}
}
}
}
func NewMachineID() string {
// drop the standard separators to match systemd
return strings.Replace(uuid.New(), "-", "", -1)
}
// CopyFile()
func CopyFile(newFile, oldFile string) error {
input, err := ioutil.ReadFile(oldFile)
if err != nil {
return err
}
err = ioutil.WriteFile(newFile, []byte(input), 0644)
if err != nil {
return err
}
return nil
}
// GenNewFleetService() is a helper for generating a temporary fleet service
// that reads from oldFile, replaces oldVal with newVal, and stores the result
// to newFile.
func GenNewFleetService(newFile, oldFile, newVal, oldVal string) error {
input, err := ioutil.ReadFile(oldFile)
if err != nil {
return err
}
lines := strings.Split(string(input), "\n")
for i, line := range lines {
if strings.Contains(line, oldVal) {
lines[i] = strings.Replace(line, oldVal, newVal, len(oldVal))
}
}
output := strings.Join(lines, "\n")
err = ioutil.WriteFile(newFile, []byte(output), 0644)
if err != nil {
return err
}
return nil
}