/
docker.go
87 lines (73 loc) 路 2 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
80
81
82
83
84
85
86
87
// Package docker provides Docker client.
package docker
import (
"context"
"net/http"
"path/filepath"
"github.com/docker/docker/api/types"
docker "github.com/docker/docker/client"
"github.com/docker/go-connections/tlsconfig"
)
// Client defines Docker client.
type Client struct {
*docker.Client
}
// ContainerJSONList returns the list of the container information.
func (c *Client) ContainerJSONList(ctx context.Context) ([]*types.ContainerJSON, error) {
containers, err := c.ContainerList(ctx, types.ContainerListOptions{All: true})
if err != nil {
return nil, err
}
res := make([]*types.ContainerJSON, 0, len(containers))
for _, cont := range containers {
ci, _, err := c.ContainerInspectWithRaw(ctx, cont.ID, true)
if err != nil {
return nil, err
}
res = append(res, &ci)
}
return res, nil
}
// NewClient creates a new Docker client.
func NewClient(ctx context.Context, host, certPath, version string, verify bool) (*Client, error) {
cli, err := docker.NewClientWithOpts(func(c *docker.Client) error {
return setOpts(c, host, certPath, version, verify)
})
if err != nil {
return nil, err
}
cli.NegotiateAPIVersion(ctx)
return &Client{cli}, nil
}
func setOpts(c *docker.Client, host, certPath, version string, verify bool) error {
if certPath != "" {
options := tlsconfig.Options{
CAFile: filepath.Join(certPath, "ca.pem"),
CertFile: filepath.Join(certPath, "cert.pem"),
KeyFile: filepath.Join(certPath, "key.pem"),
InsecureSkipVerify: !verify,
}
tlsc, err := tlsconfig.Client(options)
if err != nil {
return err
}
httpClient := &http.Client{
Transport: &http.Transport{TLSClientConfig: tlsc},
CheckRedirect: docker.CheckRedirect,
}
if err := docker.WithHTTPClient(httpClient)(c); err != nil {
return err
}
}
if host != "" {
if err := docker.WithHost(host)(c); err != nil {
return err
}
}
if version != "" {
if err := docker.WithVersion(version)(c); err != nil {
return err
}
}
return nil
}