forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
82 lines (71 loc) · 2.05 KB
/
client.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
package dockergc
import (
"context"
"time"
dockertypes "github.com/docker/docker/api/types"
dockerapi "github.com/docker/docker/client"
)
type dockerClient struct {
// timeout is the timeout of short running docker operations.
timeout time.Duration
// docker API client
client *dockerapi.Client
}
func newDockerClient(timeout time.Duration) (*dockerClient, error) {
client, err := dockerapi.NewEnvClient()
if err != nil {
return nil, err
}
return &dockerClient{
client: client,
timeout: timeout,
}, nil
}
func clientErr(ctx context.Context, err error) error {
if ctx.Err() != nil {
return ctx.Err()
}
return err
}
func (c *dockerClient) getTimeoutContext() (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), c.timeout)
}
func (c *dockerClient) Info() (*dockertypes.Info, error) {
ctx, cancel := c.getTimeoutContext()
defer cancel()
info, err := c.client.Info(ctx)
if err := clientErr(ctx, err); err != nil {
return nil, err
}
return &info, nil
}
func (c *dockerClient) ContainerList(options dockertypes.ContainerListOptions) ([]dockertypes.Container, error) {
ctx, cancel := c.getTimeoutContext()
defer cancel()
containers, err := c.client.ContainerList(ctx, options)
if err := clientErr(ctx, err); err != nil {
return nil, err
}
return containers, nil
}
func (c *dockerClient) ContainerRemove(id string, opts dockertypes.ContainerRemoveOptions) error {
ctx, cancel := c.getTimeoutContext()
defer cancel()
err := c.client.ContainerRemove(ctx, id, opts)
return clientErr(ctx, err)
}
func (c *dockerClient) ImageList(opts dockertypes.ImageListOptions) ([]dockertypes.ImageSummary, error) {
ctx, cancel := c.getTimeoutContext()
defer cancel()
images, err := c.client.ImageList(ctx, opts)
if err := clientErr(ctx, err); err != nil {
return nil, err
}
return images, nil
}
func (c *dockerClient) ImageRemove(image string, opts dockertypes.ImageRemoveOptions) error {
ctx, cancel := c.getTimeoutContext()
defer cancel()
_, err := c.client.ImageRemove(ctx, image, opts)
return clientErr(ctx, err)
}