-
Notifications
You must be signed in to change notification settings - Fork 6
/
containers.go
541 lines (489 loc) · 15.3 KB
/
containers.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
package adoc
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
)
// This part contains apis for the containers listed in
// https://docs.docker.com/reference/api/docker_remote_api_v1.17/#21-containers
type Port struct {
IP string
PrivatePort int
PublicPort int
Type string
}
// Container defines basic container information for ListContainers
type Container struct {
Command string
Created int64
Id string
Image string
Labels map[string]string
Names []string
Ports []Port
SizeRootFs int64
SizeRw int64
Status string
}
type HealthConfig struct {
// Test is the test to perform to check that the container is healthy.
// An empty slice means to inherit the default.
// The options are:
// {} : inherit healthcheck
// {"NONE"} : disable healthcheck
// {"CMD", args...} : exec arguments directly
// {"CMD-SHELL", command} : run command with system's default shell
Test []string `json:",omitempty"`
// Zero means to inherit. Durations are expressed as integer nanoseconds.
Interval time.Duration `json:",omitempty"` // Interval is the time to wait between checks.
Timeout time.Duration `json:",omitempty"` // Timeout is the time to wait before considering the check to have hung.
StartPeriod time.Duration `json:",omitempty"` // The start period for the container to initialize before the retries starts to count down.
// Retries is the number of consecutive failures needed to consider a container as unhealthy.
// Zero means inherit.
Retries int `json:",omitempty"`
}
// ContainerConfig defines basic container creation data stucture
type ContainerConfig struct {
AttachStderr bool
AttachStdin bool
AttachStdout bool
Cmd []string
Domainname string
Entrypoint []string
Env []string
ExposedPorts map[string]struct{}
Healthcheck *HealthConfig `json:",omitempty"`
Hostname string
Image string
Labels map[string]string
MacAddress string
NetworkDisabled bool
OnBuild []string
OpenStdin bool
PortSpecs []string
StdinOnce bool
Tty bool
User string
VolumeDriver string
Volumes map[string]struct{}
WorkingDir string
}
type Device struct {
PathOnHost string
PathInContainer string
CgroupPermissions string
}
type RestartPolicy struct {
MaximumRetryCount int
Name string
}
type Ulimit struct {
Name string
Soft int64
Hard int64
}
type LogConfig struct {
Type string
Config map[string]string
}
// Resources contains container's resources (cgroups config, ulimits...)
type Resources struct {
// Applicable to all platforms
CPUShares int64 `json:"CpuShares"` // CPU shares (relative weight vs. other containers)
Memory int64 // Memory limit (in bytes)
// Applicable to UNIX platforms
CgroupParent string // Parent cgroup.
BlkioWeight uint16 // Block IO weight (relative weight vs. other containers)
BlkioWeightDevice []*WeightDevice
BlkioDeviceReadBps []*ThrottleDevice
BlkioDeviceWriteBps []*ThrottleDevice
BlkioDeviceReadIOps []*ThrottleDevice
BlkioDeviceWriteIOps []*ThrottleDevice
CPUPeriod int64 `json:"CpuPeriod"` // CPU CFS (Completely Fair Scheduler) period
CPUQuota int64 `json:"CpuQuota"` // CPU CFS (Completely Fair Scheduler) quota
CpusetCpus string // CpusetCpus 0-2, 0,1
CpusetMems string // CpusetMems 0-2, 0,1
Devices []Device
DiskQuota int64 // Disk limit (in bytes)
KernelMemory int64 // Kernel memory limit (in bytes)
MemoryReservation int64 // Memory soft limit (in bytes)
MemorySwap int64 // Total memory usage (memory + swap); set `-1` to enable unlimited swap
MemorySwappiness *int64 // Tuning container memory swappiness behaviour
OomKillDisable *bool // Whether to disable OOM Killer or not
PidsLimit int64 // Setting pids limit for a container
Ulimits []*Ulimit // List of ulimits to be set in the container
// Applicable to Windows
CPUCount int64 `json:"CpuCount"` // CPU count
CPUPercent int64 `json:"CpuPercent"` // CPU percent
IOMaximumIOps uint64 // Maximum IOps for the container system drive
IOMaximumBandwidth uint64 // Maximum IO in bytes per second for the container system drive
}
// HostConfig defines basic host configuration for container to run
type HostConfig struct {
Binds []string
CapAdd []string
CapDrop []string
ContainerIDFile string
Dns []string
DnsSearch []string
ExtraHosts []string
IpcMode string
Links []string
LxcConf []map[string]string
NetworkMode string
PidMode string
PortBindings map[string][]PortBinding
Privileged bool
PublishAllPorts bool
ReadonlyRootfs bool
RestartPolicy RestartPolicy
SecurityOpt []string
VolumesFrom []string
LogConfig LogConfig // 1.18
// Contains container's resources (cgroups, ulimits)
Resources
}
type PortBinding struct {
HostIp string
HostPort string
}
type Networks struct {
Gateway string
IPAddress string
}
type NetworkSettings struct {
Bridge string
Gateway string
GlobalIPv6Address string
GlobalIPv6PrefixLen int
IPAddress string
IPPrefixLen int
IPv6Gateway string
LinkLocalIPv6Address string
LinkLocalIPv6PrefixLen int
MacAddress string
Ports map[string][]PortBinding
Networks map[string]Networks
}
type Health struct {
Status string // Status is one of Starting, Healthy or Unhealthy
FailingStreak int // FailingStreak is the number of consecutive failures
}
// ContainerState defines container running state from inspection
type ContainerState struct {
Dead bool
Error string
ExitCode int
FinishedAt time.Time
OOMKilled bool
Paused bool
Pid int64
Restarting bool
Running bool
StartedAt time.Time
Health *Health
}
// SwarmNode defines the swarm api data for container running node
type SwarmNode struct {
Name string
ID string
Addr string
IP string
Cpus int
Memory int64
Labels map[string]string
}
type GraphDriverData struct {
// data
// Required: true
Data map[string]string `json:"Data"`
// name
// Required: true
Name string `json:"Name"`
}
// ContainerDetail defines the detail data of the container from inspection, including the swarm node infor
type ContainerDetail struct {
AppArmorProfile string
Args []string
Config ContainerConfig
Created time.Time
Driver string
ExecDriver string
ExecIDs []string
GraphDriver GraphDriverData
HostConfig HostConfig
HostnamePath string
HostsPath string
Id string
Image string
LogPath string
MountLabel string
Name string
NetworkSettings NetworkSettings
Path string
ProcessLabel string
ResolvConfPath string
RestartCount int
State ContainerState
Volumes map[string]string
VolumesRW map[string]bool
Node SwarmNode // swarm api
}
type NetworkOptions struct {
Container string
EndpointConfig EndpointConfig
Force bool
}
type IPAMConfig struct {
IPv4Address string
IPv6Address string
}
type EndpointConfig struct {
IPAMConfig IPAMConfig
}
type NetworkingConfig struct {
EndpointsConfig map[string]EndpointConfig
}
// ListContainers returns containers data, showAll flag defines if you want to show all the containers including the stopped ones
func (client *DockerClient) ListContainers(showAll, showSize bool, filters ...string) ([]Container, error) {
v := url.Values{}
v.Set("all", formatBoolToIntString(showAll))
v.Set("size", formatBoolToIntString(showSize))
if len(filters) > 0 && filters[0] != "" {
v.Set("filters", filters[0])
}
uri := fmt.Sprintf("containers/json?%s", v.Encode())
if data, err := client.sendRequest("GET", uri, nil, nil, nil); err != nil {
return nil, err
} else {
var ret []Container
err := json.Unmarshal(data, &ret)
return ret, err
}
}
// InspectContainer returns container detail data with container id
func (client *DockerClient) InspectContainer(id string) (ContainerDetail, error) {
uri := fmt.Sprintf("containers/%s/json", id)
var ret ContainerDetail
if data, err := client.sendRequest("GET", uri, nil, nil, nil); err != nil {
return ret, err
} else {
err := json.Unmarshal(data, &ret)
return ret, err
}
}
func (client *DockerClient) CreateContainer(containerConf ContainerConfig, hostConf HostConfig, networkingConf NetworkingConfig, name ...string) (string, error) {
var config struct {
ContainerConfig
HostConfig HostConfig
NetworkingConfig NetworkingConfig
}
config.ContainerConfig = containerConf
config.HostConfig = hostConf
config.NetworkingConfig = networkingConf
// extra time for pull image
rc := &RequestConfig{ExtraTimeout: ImagePuSecs}
if body, err := json.Marshal(config); err != nil {
return "", err
} else {
uri := "containers/create"
if len(name) > 0 && name[0] != "" {
v := url.Values{}
v.Set("name", name[0])
uri += "?" + v.Encode()
}
if data, err := client.sendRequest("POST", uri, body, nil, rc); err != nil {
return "", err
} else {
var resp struct {
Id string
Warnings []string
}
err := json.Unmarshal(data, &resp)
if len(resp.Warnings) > 0 {
logger.Warnf("Create container returns warning from docker daemon: %+v", resp.Warnings)
}
return resp.Id, err
}
}
}
func (client *DockerClient) ConnectContainer(networkName string, id string, ipAddr string) error {
var nc NetworkOptions
nc.Container = id
nc.EndpointConfig.IPAMConfig.IPv4Address = ipAddr
if body, err := json.Marshal(nc); err != nil {
return err
} else {
uri := fmt.Sprintf("networks/%s/connect", networkName)
_, err := client.sendRequest("POST", uri, body, nil, nil)
return err
}
}
func (client *DockerClient) DisconnectContainer(networkName string, id string, force bool) error {
var nc NetworkOptions
nc.Container = id
nc.Force = force
if body, err := json.Marshal(nc); err != nil {
return err
} else {
uri := fmt.Sprintf("networks/%s/disconnect", networkName)
_, err := client.sendRequest("POST", uri, body, nil, nil)
return err
}
}
func (client *DockerClient) StartContainer(id string) error {
uri := fmt.Sprintf("containers/%s/start", id)
_, err := client.sendRequest("POST", uri, nil, nil, nil)
return err
}
func (client *DockerClient) StopContainer(id string, timeout ...int) error {
uri := fmt.Sprintf("containers/%s/stop", id)
var rc *RequestConfig
if len(timeout) > 0 && timeout[0] >= 0 {
v := url.Values{}
v.Set("t", fmt.Sprintf("%d", timeout[0]))
uri += "?" + v.Encode()
rc = &RequestConfig{ExtraTimeout: time.Duration(timeout[0]) * time.Second}
} else {
rc = &RequestConfig{ExtraTimeout: 10 * time.Second}
}
_, err := client.sendRequest("POST", uri, nil, nil, rc)
return err
}
func (client *DockerClient) UpdateContainer(id string, config interface{}) error {
uri := fmt.Sprintf("containers/%s/update", id)
body, err := json.Marshal(config)
if err != nil {
return err
}
_, err = client.sendRequest("POST", uri, body, nil, nil)
return err
}
func (client *DockerClient) RestartContainer(id string, timeout ...int) error {
uri := fmt.Sprintf("containers/%s/restart", id)
var rc *RequestConfig
if len(timeout) > 0 && timeout[0] >= 0 {
v := url.Values{}
v.Set("t", fmt.Sprintf("%d", timeout[0]))
uri += "?" + v.Encode()
rc = &RequestConfig{ExtraTimeout: time.Duration(timeout[0]) * time.Second}
} else {
rc = &RequestConfig{ExtraTimeout: 10 * time.Second}
}
_, err := client.sendRequest("POST", uri, nil, nil, rc)
return err
}
func (client *DockerClient) KillContainer(id string, signal ...string) error {
uri := fmt.Sprintf("containers/%s/kill", id)
if len(signal) > 0 && signal[0] != "" {
v := url.Values{}
v.Set("signal", signal[0])
uri += "?" + v.Encode()
}
_, err := client.sendRequest("POST", uri, nil, nil, nil)
return err
}
func (client *DockerClient) PauseContainer(id string) error {
uri := fmt.Sprintf("containers/%s/pause", id)
_, err := client.sendRequest("POST", uri, nil, nil, nil)
return err
}
func (client *DockerClient) UnpauseContainer(id string) error {
uri := fmt.Sprintf("containers/%s/unpause", id)
_, err := client.sendRequest("POST", uri, nil, nil, nil)
return err
}
func (client *DockerClient) RemoveContainer(id string, force, volumes bool) error {
v := url.Values{}
v.Set("force", formatBoolToIntString(force))
v.Set("v", formatBoolToIntString(volumes))
uri := fmt.Sprintf("containers/%s?%s", id, v.Encode())
_, err := client.sendRequest("DELETE", uri, nil, nil, nil)
return err
}
func (client *DockerClient) RenameContainer(id string, name string) error {
v := url.Values{}
v.Set("name", name)
uri := fmt.Sprintf("containers/%s/rename?%s", id, v.Encode())
_, err := client.sendRequest("POST", uri, nil, nil, nil)
return err
}
// This will block the call routine until the container is stopped
func (client *DockerClient) WaitContainer(id string) (int, error) {
uri := fmt.Sprintf("containers/%s/wait", id)
if data, err := client.sendRequest("POST", uri, nil, nil, nil, true); err != nil {
return 0, err
} else {
var ret map[string]int
if err := json.Unmarshal(data, &ret); err != nil {
return 0, err
}
if code, ok := ret["StatusCode"]; ok {
return code, nil
} else {
logger.Warnf("There is no StatusCode key inside results map, the API maybe changed, ret=%+v", ret)
return 0, fmt.Errorf("Cannot get StatusCode from return data, %+v", ret)
}
}
}
func (client *DockerClient) ContainerLogs(id string, stdout, stderr, timestamps bool, tail ...int) ([]LogEntry, error) {
// no following mode
v := url.Values{}
v.Set("stdout", formatBoolToIntString(stdout))
v.Set("stderr", formatBoolToIntString(stderr))
v.Set("timestamps", formatBoolToIntString(timestamps))
if len(tail) > 0 && tail[0] >= 0 {
v.Set("tail", fmt.Sprintf("%d", tail[0]))
}
uri := fmt.Sprintf("containers/%s/logs?%s", id, v.Encode())
var entries []LogEntry
err := client.sendRequestCallback("GET", uri, nil, nil, func(resp *http.Response) error {
var cbErr error
entries, cbErr = ReadAllDockerLogs(resp.Body)
return cbErr
}, nil)
return entries, err
}
type Processes struct {
Titles []string
Processes [][]string
}
func (client *DockerClient) ContainerProcesses(id string, psArgs ...string) (Processes, error) {
var procs Processes
v := url.Values{}
if len(psArgs) > 0 && psArgs[0] != "" {
v.Set("ps_args", psArgs[0])
}
uri := fmt.Sprintf("containers/%s/top", id)
if len(v) > 0 {
uri += "?" + v.Encode()
}
if data, err := client.sendRequest("GET", uri, nil, nil, nil); err != nil {
return procs, err
} else {
err := json.Unmarshal(data, &procs)
return procs, err
}
}
type FsChange struct {
Path string
Kind int
}
func (client *DockerClient) ContainerChanges(id string) ([]FsChange, error) {
uri := fmt.Sprintf("containers/%s/changes", id)
if data, err := client.sendRequest("GET", uri, nil, nil, nil); err != nil {
return nil, err
} else {
var changes []FsChange
err := json.Unmarshal(data, &changes)
return changes, err
}
}
// Missing apis for
// containers/(id)/copy
// containers/(id)/attach
// containers/(id)/export
// containers/(id)/resize?h=<height>&w=<width>
// containers/(id)/attach/ws