/
container.go
1478 lines (1346 loc) · 40.8 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
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package crane
import (
"bufio"
"encoding/json"
"fmt"
"github.com/flynn/go-shlex"
"io"
"os"
"path"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
)
type Container interface {
ContainerInfo
Exists() bool
Running() bool
Paused() bool
Status() [][]string
Provision(nocache bool)
PullImage()
Create(cmds []string)
Run(cmds []string)
Start()
Kill()
Stop()
Pause()
Unpause()
Exec(cmds []string)
Rm(force bool)
Logs(follow bool, since string, tail string) (sources []LogSource)
Push()
SetCommandsOutput(stdout, stderr io.Writer)
CommandsOut() io.Writer
CommandsErr() io.Writer
}
type ContainerInfo interface {
Name() string
PrefixedName() string
ActualName(bool) string
Image() string
ID() string
Dependencies() *Dependencies
BuildParams() BuildParameters
RunParams() RunParameters
RmParams() RmParameters
StartParams() StartParameters
ExecParams() ExecParameters
Hooks() Hooks
}
type container struct {
id string
RawName string
RawImage string `json:"image" yaml:"image"`
RawRequires []string `json:"requires" yaml:"requires"`
RawBuild BuildParameters `json:"build" yaml:"build"`
RawRun RunParameters `json:"run" yaml:"run"`
RawRm RmParameters `json:"rm" yaml:"rm"`
RawStart StartParameters `json:"start" yaml:"start"`
RawExec ExecParameters `json:"exec" yaml:"exec"`
hooks hooks
stdout io.Writer
stderr io.Writer
}
type BuildParameters struct {
RawContext string `json:"context" yaml:"context"`
RawFile string `json:"file" yaml:"file"`
RawBuildArgs interface{} `json:"build-arg" yaml:"build-arg"`
}
type RunParameters struct {
RawAddHost []string `json:"add-host" yaml:"add-host"`
BlkioWeight int `json:"blkio-weight" yaml:"blkio-weight"`
RawBlkioWeightDevice []string `json:"blkio-weight-device" yaml:"blkio-weight-device"`
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"`
RawDetachKeys string `json:"detach-keys" yaml:"detach-keys"`
RawDevice []string `json:"device" yaml:"device"`
RawDeviceReadBps []string `json:"device-read-bps" yaml:"device-read-bps"`
RawDeviceReadIops []string `json:"device-read-iops" yaml:"device-read-iops"`
RawDeviceWriteBps []string `json:"device-write-bps" yaml:"device-write-bps"`
RawDeviceWriteIops []string `json:"device-rewritead-iops" yaml:"device-write-iops"`
RawDNS []string `json:"dns" yaml:"dns"`
RawDNSOpt []string `json:"dns-opt" yaml:"dns-opt"`
RawDNSSearch []string `json:"dns-search" yaml:"dns-search"`
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"`
RawGroupAdd []string `json:"group-add" yaml:"group-add"`
RawHostname string `json:"hostname" yaml:"hostname"`
Interactive bool `json:"interactive" yaml:"interactive"`
RawIp string `json:"ip" yaml:"ip"`
RawIp6 string `json:"ip6" yaml:"ip6"`
RawIPC string `json:"ipc" yaml:"ipc"`
RawIsolation string `json:"isolation" yaml:"isolation"`
RawKernelMemory string `json:"kernel-memory" yaml:"kernel-memory"`
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"`
RawMemoryReservation string `json:"memory-reservation" yaml:"memory-reservation"`
RawMemorySwap string `json:"memory-swap" yaml:"memory-swap"`
MemorySwappiness OptInt `json:"memory-swappiness" yaml:"memory-swappiness"`
RawNet string `json:"net" yaml:"net"`
RawNetAlias []string `json:"net-alias" yaml:"net-alias"`
OomKillDisable bool `json:"oom-kill-disable" yaml:"oom-kill-disable"`
RawOomScoreAdj string `json:"oom-score-adj" yaml:"oom-score-adj"`
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"`
RawShmSize string `json:"shm-size" yaml:"shm-size"`
SigProxy OptBool `json:"sig-proxy" yaml:"sig-proxy"`
RawStopSignal string `json:"stop-signal" yaml:"stop-signal"`
RawTmpfs []string `json:"tmpfs" yaml:"tmpfs"`
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"`
RawVolumeDriver string `json:"volume-driver" yaml:"volume-driver"`
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"`
RawDetachKeys string `json:"detach-keys" yaml:"detach-keys"`
Interactive bool `json:"interactive" yaml:"interactive"`
}
type ExecParameters struct {
Detach bool `json:"detach" yaml:"detach"`
RawDetachKeys string `json:"detach-keys" yaml:"detach-keys"`
Interactive bool `json:"interactive" yaml:"interactive"`
Privileged bool `json:"privileged" yaml:"privileged"`
Tty bool `json:"tty" yaml:"tty"`
RawUser string `json:"user" yaml:"user"`
}
type OptInt struct {
Defined bool
Value int
}
type OptBool struct {
Defined bool
Value bool
}
type LogSource struct {
Stdout io.Reader
Stderr io.Reader
Name string
}
func (o *OptInt) UnmarshalYAML(unmarshal func(interface{}) error) error {
if err := unmarshal(&o.Value); err != nil {
return err
}
o.Defined = true
return nil
}
func (o *OptInt) UnmarshalJSON(b []byte) (err error) {
if err := json.Unmarshal(b, &o.Value); err != nil {
return err
}
o.Defined = true
return
}
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 (o OptBool) Truthy() bool {
return !o.Defined || o.Value
}
func (o OptBool) Falsy() bool {
return o.Defined && !o.Value
}
func (c *container) BuildParams() BuildParameters {
return c.RawBuild
}
func (c *container) RunParams() RunParameters {
return c.RawRun
}
func (c *container) RmParams() RmParameters {
return c.RawRm
}
func (c *container) StartParams() StartParameters {
return c.RawStart
}
func (c *container) ExecParams() ExecParameters {
return c.RawExec
}
func (c *container) Dependencies() *Dependencies {
dependencies := &Dependencies{}
for _, required := range c.Requires() {
if includes(allowed, required) && !dependencies.includes(required) {
dependencies.All = append(dependencies.All, required)
dependencies.Requires = append(dependencies.Requires, required)
}
}
if c.RunParams().Net() == "bridge" {
// links are strict dependencies only on bridge networks
for _, link := range c.RunParams().Link() {
linkName := strings.Split(link, ":")[0]
if includes(allowed, linkName) && !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 includes(allowed, volumesFromName) && !dependencies.includes(volumesFromName) {
dependencies.All = append(dependencies.All, volumesFromName)
dependencies.VolumesFrom = append(dependencies.VolumesFrom, volumesFromName)
}
}
if net := containerReference(c.RunParams().Net()); net != "" {
if includes(allowed, net) && !dependencies.includes(net) {
dependencies.Net = net
dependencies.All = append(dependencies.All, net)
}
}
if ipc := containerReference(c.RunParams().IPC()); ipc != "" {
if includes(allowed, ipc) && !dependencies.includes(ipc) {
dependencies.IPC = ipc
dependencies.All = append(dependencies.All, ipc)
}
}
return dependencies
}
func (c *container) Name() string {
return expandEnv(c.RawName)
}
func (c *container) ActualName(adHoc bool) string {
if adHoc {
return c.PrefixedName() + "-" + cfg.UniqueID()
}
return c.PrefixedName()
}
func (c *container) Image() string {
image := expandEnv(c.RawImage)
// Return if no global tag given or image is a digest
if len(cfg.Tag()) == 0 || strings.Contains(image, "@") {
return image
}
// Replace image tag with global tag
startOfTag := strings.LastIndex(image, ":")
if startOfTag != -1 {
// Check that the colon does not refer to a port.
// Tags must not contain slashes.
tagPart := image[startOfTag+1:]
slashPosition := strings.LastIndex(tagPart, "/")
if slashPosition == -1 {
image = image[:startOfTag]
}
}
return image + ":" + cfg.Tag()
}
func (c *container) Requires() []string {
var requires []string
for _, rawRequired := range c.RawRequires {
requires = append(requires, expandEnv(rawRequired))
}
return requires
}
func (b BuildParameters) Context() string {
return expandEnv(b.RawContext)
}
func (b BuildParameters) File() string {
return expandEnv(b.RawFile)
}
func (b BuildParameters) BuildArgs() []string {
return sliceOrMap2ExpandedSlice(b.RawBuildArgs)
}
func (r RunParameters) AddHost() []string {
var addHost []string
for _, rawAddHost := range r.RawAddHost {
addHost = append(addHost, expandEnv(rawAddHost))
}
return addHost
}
func (r RunParameters) BlkioWeightDevice() []string {
var blkioWeightDevice []string
for _, rawBlkioWeightDevice := range r.RawBlkioWeightDevice {
blkioWeightDevice = append(blkioWeightDevice, expandEnv(rawBlkioWeightDevice))
}
return blkioWeightDevice
}
func (r RunParameters) CapAdd() []string {
var capAdd []string
for _, rawCapAdd := range r.RawCapAdd {
capAdd = append(capAdd, expandEnv(rawCapAdd))
}
return capAdd
}
func (r RunParameters) CapDrop() []string {
var capDrop []string
for _, rawCapDrop := range r.RawCapDrop {
capDrop = append(capDrop, expandEnv(rawCapDrop))
}
return capDrop
}
func (r RunParameters) CgroupParent() string {
return expandEnv(r.RawCgroupParent)
}
func (r RunParameters) Cidfile() string {
return expandEnv(r.RawCidfile)
}
func (r RunParameters) DetachKeys() string {
return expandEnv(r.RawDetachKeys)
}
func (r RunParameters) Device() []string {
var device []string
for _, rawDevice := range r.RawDevice {
device = append(device, expandEnv(rawDevice))
}
return device
}
func (r RunParameters) DeviceReadBps() []string {
var deviceReadBps []string
for _, rawDeviceReadBps := range r.RawDeviceReadBps {
deviceReadBps = append(deviceReadBps, expandEnv(rawDeviceReadBps))
}
return deviceReadBps
}
func (r RunParameters) DeviceReadIops() []string {
var deviceReadIops []string
for _, rawDeviceReadIops := range r.RawDeviceReadIops {
deviceReadIops = append(deviceReadIops, expandEnv(rawDeviceReadIops))
}
return deviceReadIops
}
func (r RunParameters) DeviceWriteBps() []string {
var deviceWriteBps []string
for _, rawDeviceWriteBps := range r.RawDeviceWriteBps {
deviceWriteBps = append(deviceWriteBps, expandEnv(rawDeviceWriteBps))
}
return deviceWriteBps
}
func (r RunParameters) DeviceWriteIops() []string {
var deviceWriteIops []string
for _, rawDeviceWriteIops := range r.RawDeviceWriteIops {
deviceWriteIops = append(deviceWriteIops, expandEnv(rawDeviceWriteIops))
}
return deviceWriteIops
}
func (r RunParameters) DNS() []string {
var dns []string
for _, rawDNS := range r.RawDNS {
dns = append(dns, expandEnv(rawDNS))
}
return dns
}
func (r RunParameters) DNSOpt() []string {
var dnsOpt []string
for _, rawDNSOpt := range r.RawDNSOpt {
dnsOpt = append(dnsOpt, expandEnv(rawDNSOpt))
}
return dnsOpt
}
func (r RunParameters) DNSSearch() []string {
var dnsSearch []string
for _, rawDNSSearch := range r.RawDNSSearch {
dnsSearch = append(dnsSearch, expandEnv(rawDNSSearch))
}
return dnsSearch
}
func (r RunParameters) Entrypoint() string {
return expandEnv(r.RawEntrypoint)
}
func (r RunParameters) Env() []string {
return sliceOrMap2ExpandedSlice(r.RawEnv)
}
func (r RunParameters) EnvFile() []string {
var envFile []string
for _, rawEnvFile := range r.RawEnvFile {
envFile = append(envFile, expandEnv(rawEnvFile))
}
return envFile
}
func (r RunParameters) Expose() []string {
var expose []string
for _, rawExpose := range r.RawExpose {
expose = append(expose, expandEnv(rawExpose))
}
return expose
}
func (r RunParameters) GroupAdd() []string {
var groupAdd []string
for _, rawGroupAdd := range r.RawGroupAdd {
groupAdd = append(groupAdd, expandEnv(rawGroupAdd))
}
return groupAdd
}
func (r RunParameters) Hostname() string {
return expandEnv(r.RawHostname)
}
func (r RunParameters) Ip() string {
return expandEnv(r.RawIp)
}
func (r RunParameters) Ip6() string {
return expandEnv(r.RawIp6)
}
func (r RunParameters) IPC() string {
return expandEnv(r.RawIPC)
}
func (r RunParameters) Isolation() string {
return expandEnv(r.RawIsolation)
}
func (r RunParameters) KernelMemory() string {
return expandEnv(r.RawKernelMemory)
}
func (r RunParameters) Label() []string {
return sliceOrMap2ExpandedSlice(r.RawLabel)
}
func (r RunParameters) LabelFile() []string {
var labelFile []string
for _, rawLabelFile := range r.RawLabelFile {
labelFile = append(labelFile, expandEnv(rawLabelFile))
}
return labelFile
}
func (r RunParameters) Link() []string {
var link []string
for _, rawLink := range r.RawLink {
link = append(link, expandEnv(rawLink))
}
return link
}
func (r RunParameters) LogDriver() string {
return expandEnv(r.RawLogDriver)
}
func (r RunParameters) LogOpt() []string {
var opt []string
for _, rawOpt := range r.RawLogOpt {
opt = append(opt, expandEnv(rawOpt))
}
return opt
}
func (r RunParameters) LxcConf() []string {
var lxcConf []string
for _, rawLxcConf := range r.RawLxcConf {
lxcConf = append(lxcConf, expandEnv(rawLxcConf))
}
return lxcConf
}
func (r RunParameters) MacAddress() string {
return expandEnv(r.RawMacAddress)
}
func (r RunParameters) Memory() string {
return expandEnv(r.RawMemory)
}
func (r RunParameters) MemoryReservation() string {
return expandEnv(r.RawMemoryReservation)
}
func (r RunParameters) MemorySwap() string {
return expandEnv(r.RawMemorySwap)
}
func (r RunParameters) Net() string {
// Default to bridge
if len(r.RawNet) == 0 {
return "bridge"
}
return expandEnv(r.RawNet)
}
func (r RunParameters) ActualNet() string {
netParam := r.Net()
if netParam == "bridge" {
return "bridge"
}
netContainer := containerReference(netParam)
if len(netContainer) > 0 {
if includes(allowed, netContainer) {
return "container:" + cfg.Container(netContainer).ActualName(false)
}
} else {
if includes(cfg.NetworkNames(), netParam) {
return cfg.Network(netParam).ActualName()
}
}
return netParam
}
func (r RunParameters) NetAlias() []string {
var netAlias []string
for _, rawNetAlias := range r.RawNetAlias {
netAlias = append(netAlias, expandEnv(rawNetAlias))
}
return netAlias
}
func (r RunParameters) OomScoreAdj() string {
return expandEnv(r.RawOomScoreAdj)
}
func (r RunParameters) Pid() string {
return expandEnv(r.RawPid)
}
func (r RunParameters) Publish() []string {
var publish []string
for _, rawPublish := range r.RawPublish {
publish = append(publish, expandEnv(rawPublish))
}
return publish
}
func (r RunParameters) Restart() string {
return expandEnv(r.RawRestart)
}
func (r RunParameters) SecurityOpt() []string {
var securityOpt []string
for _, rawSecurityOpt := range r.RawSecurityOpt {
securityOpt = append(securityOpt, expandEnv(rawSecurityOpt))
}
return securityOpt
}
func (r RunParameters) ShmSize() string {
return expandEnv(r.RawShmSize)
}
func (r RunParameters) StopSignal() string {
return expandEnv(r.RawStopSignal)
}
func (r RunParameters) Tmpfs() []string {
var tmpfs []string
for _, rawTmpfs := range r.RawTmpfs {
tmpfs = append(tmpfs, expandEnv(rawTmpfs))
}
return tmpfs
}
func (r RunParameters) Ulimit() []string {
var ulimit []string
for _, rawUlimit := range r.RawUlimit {
ulimit = append(ulimit, expandEnv(rawUlimit))
}
return ulimit
}
func (r RunParameters) User() string {
return expandEnv(r.RawUser)
}
func (r RunParameters) Uts() string {
return expandEnv(r.RawUts)
}
func (r RunParameters) Volume() []string {
var volumes []string
for _, rawVolume := range r.RawVolume {
volume := expandEnv(rawVolume)
volumes = append(volumes, volume)
}
return volumes
}
func (r RunParameters) VolumeSources() []string {
volumes := r.Volume()
var volumeSources []string
for _, volume := range volumes {
parts := strings.Split(volume, ":")
volumeSources = append(volumeSources, parts[0])
}
return volumeSources
}
func (r RunParameters) ActualVolume() []string {
vols := []string{}
for _, volume := range r.Volume() {
parts := strings.Split(volume, ":")
if includes(cfg.VolumeNames(), parts[0]) {
parts[0] = cfg.Volume(parts[0]).ActualName()
} else if !path.IsAbs(parts[0]) {
parts[0] = cfg.Path() + "/" + parts[0]
}
vols = append(vols, strings.Join(parts, ":"))
}
return vols
}
func (r RunParameters) VolumeDriver() string {
return expandEnv(r.RawVolumeDriver)
}
func (r RunParameters) VolumesFrom() []string {
var volumesFrom []string
for _, rawVolumesFrom := range r.RawVolumesFrom {
volumesFrom = append(volumesFrom, expandEnv(rawVolumesFrom))
}
return volumesFrom
}
func (r RunParameters) Workdir() string {
return 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(expandEnv(rawCmd))
if err != nil {
printErrorf("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] = expandEnv(fmt.Sprintf("%v", v))
}
cmd = append(cmd, cmds...)
default:
panic(StatusError{fmt.Errorf("unknown type: %v", rawCmd), 65})
}
}
return cmd
}
func (s StartParameters) DetachKeys() string {
return expandEnv(s.RawDetachKeys)
}
func (e ExecParameters) DetachKeys() string {
return expandEnv(e.RawDetachKeys)
}
func (e ExecParameters) User() string {
return expandEnv(e.RawUser)
}
func containerID(name string) string {
// `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.
return inspectString(name, "{{if .State}}{{.Id}}{{else}}{{end}}")
}
func (c *container) ID() string {
if len(c.id) == 0 {
c.id = containerID(c.ActualName(false))
}
return c.id
}
func (c *container) Exists() bool {
return c.ID() != ""
}
func (c *container) Status() [][]string {
rows := [][]string{}
if !c.Exists() {
fields := []string{c.ActualName(false), c.Image(), "-", "-", "-", "-", "-"}
rows = append(rows, fields)
} else {
name := c.ActualName(false)
fields := []string{name, c.Image(), "-", "-", "-", "-", "-"}
// When using a `--tag` global flag, c.Image() may not represent an actual image tag.
// Instead we should get an image tag by inspecting "Config.Image".
output := inspectString(name, "{{.Config.Image}}+++{{.Id}}+++{{.Image}}+++{{if .NetworkSettings.IPAddress}}{{.NetworkSettings.IPAddress}}{{else}}-{{end}}+++{{range $k,$v := $.NetworkSettings.Ports}}{{$k}},{{else}}-{{end}}+++{{.State.Running}}")
if output != "" {
copy(fields[1:], strings.Split(output, "+++"))
// We asked for the image id the container was created from
fields[3] = strconv.FormatBool(imageIDFromTag(fields[1]) == fields[3])
}
rows = append(rows, fields)
}
return rows
}
func (c *container) Provision(nocache bool) {
if len(c.BuildParams().Context()) > 0 {
c.buildImage(nocache)
} else {
c.PullImage()
}
}
// Create container
func (c *container) Create(cmds []string) {
adHoc := (len(cmds) > 0)
if !adHoc {
c.Rm(true)
}
fmt.Fprintf(c.CommandsOut(), "Creating container %s ...\n", c.ActualName(adHoc))
args := append([]string{"create"}, c.createArgs(cmds)...)
executeCommand("docker", args, c.CommandsOut(), c.CommandsErr())
}
// Run container, or start it if already existing
func (c *container) Run(cmds []string) {
adHoc := (len(cmds) > 0)
if !adHoc {
c.Rm(true)
}
executeHook(c.Hooks().PreStart(), c.ActualName(adHoc))
fmt.Fprintf(c.CommandsOut(), "Running container %s ...\n", c.ActualName(adHoc))
args := []string{"run"}
// Detach
if !adHoc && c.RunParams().Detach {
args = append(args, "--detach")
}
args = append(args, c.createArgs(cmds)...)
wg := c.executePostStartHook(adHoc)
executeCommand("docker", args, c.CommandsOut(), c.CommandsErr())
wg.Wait()
}
func (c *container) executePostStartHook(adHoc bool) *sync.WaitGroup {
var wg sync.WaitGroup
if len(c.Hooks().PostStart()) > 0 {
cmd, cmdOut, _ := executeCommandBackground("docker", []string{"events", "--filter", "event=start", "--filter", "container=" + c.ActualName(adHoc)})
if cmd != nil {
wg.Add(1)
go func() {
defer func() {
handleRecoveredError(recover())
wg.Done()
}()
r := bufio.NewReader(cmdOut)
_, _, err := r.ReadLine()
cmd.Process.Kill()
if err != nil {
printNoticef("Could not execute post-start hook for %s: %s.", c.ActualName(adHoc), err)
} else {
executeHook(c.Hooks().PostStart(), c.ActualName(adHoc))
}
}()
}
}
return &wg
}
// Returns all the flags to be passed to `docker create`
func (c *container) createArgs(cmds []string) []string {
adHoc := (len(cmds) > 0)
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))
}
// BlkioWeightDevice
for _, blkioWeightDevice := range c.RunParams().BlkioWeightDevice() {
args = append(args, "--blkio-weight-device", blkioWeightDevice)
}
// 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))
}
// DetachKeys
if len(c.RunParams().DetachKeys()) > 0 {
args = append(args, "--detach-keys", c.RunParams().DetachKeys())
}
// Device
for _, device := range c.RunParams().Device() {
args = append(args, "--device", device)
}
// DeviceReadBps
for _, deviceReadBps := range c.RunParams().DeviceReadBps() {
args = append(args, "--device-read-bps", deviceReadBps)
}
// DeviceReadIops
for _, deviceReadIops := range c.RunParams().DeviceReadIops() {
args = append(args, "--device-read-iops", deviceReadIops)
}
// DeviceWriteBps
for _, deviceWriteBps := range c.RunParams().DeviceWriteBps() {
args = append(args, "--device-write-bps", deviceWriteBps)
}
// DeviceWriteIops
for _, deviceWriteIops := range c.RunParams().DeviceWriteIops() {
args = append(args, "--device-write-iops", deviceWriteIops)
}
// DNS
for _, dns := range c.RunParams().DNS() {
args = append(args, "--dns", dns)
}
// DNSOpt
for _, dnsOpt := range c.RunParams().DNSOpt() {
args = append(args, "--dns-opt", dnsOpt)
}
// DNS Search
for _, dnsSearch := range c.RunParams().DNSSearch() {
args = append(args, "--dns-search", dnsSearch)
}
// 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)
}
// GroupAdd
for _, groupAdd := range c.RunParams().GroupAdd() {
args = append(args, "--group-add", groupAdd)
}
// Host
if len(c.RunParams().Hostname()) > 0 {
args = append(args, "--hostname", c.RunParams().Hostname())
}
// Interactive
if c.RunParams().Interactive {
args = append(args, "--interactive")
}
// Ip
if !adHoc {
if len(c.RunParams().Ip()) > 0 {
args = append(args, "--ip", c.RunParams().Ip())
}
}
// Ip6
if !adHoc {
if len(c.RunParams().Ip6()) > 0 {
args = append(args, "--ip6", c.RunParams().Ip6())
}
}
// IPC
if len(c.RunParams().IPC()) > 0 {
ipcContainer := containerReference(c.RunParams().IPC())
if len(ipcContainer) > 0 {
if includes(allowed, ipcContainer) {
args = append(args, "--ipc", "container:"+cfg.Container(ipcContainer).ActualName(false))
}
} else {
args = append(args, "--ipc", c.RunParams().IPC())
}
}
// Isolation
if len(c.RunParams().Isolation()) > 0 {
args = append(args, "--isolation", c.RunParams().Isolation())
}
// KernelMemory
if len(c.RunParams().KernelMemory()) > 0 {
args = append(args, "--kernel-memory", c.RunParams().KernelMemory())
}
// 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() {
linkParts := strings.Split(link, ":")
linkName := linkParts[0]