-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdockerAPI.go
More file actions
78 lines (66 loc) · 2.06 KB
/
dockerAPI.go
File metadata and controls
78 lines (66 loc) · 2.06 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
package main
import (
"context"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/events"
"github.com/docker/docker/client"
"github.com/fasibio/funk_agent/logger"
)
// DockerClient represent all used methods from docker client
type DockerClient interface {
ContainerList(ctx context.Context, options types.ContainerListOptions) ([]types.Container, error)
Info(ctx context.Context) (types.Info, error)
Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error)
}
func getTrackingContainer(ctx context.Context, cli DockerClient) ([]types.Container, error) {
c, err := cli.ContainerList(ctx, types.ContainerListOptions{All: false})
if err != nil {
return nil, err
}
var res []types.Container
for _, one := range c {
if one.Labels["funk.log"] == "false" {
continue
} else {
res = append(res, one)
}
}
return res, nil
}
// StartListeningForContainer start the dockercontainerwatcher in an own goroutine. It will returns the docker client and metainfos
func StartListeningForContainer(ctx context.Context, trackingContainer chan []types.Container) (*client.Client, *types.Info, error) {
cli, err := client.NewEnvClient()
if err != nil {
return nil, nil, err
}
res, err := getTrackingContainer(ctx, cli)
if err != nil {
logger.Get().Errorw("Error by getTrackingContainer: " + err.Error())
} else {
trackingContainer <- res
}
info, err := cli.Info(ctx)
if err != nil {
return nil, nil, err
}
msg, errs := cli.Events(ctx, types.EventsOptions{})
go func() {
for e := range errs {
logger.Get().Errorw("Error by Events: " + e.Error())
}
}()
go readMessages(ctx, cli, msg, trackingContainer)
return cli, &info, nil
}
func readMessages(ctx context.Context, cli DockerClient, msg <-chan events.Message, trackingContainer chan []types.Container) {
for m := range msg {
if m.Type == "container" {
res, err := getTrackingContainer(ctx, cli)
if err != nil {
logger.Get().Errorw("Error by getTrackingContainer: " + err.Error())
continue
}
trackingContainer <- res
}
}
}