/
docker.go
218 lines (184 loc) · 4.96 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// Copyright 2017 AMIS Technologies
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package test
import (
"context"
"fmt"
"os"
"github.com/getamis/sirius/crypto/rand"
"github.com/getamis/sirius/log"
docker "github.com/fsouza/go-dockerclient"
)
type Container struct {
dockerClient *docker.Client
Started bool
name string
imageRespository string
imageTag string
portBindings map[docker.Port][]docker.PortBinding
exposedPorts map[docker.Port]struct{}
ports []string
entrypoint []string
runArgs []string
envs []string
links []string
container *docker.Container
healthChecker ContainerCallback
initializer ContainerCallback
}
type ContainerCallback func(*Container) error
func newDockerClient() (*docker.Client, error) {
if os.Getenv("DOCKER_MACHINE_NAME") != "" {
return docker.NewClientFromEnv()
}
return docker.NewClient("unix:///var/run/docker.sock")
}
func NewDockerContainer(opts ...Option) *Container {
client, err := newDockerClient()
if err != nil {
panic(err)
}
c := &Container{
portBindings: make(map[docker.Port][]docker.PortBinding),
exposedPorts: make(map[docker.Port]struct{}),
dockerClient: client,
healthChecker: func(c *Container) error {
return nil
},
links: []string{},
}
for _, opt := range opts {
opt(c)
}
// Automatically convert the ports to exposed ports and host binding ports
if len(c.ports) > 0 {
for _, port := range c.ports {
c.addHostPortBinding(port, port)
c.exposePort(port)
}
}
c.container, err = c.dockerClient.CreateContainer(docker.CreateContainerOptions{
Name: c.name + generateNameSuffix(),
Config: &docker.Config{
Image: c.imageRespository + ":" + c.imageTag,
Entrypoint: c.entrypoint,
Cmd: c.runArgs,
ExposedPorts: c.exposedPorts,
Env: c.envs,
},
HostConfig: &docker.HostConfig{
PortBindings: c.portBindings,
Links: c.links,
},
Context: context.TODO(),
})
if err != nil {
panic(fmt.Errorf("Failed to create a container %s:%s error:%s", c.imageRespository, c.imageTag, err))
}
return c
}
func (c *Container) OnReady(initializer ContainerCallback) {
c.initializer = initializer
}
func (c *Container) Start() error {
err := c.dockerClient.StartContainer(c.container.ID, nil)
if err != nil {
return err
}
defer log.Debug("Container IP address", "container ID", c.container.ID, "ip", c.IPAddress())
c.Started = true
defer func() {
if c.initializer != nil {
err = c.initializer(c)
}
}()
err = c.healthChecker(c)
return err
}
func (c *Container) exposePort(port string) {
c.exposedPorts[docker.Port(port)] = struct{}{}
}
func (c *Container) addHostPortBinding(containerPort string, hostPort string) {
c.portBindings[docker.Port(containerPort)] = []docker.PortBinding{
{
HostIP: "0.0.0.0",
HostPort: hostPort,
},
}
}
func (c *Container) Suspend() error {
defer func() {
c.Started = false
}()
return c.dockerClient.StopContainer(c.container.ID, 0)
}
func (c *Container) Wait() error {
_, err := c.dockerClient.WaitContainer(c.container.ID)
return err
}
func (c *Container) Run() error {
if err := c.Start(); err != nil {
log.Error("Failed to start container", "err", err)
return err
}
if err := c.Wait(); err != nil {
log.Error("Failed to wait container", "err", err)
return err
}
return c.Stop()
}
func (c *Container) Stop() error {
defer func() {
c.Started = false
}()
return c.dockerClient.RemoveContainer(docker.RemoveContainerOptions{
ID: c.container.ID,
RemoveVolumes: true,
Force: true,
Context: context.TODO(),
})
}
func (c *Container) SetHealthChecker(checker ContainerCallback) *Container {
c.healthChecker = checker
return c
}
func (c *Container) SetInitializer(initializer ContainerCallback) *Container {
c.initializer = initializer
return c
}
func (c *Container) SetEnvVars(envs []string) *Container {
c.envs = envs
return c
}
// IPAddress returns the IP adress of the container.
func (c *Container) IPAddress() string {
spec, err := c.dockerClient.InspectContainer(c.container.ID)
if err != nil {
log.Error("Failed to get IPAddress", "err", err)
return ""
}
return spec.NetworkSettings.IPAddress
}
// generateContainerID generates the UUID for container ID instead of the
// default name combinator
func generateContainerID() string {
return rand.New(
rand.HexEncoder(),
).KeyEncoded()
}
func generateNameSuffix() string {
return rand.New(
rand.UUIDEncoder(),
).KeyEncoded()
}