-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathutils.go
More file actions
307 lines (271 loc) · 6.86 KB
/
utils.go
File metadata and controls
307 lines (271 loc) · 6.86 KB
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
// Package utils contains commonly useful functions from Deis testing.
package utils
import (
_ "bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
"github.com/deis/deisctl/constant"
"github.com/docker/docker/api/client"
uuid "github.com/satori/go.uuid"
)
// NewUuid returns a new V4-style unique identifier.
func NewUuid() string {
u1 := uuid.NewV4()
s1 := fmt.Sprintf("%s", u1)
return strings.Split(s1, "-")[0]
}
func GetNewClient() (
cli *client.DockerCli, stdout *io.PipeReader, stdoutPipe *io.PipeWriter) {
testDaemonAddr := "/var/run/docker.sock"
testDaemonProto := "unix"
stdout, stdoutPipe = io.Pipe()
cli = client.NewDockerCli(
nil, stdoutPipe, nil, testDaemonProto, testDaemonAddr, nil)
return
}
func PullImage(cli *client.DockerCli, args ...string) error {
fmt.Println("pulling image : " + args[0])
err := cli.CmdPull(args...)
return err
}
func GetServices() []string {
service := []string{
"deis-builder.service",
"deis-builder-data.service",
"deis-cache.service",
"deis-controller.service",
"deis-database.service",
"deis-database-data.service",
"deis-logger.service",
"deis-logger-data.service",
"deis-registry.service",
"deis-registry-data.service",
"deis-router.service",
}
return service
}
func GetMachineID(root string) string {
fullPath := filepath.Join(root, constant.MachineId)
id, err := ioutil.ReadFile(fullPath)
if err != nil {
return ""
}
return strings.TrimSpace(string(id))
}
func GetVersion() string {
id, err := ioutil.ReadFile(constant.Version)
if err != nil {
return os.Getenv("DEISCTL_APP_VERSION")
}
return strings.TrimSpace(string(id))
}
// GetFileBytes returns a byte array of the contents of a file.
func GetFileBytes(filename string) []byte {
file, _ := os.Open(filename)
defer file.Close()
stat, _ := file.Stat()
bs := make([]byte, stat.Size())
_, _ = file.Read(bs)
return bs
}
func ListFiles(dir string) ([]string, error) {
files, err := filepath.Glob(dir)
return files, err
}
// CreateFile creates an empty file at the specified path.
func CreateFile(path string) error {
fo, err := os.Create(path)
if err != nil {
return err
}
defer fo.Close()
return nil
}
// Chdir sets the current working directory to the relative path specified.
func Chdir(app string) error {
var wd, _ = os.Getwd()
dir, _ := filepath.Abs(filepath.Join(wd, app))
err := os.Chdir(dir)
fmt.Println(dir)
return err
}
func Extract(file, dir string) {
var wd, _ = os.Getwd()
_ = os.Chdir(dir)
cmdl := exec.Command("tar", "-xvf", file)
if _, _, err := RunCommandWithStdoutStderr(cmdl); err != nil {
fmt.Printf("Failed:\n%v", err)
} else {
fmt.Println("ok")
}
_ = os.Chdir(wd)
}
// Rmdir removes a directory and its contents.
func Rmdir(app string) error {
var wd, _ = os.Getwd()
dir, _ := filepath.Abs(filepath.Join(wd, app))
err := os.RemoveAll(dir)
fmt.Println(dir)
return err
}
// GetUserDetails returns sections of a UUID.
func GetUserDetails() (string, string) {
u1 := uuid.NewV4()
s1 := fmt.Sprintf("%s", u1)
return strings.Split(s1, "-")[0], strings.Split(s1, "-")[1]
}
// GetHostOs returns either "darwin" or "ubuntu".
func GetHostOs() string {
cmd := exec.Command("uname")
out, _ := cmd.Output()
if strings.Contains(string(out), "Darwin") {
return "darwin"
}
return "ubuntu"
}
// GetHostIPAddress returns the host IP for accessing etcd and Deis services.
func GetHostIPAddress() string {
IP := os.Getenv("HOST_IPADDR")
if IP == "" {
IP = "172.17.8.100"
}
return IP
}
// Append grows a string array by appending a new element.
func Append(slice []string, data string) []string {
m := len(slice)
n := m + 1
if n > cap(slice) { // if necessary, reallocate
// allocate double what's needed, for future growth.
newSlice := make([]string, (n + 1))
copy(newSlice, slice)
slice = newSlice
}
slice = slice[0:n]
slice[n-1] = data
return slice
}
// GetRandomPort returns an unused TCP listen port on the host.
func GetRandomPort() string {
l, _ := net.Listen("tcp", "127.0.0.1:0") // listen on localhost
defer l.Close()
port := l.Addr()
return strings.Split(port.String(), ":")[1]
}
func getExitCode(err error) (int, error) {
exitCode := 0
if exiterr, ok := err.(*exec.ExitError); ok {
if procExit := exiterr.Sys().(syscall.WaitStatus); ok {
return procExit.ExitStatus(), nil
}
}
return exitCode, fmt.Errorf("failed to get exit code")
}
// RunCommandWithStdoutStderr execs a command and returns its output.
func RunCommandWithStdoutStderr(cmd *exec.Cmd) (bytes.Buffer, bytes.Buffer, error) {
var stdout, stderr bytes.Buffer
stderrPipe, err := cmd.StderrPipe()
stdoutPipe, err := cmd.StdoutPipe()
cmd.Env = os.Environ()
if err != nil {
fmt.Println("error at io pipes")
}
err = cmd.Start()
if err != nil {
fmt.Println("error at command start")
}
go func() {
io.Copy(&stdout, stdoutPipe)
fmt.Println(stdout.String())
}()
go func() {
io.Copy(&stderr, stderrPipe)
fmt.Println(stderr.String())
}()
time.Sleep(2000 * time.Millisecond)
err = cmd.Wait()
if err != nil {
fmt.Println("error at command wait")
}
return stdout, stderr, err
}
func Execute(script string) error {
cmdl := exec.Command("sh", "-c", script)
if _, _, err := RunCommandWithStdoutStderr(cmdl); err != nil {
fmt.Println("(Error )")
return err
}
return nil
}
func runCommandWithOutput(cmd *exec.Cmd) (output string, exitCode int, err error) {
exitCode = 0
out, err := cmd.CombinedOutput()
if err != nil {
var exiterr error
if exitCode, exiterr = getExitCode(err); exiterr != nil {
// TODO: Fix this so we check the error's text.
// we've failed to retrieve exit code, so we set it to 127
exitCode = 127
}
}
output = string(out)
return
}
func runCommand(cmd *exec.Cmd) (exitCode int, err error) {
exitCode = 0
err = cmd.Run()
if err != nil {
var exiterr error
if exitCode, exiterr = getExitCode(err); exiterr != nil {
// TODO: Fix this so we check the error's text.
// we've failed to retrieve exit code, so we set it to 127
exitCode = 127
}
}
return
}
func startCommand(cmd *exec.Cmd) (exitCode int, err error) {
exitCode = 0
err = cmd.Start()
if err != nil {
var exiterr error
if exitCode, exiterr = getExitCode(err); exiterr != nil {
// TODO: Fix this so we check the error's text.
// we've failed to retrieve exit code, so we set it to 127
exitCode = 127
}
}
return
}
func logDone(message string) {
fmt.Printf("[PASSED]: %s\n", message)
}
func stripTrailingCharacters(target string) string {
target = strings.Trim(target, "\n")
target = strings.Trim(target, " ")
return target
}
func errorOut(err error, t *testing.T, message string) {
if err != nil {
t.Fatal(message)
}
}
func errorOutOnNonNilError(err error, t *testing.T, message string) {
if err == nil {
t.Fatalf(message)
}
}
func nLines(s string) int {
return strings.Count(s, "\n")
}
//func deis(bash string , arg string , cmd string )