-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwait.go
85 lines (69 loc) · 1.86 KB
/
wait.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
package dockertest
import (
"bufio"
"context"
"errors"
"fmt"
"reflect"
"runtime"
"strings"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
)
var ErrClosedWithoutFinding = errors.New("log stream closed without finding")
var pollingPause = 1000 * time.Millisecond
type waitForContainerFunc func(inspectResult types.ContainerJSON, inspectError error) bool
func containerIsHealthy(inspectResult types.ContainerJSON, _ error) bool {
return inspectResult.State.Health.Status == "healthy"
}
func containerHasFadeAway(inspectResult types.ContainerJSON, inspectError error) bool {
return client.IsErrNotFound(inspectError) || !inspectResult.State.Running
}
func waitForContainer(
ctx context.Context,
f waitForContainerFunc,
dockerClient *client.Client,
containerID string,
) bool {
for {
select {
case <-ctx.Done():
funcName := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
fmt.Printf("waiting for '%s' timed out for container %v\n", funcName, containerID)
return false
default:
inspectResult, err := dockerClient.ContainerInspect(ctx, containerID)
if f(inspectResult, err) {
return true
}
time.Sleep(pollingPause)
}
}
}
func waitForContainerLog(ctx context.Context, search string, dockerClient *client.Client, containerID string) error {
var logOpts = types.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: true,
Follow: true,
}
reader, err := dockerClient.ContainerLogs(ctx, containerID, logOpts)
if err != nil {
return err
}
defer func() {
_ = reader.Close()
}()
var (
buffer = strings.Builder{}
scanner = bufio.NewScanner(reader)
)
for scanner.Scan() {
if strings.Contains(scanner.Text(), search) {
return nil
} else {
buffer.WriteString(scanner.Text() + "\n")
}
}
return fmt.Errorf("%w '%s' (output: %s)", ErrClosedWithoutFinding, search, buffer.String())
}