forked from docker/libcompose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
container.go
379 lines (326 loc) · 10.4 KB
/
container.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
package container
import (
"fmt"
"io"
"math"
"os"
"strconv"
"strings"
"time"
"golang.org/x/net/context"
"github.com/Sirupsen/logrus"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/promise"
"github.com/docker/docker/pkg/stdcopy"
"github.com/docker/docker/pkg/term"
"github.com/docker/go-connections/nat"
"github.com/docker/libcompose/config"
"github.com/docker/libcompose/labels"
"github.com/docker/libcompose/logger"
"github.com/docker/libcompose/project"
)
// Container holds information about a docker container and the service it is tied on.
type Container struct {
client client.ContainerAPIClient
id string
container *types.ContainerJSON
}
// Create creates a container and return a Container struct (and an error if any)
func Create(ctx context.Context, client client.ContainerAPIClient, name string, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig) (*Container, error) {
container, err := client.ContainerCreate(ctx, config, hostConfig, networkingConfig, name)
if err != nil {
return nil, err
}
return New(ctx, client, container.ID)
}
// New creates a container struct with the specified client, id and name
func New(ctx context.Context, client client.ContainerAPIClient, id string) (*Container, error) {
container, err := Get(ctx, client, id)
if err != nil {
return nil, err
}
return &Container{
client: client,
id: id,
container: container,
}, nil
}
// NewInspected creates a container struct from an inspected container
func NewInspected(client client.ContainerAPIClient, container *types.ContainerJSON) *Container {
return &Container{
client: client,
id: container.ID,
container: container,
}
}
// Info returns info about the container, like name, command, state or ports.
func (c *Container) Info(ctx context.Context) (project.Info, error) {
infos, err := ListByFilter(ctx, c.client, map[string][]string{
"name": {c.container.Name},
})
if err != nil || len(infos) == 0 {
return nil, err
}
info := infos[0]
result := project.Info{}
result["Id"] = c.container.ID
result["Name"] = name(info.Names)
result["Command"] = info.Command
result["State"] = info.Status
result["Ports"] = portString(info.Ports)
return result, nil
}
func portString(ports []types.Port) string {
result := []string{}
for _, port := range ports {
if port.PublicPort > 0 {
result = append(result, fmt.Sprintf("%s:%d->%d/%s", port.IP, port.PublicPort, port.PrivatePort, port.Type))
} else {
result = append(result, fmt.Sprintf("%d/%s", port.PrivatePort, port.Type))
}
}
return strings.Join(result, ", ")
}
func name(names []string) string {
max := math.MaxInt32
var current string
for _, v := range names {
if len(v) < max {
max = len(v)
current = v
}
}
return current[1:]
}
// Rename rename the container.
func (c *Container) Rename(ctx context.Context, newName string) error {
return c.client.ContainerRename(ctx, c.container.ID, newName)
}
// Remove removes the container.
func (c *Container) Remove(ctx context.Context, removeVolume bool) error {
return c.client.ContainerRemove(ctx, c.container.ID, types.ContainerRemoveOptions{
Force: true,
RemoveVolumes: removeVolume,
})
}
// Stop stops the container.
func (c *Container) Stop(ctx context.Context, timeout int) error {
timeoutDuration := time.Duration(timeout) * time.Second
return c.client.ContainerStop(ctx, c.container.ID, &timeoutDuration)
}
// Pause pauses the container. If the containers are already paused, don't fail.
func (c *Container) Pause(ctx context.Context) error {
if !c.container.State.Paused {
if err := c.client.ContainerPause(ctx, c.container.ID); err != nil {
return err
}
return c.updateInnerContainer(ctx)
}
return nil
}
// Unpause unpauses the container. If the containers are not paused, don't fail.
func (c *Container) Unpause(ctx context.Context) error {
if c.container.State.Paused {
if err := c.client.ContainerUnpause(ctx, c.container.ID); err != nil {
return err
}
return c.updateInnerContainer(ctx)
}
return nil
}
func (c *Container) updateInnerContainer(ctx context.Context) error {
container, err := Get(ctx, c.client, c.container.ID)
if err != nil {
return err
}
c.container = container
return nil
}
// Kill kill the container.
func (c *Container) Kill(ctx context.Context, signal string) error {
return c.client.ContainerKill(ctx, c.container.ID, signal)
}
// IsRunning returns the running state of the container.
// FIXME(vdemeester): remove the nil error here
func (c *Container) IsRunning(ctx context.Context) (bool, error) {
return c.container.State.Running, nil
}
// Run creates, start and attach to the container based on the image name,
// the specified configuration.
// It will always create a new container.
func (c *Container) Run(ctx context.Context, configOverride *config.ServiceConfig) (int, error) {
var (
errCh chan error
out, stderr io.Writer
in io.ReadCloser
)
if configOverride.StdinOpen {
in = os.Stdin
}
if configOverride.Tty {
out = os.Stdout
}
if configOverride.Tty {
stderr = os.Stderr
}
options := types.ContainerAttachOptions{
Stream: true,
Stdin: configOverride.StdinOpen,
Stdout: configOverride.Tty,
Stderr: configOverride.Tty,
}
resp, err := c.client.ContainerAttach(ctx, c.container.ID, options)
if err != nil {
return -1, err
}
// set raw terminal
inFd, _ := term.GetFdInfo(in)
state, err := term.SetRawTerminal(inFd)
if err != nil {
return -1, err
}
// restore raw terminal
defer term.RestoreTerminal(inFd, state)
// holdHijackedConnection (in goroutine)
errCh = promise.Go(func() error {
return holdHijackedConnection(configOverride.Tty, in, out, stderr, resp)
})
if err := c.client.ContainerStart(ctx, c.container.ID, types.ContainerStartOptions{}); err != nil {
return -1, err
}
if err := <-errCh; err != nil {
logrus.Debugf("Error hijack: %s", err)
return -1, err
}
exitedContainer, err := c.client.ContainerInspect(ctx, c.container.ID)
if err != nil {
return -1, err
}
return exitedContainer.State.ExitCode, nil
}
func holdHijackedConnection(tty bool, inputStream io.ReadCloser, outputStream, errorStream io.Writer, resp types.HijackedResponse) error {
var err error
receiveStdout := make(chan error, 1)
if outputStream != nil || errorStream != nil {
go func() {
// When TTY is ON, use regular copy
if tty && outputStream != nil {
_, err = io.Copy(outputStream, resp.Reader)
} else {
_, err = stdcopy.StdCopy(outputStream, errorStream, resp.Reader)
}
logrus.Debugf("[hijack] End of stdout")
receiveStdout <- err
}()
}
stdinDone := make(chan struct{})
go func() {
if inputStream != nil {
io.Copy(resp.Conn, inputStream)
logrus.Debugf("[hijack] End of stdin")
}
if err := resp.CloseWrite(); err != nil {
logrus.Debugf("Couldn't send EOF: %s", err)
}
close(stdinDone)
}()
select {
case err := <-receiveStdout:
if err != nil {
logrus.Debugf("Error receiveStdout: %s", err)
return err
}
case <-stdinDone:
if outputStream != nil || errorStream != nil {
if err := <-receiveStdout; err != nil {
logrus.Debugf("Error receiveStdout: %s", err)
return err
}
}
}
return nil
}
// Start the specified container with the specified host config
func (c *Container) Start(ctx context.Context) error {
logrus.WithFields(logrus.Fields{"container.ID": c.container.ID, "container.Name": c.container.Name}).Debug("Starting container")
if err := c.client.ContainerStart(ctx, c.container.ID, types.ContainerStartOptions{}); err != nil {
logrus.WithFields(logrus.Fields{"container.ID": c.container.ID, "container.Name": c.container.Name}).Debug("Failed to start container")
return err
}
return nil
}
// ID returns the container Id.
func (c *Container) ID() (string, error) {
return c.container.ID, nil
}
// Name returns the container name.
func (c *Container) Name() string {
return c.container.Name
}
// Restart restarts the container if existing, does nothing otherwise.
func (c *Container) Restart(ctx context.Context, timeout int) error {
timeoutDuration := time.Duration(timeout) * time.Second
return c.client.ContainerRestart(ctx, c.container.ID, &timeoutDuration)
}
// Log forwards container logs to the project configured logger.
func (c *Container) Log(ctx context.Context, l logger.Logger, follow bool) error {
info, err := c.client.ContainerInspect(ctx, c.container.ID)
if err != nil {
return err
}
options := types.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: true,
Follow: follow,
Tail: "all",
}
responseBody, err := c.client.ContainerLogs(ctx, c.container.ID, options)
if err != nil {
return err
}
defer responseBody.Close()
if info.Config.Tty {
_, err = io.Copy(&logger.Wrapper{Logger: l}, responseBody)
} else {
_, err = stdcopy.StdCopy(&logger.Wrapper{Logger: l}, &logger.Wrapper{Logger: l, Err: true}, responseBody)
}
logrus.WithFields(logrus.Fields{"Logger": l, "err": err}).Debug("c.client.Logs() returned error")
return err
}
// Port returns the host port the specified port is mapped on.
func (c *Container) Port(ctx context.Context, port string) (string, error) {
if bindings, ok := c.container.NetworkSettings.Ports[nat.Port(port)]; ok {
result := []string{}
for _, binding := range bindings {
result = append(result, binding.HostIP+":"+binding.HostPort)
}
return strings.Join(result, "\n"), nil
}
return "", nil
}
// Networks returns the containers network
func (c *Container) Networks() (map[string]*network.EndpointSettings, error) {
return c.container.NetworkSettings.Networks, nil
}
// Image returns the container image. Depending on the engine version its either
// the complete id or the digest reference the image.
func (c *Container) Image() string {
return c.container.Image
}
// ImageConfig returns the container image stored in the config. It's the
// human-readable name of the image.
func (c *Container) ImageConfig() string {
return c.container.Config.Image
}
// Hash returns the container hash stored as label.
func (c *Container) Hash() string {
return c.container.Config.Labels[labels.HASH.Str()]
}
// Number returns the container number stored as label.
func (c *Container) Number() (int, error) {
numberStr := c.container.Config.Labels[labels.NUMBER.Str()]
return strconv.Atoi(numberStr)
}