-
Notifications
You must be signed in to change notification settings - Fork 803
/
container.go
384 lines (313 loc) · 11.2 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
380
381
382
383
384
// Package container contains code related to dealing with docker containers
package container
import (
"fmt"
"strconv"
"strings"
"github.com/containrrr/watchtower/internal/util"
wt "github.com/containrrr/watchtower/pkg/types"
"github.com/docker/docker/api/types"
dockercontainer "github.com/docker/docker/api/types/container"
"github.com/docker/go-connections/nat"
)
// NewContainer returns a new Container instance instantiated with the
// specified ContainerInfo and ImageInfo structs.
func NewContainer(containerInfo *types.ContainerJSON, imageInfo *types.ImageInspect) *Container {
return &Container{
containerInfo: containerInfo,
imageInfo: imageInfo,
}
}
// Container represents a running Docker container.
type Container struct {
LinkedToRestarting bool
Stale bool
containerInfo *types.ContainerJSON
imageInfo *types.ImageInspect
}
// IsLinkedToRestarting returns the current value of the LinkedToRestarting field for the container
func (c *Container) IsLinkedToRestarting() bool {
return c.LinkedToRestarting
}
// IsStale returns the current value of the Stale field for the container
func (c *Container) IsStale() bool {
return c.Stale
}
// SetLinkedToRestarting sets the LinkedToRestarting field for the container
func (c *Container) SetLinkedToRestarting(value bool) {
c.LinkedToRestarting = value
}
// SetStale implements sets the Stale field for the container
func (c *Container) SetStale(value bool) {
c.Stale = value
}
// ContainerInfo fetches JSON info for the container
func (c Container) ContainerInfo() *types.ContainerJSON {
return c.containerInfo
}
// ID returns the Docker container ID.
func (c Container) ID() wt.ContainerID {
return wt.ContainerID(c.containerInfo.ID)
}
// IsRunning returns a boolean flag indicating whether or not the current
// container is running. The status is determined by the value of the
// container's "State.Running" property.
func (c Container) IsRunning() bool {
return c.containerInfo.State.Running
}
// IsRestarting returns a boolean flag indicating whether or not the current
// container is restarting. The status is determined by the value of the
// container's "State.Restarting" property.
func (c Container) IsRestarting() bool {
return c.containerInfo.State.Restarting
}
// Name returns the Docker container name.
func (c Container) Name() string {
return c.containerInfo.Name
}
// ImageID returns the ID of the Docker image that was used to start the
// container. May cause nil dereference if imageInfo is not set!
func (c Container) ImageID() wt.ImageID {
return wt.ImageID(c.imageInfo.ID)
}
// SafeImageID returns the ID of the Docker image that was used to start the container if available,
// otherwise returns an empty string
func (c Container) SafeImageID() wt.ImageID {
if c.imageInfo == nil {
return ""
}
return wt.ImageID(c.imageInfo.ID)
}
// ImageName returns the name of the Docker image that was used to start the
// container. If the original image was specified without a particular tag, the
// "latest" tag is assumed.
func (c Container) ImageName() string {
// Compatibility w/ Zodiac deployments
imageName, ok := c.getLabelValue(zodiacLabel)
if !ok {
imageName = c.containerInfo.Config.Image
}
if !strings.Contains(imageName, ":") {
imageName = fmt.Sprintf("%s:latest", imageName)
}
return imageName
}
// Enabled returns the value of the container enabled label and if the label
// was set.
func (c Container) Enabled() (bool, bool) {
rawBool, ok := c.getLabelValue(enableLabel)
if !ok {
return false, false
}
parsedBool, err := strconv.ParseBool(rawBool)
if err != nil {
return false, false
}
return parsedBool, true
}
// IsMonitorOnly returns the value of the monitor-only label. If the label
// is not set then false is returned.
func (c Container) IsMonitorOnly() bool {
rawBool, ok := c.getLabelValue(monitorOnlyLabel)
if !ok {
return false
}
parsedBool, err := strconv.ParseBool(rawBool)
if err != nil {
return false
}
return parsedBool
}
// IsNoPull returns the value of the no-pull label. If the label is not set
// then false is returned.
func (c Container) IsNoPull() bool {
rawBool, ok := c.getLabelValue(noPullLabel)
if !ok {
return false
}
parsedBool, err := strconv.ParseBool(rawBool)
if err != nil {
return false
}
return parsedBool
}
// Scope returns the value of the scope UID label and if the label
// was set.
func (c Container) Scope() (string, bool) {
rawString, ok := c.getLabelValue(scope)
if !ok {
return "", false
}
return rawString, true
}
// Links returns a list containing the names of all the containers to which
// this container is linked.
func (c Container) Links() []string {
var links []string
dependsOnLabelValue := c.getLabelValueOrEmpty(dependsOnLabel)
if dependsOnLabelValue != "" {
for _, link := range strings.Split(dependsOnLabelValue, ",") {
// Since the container names need to start with '/', let's prepend it if it's missing
if !strings.HasPrefix(link, "/") {
link = "/" + link
}
links = append(links, link)
}
return links
}
if (c.containerInfo != nil) && (c.containerInfo.HostConfig != nil) {
for _, link := range c.containerInfo.HostConfig.Links {
name := strings.Split(link, ":")[0]
links = append(links, name)
}
// If the container uses another container for networking, it can be considered an implicit link
// since the container would stop working if the network supplier were to be recreated
networkMode := c.containerInfo.HostConfig.NetworkMode
if networkMode.IsContainer() {
links = append(links, networkMode.ConnectedContainer())
}
}
return links
}
// ToRestart return whether the container should be restarted, either because
// is stale or linked to another stale container.
func (c Container) ToRestart() bool {
return c.Stale || c.LinkedToRestarting
}
// IsWatchtower returns a boolean flag indicating whether or not the current
// container is the watchtower container itself. The watchtower container is
// identified by the presence of the "com.centurylinklabs.watchtower" label in
// the container metadata.
func (c Container) IsWatchtower() bool {
return ContainsWatchtowerLabel(c.containerInfo.Config.Labels)
}
// PreUpdateTimeout checks whether a container has a specific timeout set
// for how long the pre-update command is allowed to run. This value is expressed
// either as an integer, in minutes, or as 0 which will allow the command/script
// to run indefinitely. Users should be cautious with the 0 option, as that
// could result in watchtower waiting forever.
func (c Container) PreUpdateTimeout() int {
var minutes int
var err error
val := c.getLabelValueOrEmpty(preUpdateTimeoutLabel)
minutes, err = strconv.Atoi(val)
if err != nil || val == "" {
return 1
}
return minutes
}
// PostUpdateTimeout checks whether a container has a specific timeout set
// for how long the post-update command is allowed to run. This value is expressed
// either as an integer, in minutes, or as 0 which will allow the command/script
// to run indefinitely. Users should be cautious with the 0 option, as that
// could result in watchtower waiting forever.
func (c Container) PostUpdateTimeout() int {
var minutes int
var err error
val := c.getLabelValueOrEmpty(postUpdateTimeoutLabel)
minutes, err = strconv.Atoi(val)
if err != nil || val == "" {
return 1
}
return minutes
}
// StopSignal returns the custom stop signal (if any) that is encoded in the
// container's metadata. If the container has not specified a custom stop
// signal, the empty string "" is returned.
func (c Container) StopSignal() string {
return c.getLabelValueOrEmpty(signalLabel)
}
// GetCreateConfig returns the container's current Config converted into a format
// that can be re-submitted to the Docker create API.
//
// Ideally, we'd just be able to take the ContainerConfig from the old container
// and use it as the starting point for creating the new container; however,
// the ContainerConfig that comes back from the Inspect call merges the default
// configuration (the stuff specified in the metadata for the image itself)
// with the overridden configuration (the stuff that you might specify as part
// of the "docker run").
//
// In order to avoid unintentionally overriding the
// defaults in the new image we need to separate the override options from the
// default options. To do this we have to compare the ContainerConfig for the
// running container with the ContainerConfig from the image that container was
// started from. This function returns a ContainerConfig which contains just
// the options overridden at runtime.
func (c Container) GetCreateConfig() *dockercontainer.Config {
config := c.containerInfo.Config
hostConfig := c.containerInfo.HostConfig
imageConfig := c.imageInfo.Config
if config.WorkingDir == imageConfig.WorkingDir {
config.WorkingDir = ""
}
if config.User == imageConfig.User {
config.User = ""
}
if hostConfig.NetworkMode.IsContainer() {
config.Hostname = ""
}
if util.SliceEqual(config.Entrypoint, imageConfig.Entrypoint) {
config.Entrypoint = nil
if util.SliceEqual(config.Cmd, imageConfig.Cmd) {
config.Cmd = nil
}
}
config.Env = util.SliceSubtract(config.Env, imageConfig.Env)
config.Labels = util.StringMapSubtract(config.Labels, imageConfig.Labels)
config.Volumes = util.StructMapSubtract(config.Volumes, imageConfig.Volumes)
// subtract ports exposed in image from container
for k := range config.ExposedPorts {
if _, ok := imageConfig.ExposedPorts[k]; ok {
delete(config.ExposedPorts, k)
}
}
for p := range c.containerInfo.HostConfig.PortBindings {
config.ExposedPorts[p] = struct{}{}
}
config.Image = c.ImageName()
return config
}
// GetCreateHostConfig returns the container's current HostConfig with any links
// re-written so that they can be re-submitted to the Docker create API.
func (c Container) GetCreateHostConfig() *dockercontainer.HostConfig {
hostConfig := c.containerInfo.HostConfig
for i, link := range hostConfig.Links {
name := link[0:strings.Index(link, ":")]
alias := link[strings.LastIndex(link, "/"):]
hostConfig.Links[i] = fmt.Sprintf("%s:%s", name, alias)
}
return hostConfig
}
// HasImageInfo returns whether image information could be retrieved for the container
func (c Container) HasImageInfo() bool {
return c.imageInfo != nil
}
// ImageInfo fetches the ImageInspect data of the current container
func (c Container) ImageInfo() *types.ImageInspect {
return c.imageInfo
}
// VerifyConfiguration checks the container and image configurations for nil references to make sure
// that the container can be recreated once deleted
func (c Container) VerifyConfiguration() error {
if c.imageInfo == nil {
return errorNoImageInfo
}
containerInfo := c.ContainerInfo()
if containerInfo == nil {
return errorNoContainerInfo
}
containerConfig := containerInfo.Config
if containerConfig == nil {
return errorInvalidConfig
}
hostConfig := containerInfo.HostConfig
if hostConfig == nil {
return errorInvalidConfig
}
// Instead of returning an error here, we just create an empty map
// This should allow for updating containers where the exposed ports are missing
if len(hostConfig.PortBindings) > 0 && containerConfig.ExposedPorts == nil {
containerConfig.ExposedPorts = make(map[nat.Port]struct{})
}
return nil
}