forked from cosandr/go-motd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
docker.go
79 lines (70 loc) · 1.83 KB
/
docker.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
package datasources
import (
"context"
"fmt"
"strings"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/cosandr/go-motd/utils"
)
const (
dockerMinAPI = "1.40"
)
// ConfDocker extends ConfBase with a list of containers to ignore
type ConfDocker struct {
ConfBase `yaml:",inline"`
// Interact directly with the docker CLI, much slower than API
Exec bool `yaml:"use_exec"`
// List of container names to ignore
Ignore []string `yaml:"ignore,omitempty"`
}
// Init sets up default alignment
func (c *ConfDocker) Init() {
c.ConfBase.Init()
c.PadHeader[1] = 3
}
// GetDocker docker container status using the API
func GetDocker(ch chan<- SourceReturn, conf *Conf) {
c := conf.Docker
// Check for warnOnly override
if c.WarnOnly == nil {
c.WarnOnly = &conf.WarnOnly
}
sr := NewSourceReturn(conf.debug)
defer func() {
ch <- sr.Return(&c.ConfBase)
}()
var err error
var cl containerList
if c.Exec {
cl, err = getContainersExec(false, false)
} else {
cl, err = getDockerContainers()
}
if err != nil {
err = &ModuleNotAvailable{"docker", err}
sr.Header = fmt.Sprintf("%s: %s\n", utils.Wrap("Docker", c.padL, c.padR), utils.Warn("unavailable"))
} else {
sr.Header, sr.Content, sr.Error = cl.toHeaderContent(c.Ignore, *c.WarnOnly, c.padL, c.padR)
}
return
}
func getDockerContainers() (cl containerList, err error) {
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithVersion(dockerMinAPI))
if err != nil {
return
}
allContainers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true})
if err != nil {
return
}
cl.Runtime = "Docker"
cl.Root = true
for _, container := range allContainers {
cl.Containers = append(cl.Containers, containerStatus{
Name: strings.TrimPrefix(container.Names[0], "/"),
Status: container.State,
})
}
return
}