-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent.go
81 lines (66 loc) · 1.52 KB
/
event.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
package main
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
)
type Error string
func (e Error) Error() string {
return string(e)
}
const (
timeoutError Error = "timeout while waiting for containers to be healthy"
unhealthyError Error = "containers are unhealthy"
)
func listen(c Containers, since time.Time, timeout time.Duration, failOnUnhealthy bool) (bool, error) {
cli, err := client.NewClientWithOpts(
client.FromEnv,
client.WithAPIVersionNegotiation(),
)
if err != nil {
return false, err
}
filter := filters.NewArgs()
filter.Add("type", "container")
filter.Add("event", "health_status")
for id := range c {
filter.Add("container", id)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
msgs, errs := cli.Events(ctx, types.EventsOptions{
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: msg.Status[15:],
Changed: time.Unix(msg.Time, msg.TimeNano),
}
c.Add(msg.ID, container)
if c.Healthy() {
return true, nil
}
if err := c.Unhealthy(); err != nil && failOnUnhealthy {
return false, err
}
case <-timeoutChan:
return false, fmt.Errorf(
"%w (%s): %s",
timeoutError,
timeout,
strings.Join(c.NonHealtyContainers(), ", "),
)
}
}
}