forked from cloudfoundry/dagger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
371 lines (309 loc) · 8.86 KB
/
app.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
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package dagger
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"os/exec"
"regexp"
"strings"
"time"
"github.com/paketo-buildpacks/packit/pexec"
"github.com/pkg/errors"
)
type App struct {
ImageName string
CacheImage string
ContainerID string
Memory string
Env map[string]string
buildLogs *bytes.Buffer
logProc *exec.Cmd
port string
fixtureName string
healthCheck HealthCheck
}
type HealthCheck struct {
command string
interval string
timeout string
}
func NewApp(fixturePath, imageName, cacheImage string, buildLogs *bytes.Buffer, env map[string]string) App {
return App{
ImageName: imageName,
CacheImage: cacheImage,
buildLogs: buildLogs,
Env: env,
fixtureName: fixturePath,
}
}
func (a *App) Start() error {
return a.StartWithCommand("")
}
func (a *App) StartWithCommand(startCmd string) error {
if a.Env["PORT"] == "" {
a.Env["PORT"] = "8080"
}
args := []string{"run", "-d", "-p", a.Env["PORT"], "-P"}
if a.Memory != "" {
args = append(args, "--memory", a.Memory)
}
if a.healthCheck.command == "" {
a.healthCheck.command = fmt.Sprintf("curl --fail http://localhost:%s || exit 1", a.Env["PORT"])
}
args = append(args, "--health-cmd", a.healthCheck.command)
if a.healthCheck.interval != "" {
args = append(args, "--health-interval", a.healthCheck.interval)
}
if a.healthCheck.timeout != "" {
args = append(args, "--health-timeout", a.healthCheck.timeout)
}
envTemplate := "%s=%s"
for k, v := range a.Env {
envString := fmt.Sprintf(envTemplate, k, v)
args = append(args, "-e", envString)
}
args = append(args, a.ImageName)
if startCmd != "" {
args = append(args, startCmd)
}
docker := pexec.NewExecutable("docker")
stdout := bytes.NewBuffer(nil)
err := docker.Execute(pexec.Execution{
Args: args,
Stdout: stdout,
})
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to run docker image: %s\n with command: %s", a.ImageName, args))
}
a.ContainerID = stdout.String()[:12]
ticker := time.NewTicker(1 * time.Second)
timeOut := time.After(2 * time.Minute)
docker:
for {
select {
case <-ticker.C:
health, err := exec.Command("docker", "inspect", "-f", "{{.State.Health}}", a.ContainerID).CombinedOutput()
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to docker inspect health of container: %s\n with health status: %s\n", a.ContainerID, string(health)))
}
status := strings.TrimSuffix(string(health), "\n")
if status != "<nil>" {
// Split string by space and remove curly brace in front
status = strings.Split(string(status), " ")[0][1:]
status = strings.TrimSpace(status)
}
if status == "unhealthy" {
logs, _ := a.Logs()
return errors.Errorf("app failed to start: %s\n%s\n", a.fixtureName, logs)
}
if status == "healthy" || status == "<nil>" {
break docker
}
case <-timeOut:
return fmt.Errorf("timed out waiting for app : %s", a.fixtureName)
}
}
stdout = bytes.NewBuffer(nil)
err = docker.Execute(pexec.Execution{
Args: []string{"container", "port", a.ContainerID},
Stdout: stdout,
})
if err != nil {
return errors.Wrap(err, fmt.Sprintf("docker error: failed to get port from container: %s", a.ContainerID))
}
ports := strings.Split(stdout.String(), ":")
if len(ports) > 1 {
a.port = strings.TrimSpace(ports[1])
} else {
return fmt.Errorf("unable to get port map from docker")
}
return nil
}
func (a *App) Destroy() error {
if a == nil {
return nil
}
docker := pexec.NewExecutable("docker")
cntrExists, err := DockerArtifactExists(a.ContainerID)
if err != nil {
return fmt.Errorf("failed to find container %s: %s", a.ContainerID, err)
}
if cntrExists {
err := docker.Execute(pexec.Execution{
Args: []string{"stop", a.ContainerID},
})
if err != nil {
return fmt.Errorf("failed to stop container %s: %s", a.ContainerID, err)
}
err = docker.Execute(pexec.Execution{
Args: []string{"rm", a.ContainerID, "-f", "--volumes"},
})
if err != nil {
return fmt.Errorf("failed to remove container %s: %s", a.ContainerID, err)
}
}
imgExists, err := DockerArtifactExists(a.ImageName)
if err != nil {
return fmt.Errorf("failed to find image %s: %s", a.ImageName, err)
}
if imgExists {
err = docker.Execute(pexec.Execution{
Args: []string{"rmi", a.ImageName, "-f"},
})
if err != nil {
return fmt.Errorf("failed to remove image %s: %s", a.ImageName, err)
}
}
cacheExists, err := DockerArtifactExists(a.CacheImage)
if err != nil {
return fmt.Errorf("failed to find cache image %s: %s", a.CacheImage, err)
}
if cacheExists {
err = docker.Execute(pexec.Execution{
Args: []string{"rmi", a.CacheImage, "-f"},
})
if err != nil {
return fmt.Errorf("failed to remove cache image %s: %s", a.CacheImage, err)
}
}
cacheBuildVolumeExists, err := DockerArtifactExists(fmt.Sprintf("%s.build", a.CacheImage))
if err != nil {
return fmt.Errorf("failed to find cache build volume %s.build: %s", a.CacheImage, err)
}
if cacheBuildVolumeExists {
err = docker.Execute(pexec.Execution{
Args: []string{"volume", "rm", fmt.Sprintf("%s.build", a.CacheImage)},
})
if err != nil {
return fmt.Errorf("failed to remove cache build volume %s.build: %s", a.CacheImage, err)
}
}
cacheLaunchVolumeExists, err := DockerArtifactExists(fmt.Sprintf("%s.launch", a.CacheImage))
if err != nil {
return fmt.Errorf("failed to find cache launch volume %s.launch: %s", a.CacheImage, err)
}
if cacheLaunchVolumeExists {
err = docker.Execute(pexec.Execution{
Args: []string{"volume", "rm", fmt.Sprintf("%s.launch", a.CacheImage)},
})
if err != nil {
return fmt.Errorf("failed to remove cache launch volume %s.launch: %s", a.CacheImage, err)
}
}
err = docker.Execute(pexec.Execution{
Args: []string{"image", "prune", "-f"},
})
if err != nil {
return fmt.Errorf("failed to prune images: %s", err)
}
*a = App{}
return nil
}
func (a *App) Logs() (string, error) {
docker := pexec.NewExecutable("docker")
buffer := bytes.NewBuffer(nil)
err := docker.Execute(pexec.Execution{
Args: []string{"logs", a.ContainerID},
Stdout: buffer,
Stderr: buffer,
})
if err != nil {
return "", err
}
return stripColor(buffer.String()), nil
}
func (a *App) BuildLogs() string {
return stripColor(a.buildLogs.String())
}
func (a *App) SetHealthCheck(command, interval, timeout string) {
a.healthCheck = HealthCheck{
command: command,
interval: interval,
timeout: timeout,
}
}
func (a *App) Files(path string) ([]string, error) {
// Ensures that the error and results from "Permission denied" don't get sent to the output
docker := pexec.NewExecutable("docker")
stdout := bytes.NewBuffer(nil)
err := docker.Execute(pexec.Execution{
Args: []string{
"run", a.ImageName,
"find", "./..", fmt.Sprintf("-wholename *%s* 2>&1 | grep -v \"Permission denied\"", path),
},
Stdout: stdout,
})
if err != nil {
return []string{}, err
}
return strings.Split(stdout.String(), "\n"), nil
}
func (a *App) Info() (cID string, imageID string, cacheID []string, e error) {
volumes, err := getCacheVolumes()
if err != nil {
return "", "", []string{}, err
}
return a.ContainerID, a.ImageName, volumes, nil
}
func (a App) GetBaseURL() string {
return fmt.Sprintf("http://localhost:%s", a.port)
}
func (a *App) HTTPGet(path string) (string, map[string][]string, error) {
resp, err := http.Get(fmt.Sprintf("%s%s", a.GetBaseURL(), path))
if err != nil {
return "", nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return "", nil, fmt.Errorf("received bad response from application")
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", nil, err
}
return string(body), resp.Header, nil
}
func (a *App) HTTPGetBody(path string) (string, error) {
resp, _, err := a.HTTPGet(path)
return resp, err
}
func stripColor(input string) string {
const ansi = "[\u001B\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
var re = regexp.MustCompile(ansi)
return re.ReplaceAllString(input, "")
}
func getCacheVolumes() ([]string, error) {
docker := pexec.NewExecutable("docker")
stdout := bytes.NewBuffer(nil)
err := docker.Execute(pexec.Execution{
Args: []string{"volume", "ls", "-q"},
Stdout: stdout,
})
if err != nil {
return []string{}, err
}
outputArr := strings.Split(stdout.String(), "\n")
var finalVolumes []string
for _, line := range outputArr {
if strings.Contains(line, "pack-cache") {
finalVolumes = append(finalVolumes, line)
}
}
return outputArr, nil
}
func DockerArtifactExists(name string) (bool, error) {
docker := pexec.NewExecutable("docker")
stderr := bytes.NewBuffer(nil)
err := docker.Execute(pexec.Execution{
Args: []string{"inspect", name},
Stderr: stderr,
})
if err != nil {
if strings.Contains(stderr.String(), "No such object") {
return false, nil
}
return false, err
}
return true, nil
}