forked from michaelsauter/crane
/
container.go
380 lines (358 loc) · 10.6 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 main
import (
"github.com/michaelsauter/crane/print"
"fmt"
"os"
"path"
"regexp"
"strconv"
"strings"
"text/tabwriter"
)
type Container struct {
Id string
Name string `json:"name" yaml:"name"`
Dockerfile string `json:"dockerfile" yaml:"dockerfile"`
Image string `json:"image" yaml:"image"`
Manual bool `json:"manual" yaml:"manual"`
Run RunParameters
}
type RunParameters struct {
Cidfile string `json:"cidfile" yaml:"cidfile"`
CpuShares int `json:"cpu-shares" yaml:"cpu-shares"`
Detach bool `json:"detach" yaml:"detach"`
Dns []string `json:"dns" yaml:"dns"`
Entrypoint string `json:"entrypoint" yaml:"entrypoint"`
Env []string `json:"env" yaml:"env"`
Expose []string `json:"expose" yaml:"expose"`
Host string `json:"host" yaml:"host"`
Interactive bool `json:"interactive" yaml:"interactive"`
Link []string `json:"link" yaml:"link"`
LxcConf []string `json:"lxc-conf" yaml:"lxc-conf"`
MappedVolumesFrom []string `json:"mapped-volumes-from" yaml:"mapped-volumes-from"`
Memory string `json:"memory" yaml:"memory"`
Privileged bool `json:"privileged" yaml:"privileged"`
Publish []string `json:"publish" yaml:"publish"`
PublishAll bool `json:"publish-all" yaml:"publish-all"`
Rm bool `json:"rm" yaml:"rm"`
Tty bool `json:"tty" yaml:"tty"`
User string `json:"user" yaml:"user"`
Volume []string `json:"volume" yaml:"volume"`
VolumesFrom []string `json:"volumes-from" yaml:"volumes-from"`
Workdir string `json:"workdir" yaml:"workdir"`
Command interface{} `json:"cmd" yaml:"cmd"`
}
func (container *Container) getId() (id string, err error) {
if len(container.Id) > 0 {
id = container.Id
} else {
// Inspect container, extracting the Id.
// This will return gibberish if no container is found.
args := []string{"inspect", "--format={{.Id}}|{{.ID}}", container.Name}
output, outErr := commandOutput("docker", args)
if err == nil {
ids := strings.Split(output, "|")
for _, possible_id := range ids {
if possible_id != "<no value>" {
id = possible_id
container.Id = possible_id
return
}
}
} else {
err = outErr
}
}
return
}
func (container *Container) exists() bool {
// `ps -a` returns all existant containers
id, err := container.getId()
if err != nil || len(id) == 0 {
return false
}
dockerCmd := []string{"docker", "ps", "--quiet", "--all", "--no-trunc"}
grepCmd := []string{"grep", "-wF", id}
output, err := pipedCommandOutput(dockerCmd, grepCmd)
if err != nil {
return false
}
result := string(output)
if len(result) > 0 {
return true
} else {
return false
}
}
func (container *Container) running() bool {
// `ps` returns all running containers
id, err := container.getId()
if err != nil || len(id) == 0 {
return false
}
dockerCmd := []string{"docker", "ps", "--quiet", "--no-trunc"}
grepCmd := []string{"grep", "-wF", id}
output, err := pipedCommandOutput(dockerCmd, grepCmd)
if err != nil {
return false
}
result := string(output)
if len(result) > 0 {
return true
} else {
return false
}
}
func (container *Container) imageExists() bool {
dockerCmd := []string{"docker", "images", "--no-trunc"}
grepCmd := []string{"grep", "-wF", container.Image}
output, err := pipedCommandOutput(dockerCmd, grepCmd)
if err != nil {
return false
}
result := string(output)
if len(result) > 0 {
return true
} else {
return false
}
}
func (container *Container) status(w *tabwriter.Writer) {
args := []string{"inspect", "--format={{.State.Running}}\t{{.Id}}\t{{if .NetworkSettings.IPAddress}}{{.NetworkSettings.IPAddress}}{{else}}-{{end}}\t{{range $k,$v := $.NetworkSettings.Ports}}{{$k}},{{end}}", container.Name}
output, err := commandOutput("docker", args)
if err != nil {
fmt.Fprintf(w, "%s\tError:%v\t%v\n", container.Name, err, output)
return
}
fmt.Fprintf(w, "%s\t%s\n", container.Name, output)
}
// Pull image for container
func (container *Container) pullImage() {
fmt.Printf("Pulling image %s ... ", container.Image)
args := []string{"pull", container.Image}
executeCommand("docker", args)
}
// Build image for container
func (container *Container) buildImage() {
fmt.Printf("Building image %s ... ", container.Image)
args := []string{"build", "--rm", "--tag=" + container.Image, os.ExpandEnv(container.Dockerfile)}
executeCommand("docker", args)
}
func (container Container) provision(force bool) {
if force || !container.imageExists() {
if len(container.Dockerfile) > 0 {
container.buildImage()
} else {
container.pullImage()
}
} else {
print.Notice("Image %s does already exist. Use --force to recreate.\n", container.Image)
}
}
// Run or start container
func (container Container) runOrStart() {
if container.exists() {
container.start()
} else {
container.run()
}
}
// Run container
func (container Container) run() {
if !isManualTargetting() && container.Manual {
return
}
if container.exists() {
print.Notice("Container %s does already exist. Use --force to recreate.\n", container.Name)
if !container.running() {
container.start()
}
} else {
fmt.Printf("Running container %s ... ", container.Name)
// Assemble command arguments
args := []string{"run"}
// Cidfile
if len(container.Run.Cidfile) > 0 {
args = append(args, "--cidfile", os.ExpandEnv(container.Run.Cidfile))
}
// CPU shares
if container.Run.CpuShares > 0 {
args = append(args, "--cpu-shares", os.ExpandEnv(strconv.Itoa(container.Run.CpuShares)))
}
// Detach
if container.Run.Detach {
args = append(args, "--detach")
}
// Dns
for _, dns := range container.Run.Dns {
args = append(args, "--dns", os.ExpandEnv(dns))
}
// Entrypoint
if len(container.Run.Entrypoint) > 0 {
args = append(args, "--entrypoint", os.ExpandEnv(container.Run.Entrypoint))
}
// Env
for _, env := range container.Run.Env {
args = append(args, "--env", os.ExpandEnv(env))
}
// Expose
for _, expose := range container.Run.Expose {
args = append(args, "--expose", os.ExpandEnv(expose))
}
// Host
if len(container.Run.Host) > 0 {
args = append(args, "--hostname", os.ExpandEnv(container.Run.Host))
}
// Interactive
if container.Run.Interactive {
args = append(args, "--interactive")
}
// Link
for _, link := range container.Run.Link {
args = append(args, "--link", link)
}
// LxcConf
for _, lxcConf := range container.Run.LxcConf {
args = append(args, "--lxc-conf", os.ExpandEnv(lxcConf))
}
// MappedVolumesFrom
for _, mappedVolumesFrom := range container.Run.MappedVolumesFrom {
mappedVolumesFrom = os.ExpandEnv(mappedVolumesFrom)
x := strings.Split(mappedVolumesFrom, ":")
from, volume, dest := x[0], x[1], x[2]
src_volume_dir := getSourceForVolume(from, volume)
vol_map := strings.Join([]string{src_volume_dir, dest}, ":")
args = append(args, "--volume", vol_map)
}
// Memory
if len(container.Run.Memory) > 0 {
args = append(args, "--memory", os.ExpandEnv(container.Run.Memory))
}
// Privileged
if container.Run.Privileged {
args = append(args, "--privileged")
}
// Publish
for _, port := range container.Run.Publish {
args = append(args, "--publish", os.ExpandEnv(port))
}
// PublishAll
if container.Run.PublishAll {
args = append(args, "--publish-all")
}
// Rm
if container.Run.Rm {
args = append(args, "--rm")
}
// Tty
if container.Run.Tty {
args = append(args, "--tty")
}
// User
if len(container.Run.User) > 0 {
args = append(args, "--user", os.ExpandEnv(container.Run.User))
}
// Volumes
for _, volume := range container.Run.Volume {
paths := strings.Split(volume, ":")
if !path.IsAbs(paths[0]) {
cwd, _ := os.Getwd()
paths[0] = cwd + "/" + paths[0]
}
args = append(args, "--volume", os.ExpandEnv(strings.Join(paths, ":")))
}
// VolumesFrom
for _, volumeFrom := range container.Run.VolumesFrom {
args = append(args, "--volumes-from", os.ExpandEnv(volumeFrom))
}
// Workdir
if len(container.Run.Workdir) > 0 {
args = append(args, "--workdir", os.ExpandEnv(container.Run.Workdir))
}
// Name
args = append(args, "--name", container.Name)
// Image
args = append(args, container.Image)
// Command
if container.Run.Command != nil {
switch cmd := container.Run.Command.(type) {
case string:
if len(cmd) > 0 {
args = append(args, cmd)
}
case []interface{}:
cmds := make([]string, len(cmd))
for i, v := range cmd {
cmds[i] = v.(string)
}
args = append(args, cmds...)
default:
print.Error("cmd is of unknown type!")
}
}
// Execute command
executeCommand("docker", args)
}
}
// Start container
func (container Container) start() {
if !isManualTargetting() && container.Manual {
return
}
if container.exists() {
if !container.running() {
fmt.Printf("Starting container %s ... ", container.Name)
args := []string{"start", container.Name}
executeCommand("docker", args)
}
} else {
print.Error("Container %s does not exist.\n", container.Name)
}
}
// Kill container
func (container Container) kill() {
if container.running() {
fmt.Printf("Killing container %s ... ", container.Name)
args := []string{"kill", container.Name}
executeCommand("docker", args)
}
}
// Stop container
func (container Container) stop() {
if container.running() {
fmt.Printf("Stopping container %s ... ", container.Name)
args := []string{"stop", container.Name}
executeCommand("docker", args)
}
}
// Remove container
func (container Container) rm() {
if container.exists() {
if container.running() {
print.Error("Container %s is running and cannot be removed.\n", container.Name)
} else {
fmt.Printf("Removing container %s ... ", container.Name)
args := []string{"rm", container.Name}
executeCommand("docker", args)
}
}
}
func getSourceForVolume(from, volume string) string {
args := []string{"inspect","--format={{.Volumes}}", from}
output, err := commandOutput("docker", args)
if err != nil {
panic(fmt.Sprintf("Cannot getSourceForVolume %v %v", from, volume))
}
// output looks like:
// map[/scirev-admin:/home/core/scirev-admin /var/log/nginx/pricingconsole:/home/core/pc_logs /var/log/pricingconsole:/home/core/pc_logs]
inner_part_regex := regexp.MustCompile("map[[](.*)[]]$")
inner := inner_part_regex.FindStringSubmatch(output)[1]
for _, vol_map := range strings.Split(inner, " ") {
x := strings.Split(vol_map, ":")
container_path, host_path := x[0], x[1]
if container_path == volume {
return host_path
}
}
panic(fmt.Sprintf("getSourceForVolume cannot find volume %v for container %v", volume, from))
}