forked from michaelsauter/crane
/
container.go
946 lines (872 loc) · 25.1 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
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
package crane
import (
"encoding/json"
"fmt"
"github.com/flynn/go-shlex"
"github.com/michaelsauter/crane/print"
"io"
"os"
"path"
"strconv"
"strings"
)
type Container interface {
Name() string
Dockerfile() string
Image() string
ImageWithTag() string
Id() string
Dependencies() *Dependencies
Exists() bool
Running() bool
Paused() bool
ImageExists() bool
Status() []string
Provision(nocache bool)
ProvisionOrSkip(update bool, nocache bool)
PullImage()
Create(ignoreMissing string, configPath string)
Run(ignoreMissing string, configPath string)
Start()
RunOrStart(ignoreMissing string, configPath string)
Kill()
Stop()
Pause()
Unpause()
Rm(force bool)
Logs(follow bool, since string, tail string) (stdout, stderr io.Reader)
Push()
Hooks() Hooks
}
type container struct {
id string
RawName string
RawDockerfile string `json:"dockerfile" yaml:"dockerfile"`
RawImage string `json:"image" yaml:"image"`
RunParams RunParameters `json:"run" yaml:"run"`
RmParams RmParameters `json:"rm" yaml:"rm"`
StartParams StartParameters `json:"start" yaml:"start"`
hooks hooks
}
type RunParameters struct {
RawAddHost []string `json:"add-host" yaml:"add-host"`
BlkioWeight int `json:"blkio-weight" yaml:"blkio-weight"`
RawCapAdd []string `json:"cap-add" yaml:"cap-add"`
RawCapDrop []string `json:"cap-drop" yaml:"cap-drop"`
RawCgroupParent string `json:"cgroup-parent" yaml:"cgroup-parent"`
CpuPeriod int `json:"cpu-period" yaml:"cpu-period"`
CpuQuota int `json:"cpu-quota" yaml:"cpu-quota"`
RawCidfile string `json:"cidfile" yaml:"cidfile"`
Cpuset int `json:"cpuset" yaml:"cpuset"`
CpuShares int `json:"cpu-shares" yaml:"cpu-shares"`
Detach bool `json:"detach" yaml:"detach"`
RawDevice []string `json:"device" yaml:"device"`
RawDns []string `json:"dns" yaml:"dns"`
RawEntrypoint string `json:"entrypoint" yaml:"entrypoint"`
RawEnv interface{} `json:"env" yaml:"env"`
RawEnvFile []string `json:"env-file" yaml:"env-file"`
RawExpose []string `json:"expose" yaml:"expose"`
RawHostname string `json:"hostname" yaml:"hostname"`
Interactive bool `json:"interactive" yaml:"interactive"`
RawLabel interface{} `json:"label" yaml:"label"`
RawLabelFile []string `json:"label-file" yaml:"label-file"`
RawLink []string `json:"link" yaml:"link"`
RawLogDriver string `json:"log-driver" yaml:"log-driver"`
RawLogOpt []string `json:"log-opt" yaml:"log-opt"`
RawLxcConf []string `json:"lxc-conf" yaml:"lxc-conf"`
RawMacAddress string `json:"mac-address" yaml:"mac-address"`
RawMemory string `json:"memory" yaml:"memory"`
RawMemorySwap string `json:"memory-swap" yaml:"memory-swap"`
RawNet string `json:"net" yaml:"net"`
OomKillDisable bool `json:"oom-kill-disable" yaml:"oom-kill-disable"`
RawPid string `json:"pid" yaml:"pid"`
Privileged bool `json:"privileged" yaml:"privileged"`
RawPublish []string `json:"publish" yaml:"publish"`
PublishAll bool `json:"publish-all" yaml:"publish-all"`
ReadOnly bool `json:"read-only" yaml:"read-only"`
RawRestart string `json:"restart" yaml:"restart"`
Rm bool `json:"rm" yaml:"rm"`
RawSecurityOpt []string `json:"security-opt" yaml:"security-opt"`
SigProxy OptBool `json:"sig-proxy" yaml:"sig-proxy"`
Tty bool `json:"tty" yaml:"tty"`
RawUlimit []string `json:"ulimit" yaml:"ulimit"`
RawUser string `json:"user" yaml:"user"`
RawUts string `json:"uts" yaml:"uts"`
RawVolume []string `json:"volume" yaml:"volume"`
RawVolumesFrom []string `json:"volumes-from" yaml:"volumes-from"`
RawWorkdir string `json:"workdir" yaml:"workdir"`
RawCmd interface{} `json:"cmd" yaml:"cmd"`
}
type RmParameters struct {
Volumes bool `json:"volumes" yaml:"volumes"`
}
type StartParameters struct {
Attach bool `json:"attach" yaml:"attach"`
Interactive bool `json:"interactive" yaml:"interactive"`
}
type OptBool struct {
Defined bool
Value bool
}
func (o *OptBool) UnmarshalYAML(unmarshal func(interface{}) error) error {
if err := unmarshal(&o.Value); err != nil {
return err
}
o.Defined = true
return nil
}
func (o *OptBool) UnmarshalJSON(b []byte) (err error) {
if err := json.Unmarshal(b, &o.Value); err != nil {
return err
}
o.Defined = true
return
}
func (c *container) netContainer() (name string) {
if netParts := strings.Split(c.RunParams.Net(), ":"); len(netParts) == 2 && netParts[0] == "container" {
// We'll just assume here that the reference is a name, and not an id, even
// though docker supports it, since we have no bullet-proof way to tell:
// heuristics to detect whether it's an id could bring false positives, and
// a lookup in the list of container names could bring false negatives
name = netParts[1]
}
return
}
func (c *container) Dependencies() *Dependencies {
dependencies := &Dependencies{}
for _, link := range c.RunParams.Link() {
linkName := strings.Split(link, ":")[0]
if !dependencies.includes(linkName) {
dependencies.All = append(dependencies.All, linkName)
dependencies.Link = append(dependencies.Link, linkName)
}
}
for _, volumesFrom := range c.RunParams.VolumesFrom() {
volumesFromName := strings.Split(volumesFrom, ":")[0]
if !dependencies.includes(volumesFromName) {
dependencies.All = append(dependencies.All, volumesFromName)
dependencies.VolumesFrom = append(dependencies.VolumesFrom, volumesFromName)
}
}
if dependencies.Net = c.netContainer(); dependencies.Net != "" {
if !dependencies.includes(dependencies.Net) {
dependencies.All = append(dependencies.All, dependencies.Net)
}
}
return dependencies
}
func (c *container) Name() string {
return os.ExpandEnv(c.RawName)
}
func (c *container) Dockerfile() string {
return os.ExpandEnv(c.RawDockerfile)
}
func (c *container) Image() string {
return os.ExpandEnv(c.RawImage)
}
func (c *container) ImageWithTag() string {
imageParts := strings.Split(c.Image(), "/")
lastImagePart := imageParts[len(imageParts)-1]
if !strings.Contains(lastImagePart, ":") {
return lastImagePart + ":latest"
}
return lastImagePart
}
func (r *RunParameters) AddHost() []string {
var addHost []string
for _, rawAddHost := range r.RawAddHost {
addHost = append(addHost, os.ExpandEnv(rawAddHost))
}
return addHost
}
func (r *RunParameters) CapAdd() []string {
var capAdd []string
for _, rawCapAdd := range r.RawCapAdd {
capAdd = append(capAdd, os.ExpandEnv(rawCapAdd))
}
return capAdd
}
func (r *RunParameters) CapDrop() []string {
var capDrop []string
for _, rawCapDrop := range r.RawCapDrop {
capDrop = append(capDrop, os.ExpandEnv(rawCapDrop))
}
return capDrop
}
func (r *RunParameters) CgroupParent() string {
return os.ExpandEnv(r.RawCgroupParent)
}
func (r *RunParameters) Cidfile() string {
return os.ExpandEnv(r.RawCidfile)
}
func (r *RunParameters) Device() []string {
var device []string
for _, rawDevice := range r.RawDevice {
device = append(device, os.ExpandEnv(rawDevice))
}
return device
}
func (r *RunParameters) Dns() []string {
var dns []string
for _, rawDns := range r.RawDns {
dns = append(dns, os.ExpandEnv(rawDns))
}
return dns
}
func (r *RunParameters) Entrypoint() string {
return os.ExpandEnv(r.RawEntrypoint)
}
func (r *RunParameters) Env() []string {
var env []string
if r.RawEnv != nil {
switch rawEnv := r.RawEnv.(type) {
case []interface{}:
for _, v := range rawEnv {
env = append(env, os.ExpandEnv(v.(string)))
}
case map[interface{}]interface{}:
for k, v := range rawEnv {
env = append(env, os.ExpandEnv(k.(string))+"="+os.ExpandEnv(v.(string)))
}
default:
print.Errorf("env is of unknown type!")
}
}
return env
}
func (r *RunParameters) EnvFile() []string {
var envFile []string
for _, rawEnvFile := range r.RawEnvFile {
envFile = append(envFile, os.ExpandEnv(rawEnvFile))
}
return envFile
}
func (r *RunParameters) Expose() []string {
var expose []string
for _, rawExpose := range r.RawExpose {
expose = append(expose, os.ExpandEnv(rawExpose))
}
return expose
}
func (r *RunParameters) Hostname() string {
return os.ExpandEnv(r.RawHostname)
}
func (r *RunParameters) Label() []string {
var label []string
if r.RawLabel != nil {
switch rawLabel := r.RawLabel.(type) {
case []interface{}:
for _, v := range rawLabel {
label = append(label, os.ExpandEnv(v.(string)))
}
case map[interface{}]interface{}:
for k, v := range rawLabel {
label = append(label, os.ExpandEnv(k.(string))+"="+os.ExpandEnv(v.(string)))
}
default:
print.Errorf("label is of unknown type!")
}
}
return label
}
func (r *RunParameters) LabelFile() []string {
var labelFile []string
for _, rawLabelFile := range r.RawLabelFile {
labelFile = append(labelFile, os.ExpandEnv(rawLabelFile))
}
return labelFile
}
func (r *RunParameters) Link() []string {
var link []string
for _, rawLink := range r.RawLink {
link = append(link, os.ExpandEnv(rawLink))
}
return link
}
func (r *RunParameters) LogDriver() string {
return os.ExpandEnv(r.RawLogDriver)
}
func (r *RunParameters) LogOpt() []string {
var opt []string
for _, rawOpt := range r.RawLogOpt {
opt = append(opt, os.ExpandEnv(rawOpt))
}
return opt
}
func (r *RunParameters) LxcConf() []string {
var lxcConf []string
for _, rawLxcConf := range r.RawLxcConf {
lxcConf = append(lxcConf, os.ExpandEnv(rawLxcConf))
}
return lxcConf
}
func (r *RunParameters) MacAddress() string {
return os.ExpandEnv(r.RawMacAddress)
}
func (r *RunParameters) Memory() string {
return os.ExpandEnv(r.RawMemory)
}
func (r *RunParameters) MemorySwap() string {
return os.ExpandEnv(r.RawMemorySwap)
}
func (r *RunParameters) Net() string {
// Default to bridge
if len(r.RawNet) == 0 {
return "bridge"
} else {
return os.ExpandEnv(r.RawNet)
}
}
func (r *RunParameters) Pid() string {
return os.ExpandEnv(r.RawPid)
}
func (r *RunParameters) Publish() []string {
var publish []string
for _, rawPublish := range r.RawPublish {
publish = append(publish, os.ExpandEnv(rawPublish))
}
return publish
}
func (r *RunParameters) Restart() string {
return os.ExpandEnv(r.RawRestart)
}
func (r *RunParameters) SecurityOpt() []string {
var securityOpt []string
for _, rawSecurityOpt := range r.RawSecurityOpt {
securityOpt = append(securityOpt, os.ExpandEnv(rawSecurityOpt))
}
return securityOpt
}
func (r *RunParameters) Ulimit() []string {
var ulimit []string
for _, rawUlimit := range r.RawUlimit {
ulimit = append(ulimit, os.ExpandEnv(rawUlimit))
}
return ulimit
}
func (r *RunParameters) User() string {
return os.ExpandEnv(r.RawUser)
}
func (r *RunParameters) Uts() string {
return os.ExpandEnv(r.RawUts)
}
func (r *RunParameters) Volume(configPath string) []string {
var volumes []string
for _, rawVolume := range r.RawVolume {
volume := os.ExpandEnv(rawVolume)
paths := strings.Split(volume, ":")
if !path.IsAbs(paths[0]) {
paths[0] = configPath + "/" + paths[0]
}
volumes = append(volumes, strings.Join(paths, ":"))
}
return volumes
}
func (r *RunParameters) VolumesFrom() []string {
var volumesFrom []string
for _, rawVolumesFrom := range r.RawVolumesFrom {
volumesFrom = append(volumesFrom, os.ExpandEnv(rawVolumesFrom))
}
return volumesFrom
}
func (r *RunParameters) Workdir() string {
return os.ExpandEnv(r.RawWorkdir)
}
func (r *RunParameters) Cmd() []string {
var cmd []string
if r.RawCmd != nil {
switch rawCmd := r.RawCmd.(type) {
case string:
if len(rawCmd) > 0 {
cmds, err := shlex.Split(os.ExpandEnv(rawCmd))
if err != nil {
print.Errorf("Error when parsing cmd `%v`: %v. Proceeding with %q.", rawCmd, err, cmds)
}
cmd = append(cmd, cmds...)
}
case []interface{}:
cmds := make([]string, len(rawCmd))
for i, v := range rawCmd {
cmds[i] = os.ExpandEnv(v.(string))
}
cmd = append(cmd, cmds...)
default:
print.Errorf("cmd is of unknown type!")
}
}
return cmd
}
func (c *container) Id() string {
if len(c.id) == 0 {
// `docker inspect` works for both image and containers, make sure this is a
// container payload we get back, otherwise we might end up getting the Id
// of the image of the same name.
c.id = inspectString(c.Name(), "{{if .State}}{{.Id}}{{else}}{{end}}")
}
return c.id
}
func (c *container) Exists() bool {
return c.Id() != ""
}
func (c *container) Running() bool {
if !c.Exists() {
return false
}
return inspectBool(c.Id(), "{{.State.Running}}")
}
func (c *container) Paused() bool {
if !c.Exists() {
return false
}
return inspectBool(c.Id(), "{{.State.Paused}}")
}
func (c *container) ImageExists() bool {
_, err := commandOutput("docker", []string{"inspect", c.ImageWithTag()})
return err == nil
}
func (c *container) Status() []string {
fields := []string{c.Name(), c.Image(), "-", "-", "-", "-", "-"}
output := inspectString(c.Id(), "{{.Id}}\t{{.Image}}\t{{if .NetworkSettings.IPAddress}}{{.NetworkSettings.IPAddress}}{{else}}-{{end}}\t{{range $k,$v := $.NetworkSettings.Ports}}{{$k}},{{else}}-{{end}}\t{{.State.Running}}")
if output != "" {
copy(fields[2:], strings.Split(output, "\t"))
// We asked for the image id the container was created from
fields[3] = strconv.FormatBool(imageIdFromTag(fields[1]) == fields[3])
}
return fields
}
func (c *container) Provision(nocache bool) {
if len(c.Dockerfile()) > 0 {
c.buildImage(nocache)
} else {
c.PullImage()
}
}
// Run or start container
func (c *container) RunOrStart(ignoreMissing string, configPath string) {
if c.Exists() {
c.Start()
} else {
c.Run(ignoreMissing, configPath)
}
}
// Provision or skip container
func (c *container) ProvisionOrSkip(update bool, nocache bool) {
if update || !c.ImageExists() {
c.Provision(nocache)
}
}
// Create container
func (c *container) Create(ignoreMissing string, configPath string) {
if c.Exists() {
print.Noticef("Container %s does already exist. Use --recreate to recreate.\n", c.Name())
} else {
fmt.Printf("Creating container %s ... ", c.Name())
args := append([]string{"create"}, c.createArgs(ignoreMissing, configPath)...)
executeCommand("docker", args)
}
}
// Run container, or start it if already existing
func (c *container) Run(ignoreMissing string, configPath string) {
if c.Exists() {
print.Noticef("Container %s does already exist. Use --recreate to recreate.\n", c.Name())
if !c.Running() {
c.Start()
}
} else {
executeHook(c.Hooks().PreStart())
fmt.Printf("Running container %s ... ", c.Name())
args := []string{"run"}
// Detach
if c.RunParams.Detach {
args = append(args, "--detach")
}
args = append(args, c.createArgs(ignoreMissing, configPath)...)
executeCommand("docker", args)
executeHook(c.Hooks().PostStart())
}
}
// Returns all the flags to be passed to `docker create`
func (c *container) createArgs(ignoreMissing string, configPath string) []string {
args := []string{}
// AddHost
for _, addHost := range c.RunParams.AddHost() {
args = append(args, "--add-host", addHost)
}
// BlkioWeight
if c.RunParams.BlkioWeight > 0 {
args = append(args, "--blkio-weight", strconv.Itoa(c.RunParams.BlkioWeight))
}
// CapAdd
for _, capAdd := range c.RunParams.CapAdd() {
args = append(args, "--cap-add", capAdd)
}
// CapDrop
for _, capDrop := range c.RunParams.CapDrop() {
args = append(args, "--cap-drop", capDrop)
}
// CgroupParent
if len(c.RunParams.CgroupParent()) > 0 {
args = append(args, "--cgroup-parent", c.RunParams.CgroupParent())
}
// Cidfile
if len(c.RunParams.Cidfile()) > 0 {
args = append(args, "--cidfile", c.RunParams.Cidfile())
}
// CpuPeriod
if c.RunParams.CpuPeriod > 0 {
args = append(args, "--cpu-period", strconv.Itoa(c.RunParams.CpuPeriod))
}
// CpuQuota
if c.RunParams.CpuQuota > 0 {
args = append(args, "--cpu-quota", strconv.Itoa(c.RunParams.CpuQuota))
}
// CPU set
if c.RunParams.Cpuset > 0 {
args = append(args, "--cpuset", strconv.Itoa(c.RunParams.Cpuset))
}
// CPU shares
if c.RunParams.CpuShares > 0 {
args = append(args, "--cpu-shares", strconv.Itoa(c.RunParams.CpuShares))
}
// Device
for _, device := range c.RunParams.Device() {
args = append(args, "--device", device)
}
// Dns
for _, dns := range c.RunParams.Dns() {
args = append(args, "--dns", dns)
}
// Entrypoint
if len(c.RunParams.Entrypoint()) > 0 {
args = append(args, "--entrypoint", c.RunParams.Entrypoint())
}
// Env
for _, env := range c.RunParams.Env() {
args = append(args, "--env", env)
}
// Env file
for _, envFile := range c.RunParams.EnvFile() {
args = append(args, "--env-file", envFile)
}
// Expose
for _, expose := range c.RunParams.Expose() {
args = append(args, "--expose", expose)
}
// Host
if len(c.RunParams.Hostname()) > 0 {
args = append(args, "--hostname", c.RunParams.Hostname())
}
// Interactive
if c.RunParams.Interactive {
args = append(args, "--interactive")
}
// Label
for _, label := range c.RunParams.Label() {
args = append(args, "--label", label)
}
// LabelFile
for _, labelFile := range c.RunParams.LabelFile() {
args = append(args, "--label-file", labelFile)
}
// Link
for _, link := range c.RunParams.Link() {
if ignoreMissing == "all" || ignoreMissing == "link" {
// Omit non-running targets
target := container{RawName: strings.Split(link, ":")[0]}
if !target.Running() {
continue
}
}
args = append(args, "--link", link)
}
// LogDriver
if len(c.RunParams.LogDriver()) > 0 {
args = append(args, "--log-driver", c.RunParams.LogDriver())
}
// LogOpt
for _, opt := range c.RunParams.LogOpt() {
args = append(args, "--log-opt", opt)
}
// LxcConf
for _, lxcConf := range c.RunParams.LxcConf() {
args = append(args, "--lxc-conf", lxcConf)
}
// Mac address
if len(c.RunParams.MacAddress()) > 0 {
args = append(args, "--mac-address", c.RunParams.MacAddress())
}
// Memory
if len(c.RunParams.Memory()) > 0 {
args = append(args, "--memory", c.RunParams.Memory())
}
// MemorySwap
if len(c.RunParams.MemorySwap()) > 0 {
args = append(args, "--memory-swap", c.RunParams.MemorySwap())
}
// Net
if c.RunParams.Net() != "bridge" {
skip := false
name := c.netContainer()
if name != "" && (ignoreMissing == "all" || ignoreMissing == "net") {
target := container{RawName: name}
if !target.Running() {
skip = true
}
}
if !skip {
args = append(args, "--net", c.RunParams.Net())
}
}
// OomKillDisable
if c.RunParams.OomKillDisable {
args = append(args, "--oom-kill-disable")
}
// PID
if len(c.RunParams.Pid()) > 0 {
args = append(args, "--pid", c.RunParams.Pid())
}
// Privileged
if c.RunParams.Privileged {
args = append(args, "--privileged")
}
// Publish
for _, port := range c.RunParams.Publish() {
args = append(args, "--publish", port)
}
// PublishAll
if c.RunParams.PublishAll {
args = append(args, "--publish-all")
}
// ReadOnly
if c.RunParams.ReadOnly {
args = append(args, "--read-only")
}
// Restart
if len(c.RunParams.Restart()) > 0 {
args = append(args, "--restart", c.RunParams.Restart())
}
// Rm
if c.RunParams.Rm {
args = append(args, "--rm")
}
// SecurityOpt
for _, securityOpt := range c.RunParams.SecurityOpt() {
args = append(args, "--security-opt", securityOpt)
}
// SigProxy
if c.RunParams.SigProxy.Defined && !c.RunParams.SigProxy.Value {
args = append(args, "--sig-proxy=false")
}
// Tty
if c.RunParams.Tty {
args = append(args, "--tty")
}
// Ulimit
for _, ulimit := range c.RunParams.Ulimit() {
args = append(args, "--ulimit", ulimit)
}
// User
if len(c.RunParams.User()) > 0 {
args = append(args, "--user", c.RunParams.User())
}
// Uts
if len(c.RunParams.Uts()) > 0 {
args = append(args, "--uts", c.RunParams.Uts())
}
// Volumes
for _, volume := range c.RunParams.Volume(configPath) {
args = append(args, "--volume", volume)
}
// VolumesFrom
for _, volumesFrom := range c.RunParams.VolumesFrom() {
if ignoreMissing == "all" || ignoreMissing == "volumesFrom" {
// Omit non-existing targets
target := container{RawName: strings.Split(volumesFrom, ":")[0]}
if !target.Exists() {
continue
}
}
args = append(args, "--volumes-from", volumesFrom)
}
// Workdir
if len(c.RunParams.Workdir()) > 0 {
args = append(args, "--workdir", c.RunParams.Workdir())
}
// Name
args = append(args, "--name", c.Name())
// Image
args = append(args, c.Image())
// Command
args = append(args, c.RunParams.Cmd()...)
return args
}
// Start container
func (c *container) Start() {
if c.Exists() {
if !c.Running() {
executeHook(c.Hooks().PreStart())
fmt.Printf("Starting container %s ... ", c.Name())
args := []string{"start"}
if c.StartParams.Attach {
args = append(args, "--attach")
}
if c.StartParams.Interactive {
args = append(args, "--interactive")
}
args = append(args, c.Name())
executeCommand("docker", args)
executeHook(c.Hooks().PostStart())
}
} else {
print.Errorf("Container %s does not exist.\n", c.Name())
}
}
// Kill container
func (c *container) Kill() {
if c.Running() {
executeHook(c.Hooks().PreStop())
fmt.Printf("Killing container %s ... ", c.Name())
args := []string{"kill", c.Name()}
executeCommand("docker", args)
executeHook(c.Hooks().PostStop())
}
}
// Stop container
func (c *container) Stop() {
if c.Running() {
executeHook(c.Hooks().PreStop())
fmt.Printf("Stopping container %s ... ", c.Name())
args := []string{"stop", c.Name()}
executeCommand("docker", args)
executeHook(c.Hooks().PostStop())
}
}
// Pause container
func (c *container) Pause() {
if c.Running() {
if c.Paused() {
print.Noticef("Container %s is already paused.\n", c.Name())
} else {
fmt.Printf("Pausing container %s ... ", c.Name())
args := []string{"pause", c.Name()}
executeCommand("docker", args)
}
} else {
print.Noticef("Container %s is not running.\n", c.Name())
}
}
// Unpause container
func (c *container) Unpause() {
if c.Paused() {
fmt.Printf("Unpausing container %s ... ", c.Name())
args := []string{"unpause", c.Name()}
executeCommand("docker", args)
}
}
// Remove container
func (c *container) Rm(force bool) {
if c.Exists() {
containerIsRunning := c.Running()
if !force && containerIsRunning {
print.Errorf("Container %s is running and cannot be removed. Use --force to remove anyway.\n", c.Name())
} else {
args := []string{"rm"}
if force && containerIsRunning {
executeHook(c.Hooks().PreStop())
args = append(args, "--force")
}
if c.RmParams.Volumes {
fmt.Printf("Removing container %s and its volumes ... ", c.Name())
args = append(args, "--volumes")
} else {
fmt.Printf("Removing container %s ... ", c.Name())
}
args = append(args, c.Name())
executeCommand("docker", args)
if force && containerIsRunning {
executeHook(c.Hooks().PostStop())
}
c.id = ""
}
}
}
// Dump container logs
func (c *container) Logs(follow bool, since string, tail string) (stdout, stderr io.Reader) {
if c.Exists() {
args := []string{"logs"}
if follow {
args = append(args, "-f")
}
if len(since) > 0 {
args = append(args, "--since", since)
}
if len(tail) > 0 && tail != "all" {
args = append(args, "--tail", tail)
}
// always include timestamps for ordering, we'll just strip
// them if the user doesn't want to see them
args = append(args, "-t")
args = append(args, c.Id())
stdout, stderr := executeCommandBackground("docker", args)
return stdout, stderr
} else {
return nil, nil
}
}
// Push container
func (c *container) Push() {
if len(c.Image()) > 0 {
fmt.Printf("Pushing image %s ... ", c.Image())
args := []string{"push", c.Image()}
executeCommand("docker", args)
} else {
print.Noticef("Skipping %s as it does not have an image name.\n", c.Name())
}
}
func (c *container) Hooks() Hooks {
return &c.hooks
}
// Pull image for container
func (c *container) PullImage() {
fmt.Printf("Pulling image %s ... ", c.Image())
args := []string{"pull", c.Image()}
executeCommand("docker", args)
}
// Build image for container
func (c *container) buildImage(nocache bool) {
fmt.Printf("Building image %s ... ", c.Image())
args := []string{"build"}
if nocache {
args = append(args, "--no-cache")
}
args = append(args, "--rm", "--tag="+c.Image(), c.Dockerfile())
executeCommand("docker", args)
}
// Return the image id of a tag, or an empty string if it doesn't exist
func imageIdFromTag(tag string) string {
args := []string{"inspect", "--format={{.Id}}", tag}
output, err := commandOutput("docker", args)
if err != nil {
return ""
}
return string(output)
}
// Attempt to parse the value referenced by the go template
// for the `docker inspect` as a boolean, fallbacking to
// false on error
func inspectBool(container string, format string) bool {
output := inspectString(container, format)
flag, _ := strconv.ParseBool(output)
return flag
}
// Returns the value referenced by the go template for
// the `docker inspect` as a string, fallbacking to
// an empty string on error
func inspectString(container string, format string) string {
args := []string{"inspect", "--format=" + format, container}
output, err := commandOutput("docker", args)
if err != nil {
return ""
}
return output
}