-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevent.go
More file actions
82 lines (67 loc) · 1.63 KB
/
event.go
File metadata and controls
82 lines (67 loc) · 1.63 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
package main
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"github.com/docker/docker/api/types/events"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
)
type Error string
func (e Error) Error() string {
return string(e)
}
const (
errTimeout Error = "timeout while waiting for containers to be healthy"
errUnhealthy Error = "containers are unhealthy"
)
func listen(containers Containers, since time.Time, timeout time.Duration, failOnUnhealthy bool) (bool, error) {
cli, err := client.NewClientWithOpts(
client.FromEnv,
client.WithAPIVersionNegotiation(),
)
if err != nil {
return false, fmt.Errorf("creating Docker client: %w", err)
}
filter := filters.NewArgs()
filter.Add("type", "container")
filter.Add("event", "health_status")
for id := range containers {
filter.Add("container", id)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
msgs, errs := cli.Events(ctx, events.ListOptions{
Filters: filter,
Since: strconv.FormatInt(since.Unix(), 10),
})
timeoutChan := time.After(timeout)
for {
select {
case err := <-errs:
return false, err
case msg := <-msgs:
container := Container{
Status: string(msg.Action)[15:],
Changed: time.Unix(msg.Time, msg.TimeNano),
}
containers.Add(msg.Actor.ID, container)
if containers.Healthy() {
return true, nil
}
err := containers.Unhealthy()
if err != nil && failOnUnhealthy {
return false, err
}
case <-timeoutChan:
return false, fmt.Errorf(
"%w (%s): %s",
errTimeout,
timeout,
strings.Join(containers.NonHealtyContainers(), ", "),
)
}
}
}