File: docker_cli_create_test.go

package info (click to toggle)
docker.io 1.11.2~ds1-6
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 23,652 kB
  • ctags: 12,672
  • sloc: sh: 7,238; makefile: 340; ansic: 123; xml: 62
file content (460 lines) | stat: -rw-r--r-- 15,908 bytes parent folder | download | duplicates (2)
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
package main

import (
	"encoding/json"
	"fmt"
	"os"
	"reflect"
	"strings"
	"time"

	"os/exec"

	"io/ioutil"

	"github.com/docker/docker/pkg/integration/checker"
	"github.com/docker/docker/pkg/stringid"
	"github.com/docker/go-connections/nat"
	"gopkg.in/check.v1"
)

// Make sure we can create a simple container with some args
func (s *DockerSuite) TestCreateArgs(c *check.C) {
	// TODO Windows. This requires further investigation for porting to
	// Windows CI. Currently fails.
	if daemonPlatform == "windows" {
		c.Skip("Fails on Windows CI")
	}
	out, _ := dockerCmd(c, "create", "busybox", "command", "arg1", "arg2", "arg with space")

	cleanedContainerID := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "inspect", cleanedContainerID)

	containers := []struct {
		ID      string
		Created time.Time
		Path    string
		Args    []string
		Image   string
	}{}

	err := json.Unmarshal([]byte(out), &containers)
	c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err))
	c.Assert(containers, checker.HasLen, 1)

	cont := containers[0]
	c.Assert(string(cont.Path), checker.Equals, "command", check.Commentf("Unexpected container path. Expected command, received: %s", cont.Path))

	b := false
	expected := []string{"arg1", "arg2", "arg with space"}
	for i, arg := range expected {
		if arg != cont.Args[i] {
			b = true
			break
		}
	}
	if len(cont.Args) != len(expected) || b {
		c.Fatalf("Unexpected args. Expected %v, received: %v", expected, cont.Args)
	}

}

// Make sure we can set hostconfig options too
func (s *DockerSuite) TestCreateHostConfig(c *check.C) {
	out, _ := dockerCmd(c, "create", "-P", "busybox", "echo")

	cleanedContainerID := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "inspect", cleanedContainerID)

	containers := []struct {
		HostConfig *struct {
			PublishAllPorts bool
		}
	}{}

	err := json.Unmarshal([]byte(out), &containers)
	c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err))
	c.Assert(containers, checker.HasLen, 1)

	cont := containers[0]
	c.Assert(cont.HostConfig, check.NotNil, check.Commentf("Expected HostConfig, got none"))
	c.Assert(cont.HostConfig.PublishAllPorts, check.NotNil, check.Commentf("Expected PublishAllPorts, got false"))
}

func (s *DockerSuite) TestCreateWithPortRange(c *check.C) {
	// Windows does not currently support port ranges.
	testRequires(c, DaemonIsLinux)
	out, _ := dockerCmd(c, "create", "-p", "3300-3303:3300-3303/tcp", "busybox", "echo")

	cleanedContainerID := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "inspect", cleanedContainerID)

	containers := []struct {
		HostConfig *struct {
			PortBindings map[nat.Port][]nat.PortBinding
		}
	}{}
	err := json.Unmarshal([]byte(out), &containers)
	c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err))
	c.Assert(containers, checker.HasLen, 1)

	cont := containers[0]

	c.Assert(cont.HostConfig, check.NotNil, check.Commentf("Expected HostConfig, got none"))
	c.Assert(cont.HostConfig.PortBindings, checker.HasLen, 4, check.Commentf("Expected 4 ports bindings, got %d", len(cont.HostConfig.PortBindings)))

	for k, v := range cont.HostConfig.PortBindings {
		c.Assert(v, checker.HasLen, 1, check.Commentf("Expected 1 ports binding, for the port  %s but found %s", k, v))
		c.Assert(k.Port(), checker.Equals, v[0].HostPort, check.Commentf("Expected host port %s to match published port %s", k.Port(), v[0].HostPort))

	}

}

func (s *DockerSuite) TestCreateWithLargePortRange(c *check.C) {
	// Windows does not currently support port ranges.
	testRequires(c, DaemonIsLinux)
	out, _ := dockerCmd(c, "create", "-p", "1-65535:1-65535/tcp", "busybox", "echo")

	cleanedContainerID := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "inspect", cleanedContainerID)

	containers := []struct {
		HostConfig *struct {
			PortBindings map[nat.Port][]nat.PortBinding
		}
	}{}

	err := json.Unmarshal([]byte(out), &containers)
	c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err))
	c.Assert(containers, checker.HasLen, 1)

	cont := containers[0]
	c.Assert(cont.HostConfig, check.NotNil, check.Commentf("Expected HostConfig, got none"))
	c.Assert(cont.HostConfig.PortBindings, checker.HasLen, 65535)

	for k, v := range cont.HostConfig.PortBindings {
		c.Assert(v, checker.HasLen, 1)
		c.Assert(k.Port(), checker.Equals, v[0].HostPort, check.Commentf("Expected host port %s to match published port %s", k.Port(), v[0].HostPort))
	}

}

// "test123" should be printed by docker create + start
func (s *DockerSuite) TestCreateEchoStdout(c *check.C) {
	out, _ := dockerCmd(c, "create", "busybox", "echo", "test123")

	cleanedContainerID := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "start", "-ai", cleanedContainerID)
	c.Assert(out, checker.Equals, "test123\n", check.Commentf("container should've printed 'test123', got %q", out))

}

func (s *DockerSuite) TestCreateVolumesCreated(c *check.C) {
	testRequires(c, SameHostDaemon)
	prefix := "/"
	if daemonPlatform == "windows" {
		prefix = `c:\`
	}

	name := "test_create_volume"
	dockerCmd(c, "create", "--name", name, "-v", prefix+"foo", "busybox")

	dir, err := inspectMountSourceField(name, prefix+"foo")
	c.Assert(err, check.IsNil, check.Commentf("Error getting volume host path: %q", err))

	if _, err := os.Stat(dir); err != nil && os.IsNotExist(err) {
		c.Fatalf("Volume was not created")
	}
	if err != nil {
		c.Fatalf("Error statting volume host path: %q", err)
	}

}

func (s *DockerSuite) TestCreateLabels(c *check.C) {
	name := "test_create_labels"
	expected := map[string]string{"k1": "v1", "k2": "v2"}
	dockerCmd(c, "create", "--name", name, "-l", "k1=v1", "--label", "k2=v2", "busybox")

	actual := make(map[string]string)
	inspectFieldAndMarshall(c, name, "Config.Labels", &actual)

	if !reflect.DeepEqual(expected, actual) {
		c.Fatalf("Expected %s got %s", expected, actual)
	}
}

func (s *DockerSuite) TestCreateLabelFromImage(c *check.C) {
	imageName := "testcreatebuildlabel"
	_, err := buildImage(imageName,
		`FROM busybox
		LABEL k1=v1 k2=v2`,
		true)

	c.Assert(err, check.IsNil)

	name := "test_create_labels_from_image"
	expected := map[string]string{"k2": "x", "k3": "v3", "k1": "v1"}
	dockerCmd(c, "create", "--name", name, "-l", "k2=x", "--label", "k3=v3", imageName)

	actual := make(map[string]string)
	inspectFieldAndMarshall(c, name, "Config.Labels", &actual)

	if !reflect.DeepEqual(expected, actual) {
		c.Fatalf("Expected %s got %s", expected, actual)
	}
}

func (s *DockerSuite) TestCreateHostnameWithNumber(c *check.C) {
	// TODO Windows. Consider enabling this in TP5 timeframe if Windows support
	// is fully hooked up. The hostname is passed through, but only to the
	// environment variable "COMPUTERNAME". It is not hooked up to hostname.exe
	// or returned in ipconfig. Needs platform support in networking.
	testRequires(c, DaemonIsLinux)
	out, _ := dockerCmd(c, "run", "-h", "web.0", "busybox", "hostname")
	c.Assert(strings.TrimSpace(out), checker.Equals, "web.0", check.Commentf("hostname not set, expected `web.0`, got: %s", out))

}

func (s *DockerSuite) TestCreateRM(c *check.C) {
	// Test to make sure we can 'rm' a new container that is in
	// "Created" state, and has ever been run. Test "rm -f" too.

	// create a container
	out, _ := dockerCmd(c, "create", "busybox")
	cID := strings.TrimSpace(out)

	dockerCmd(c, "rm", cID)

	// Now do it again so we can "rm -f" this time
	out, _ = dockerCmd(c, "create", "busybox")

	cID = strings.TrimSpace(out)
	dockerCmd(c, "rm", "-f", cID)
}

func (s *DockerSuite) TestCreateModeIpcContainer(c *check.C) {
	// Uses Linux specific functionality (--ipc)
	testRequires(c, DaemonIsLinux)
	testRequires(c, SameHostDaemon, NotUserNamespace)

	out, _ := dockerCmd(c, "create", "busybox")
	id := strings.TrimSpace(out)

	dockerCmd(c, "create", fmt.Sprintf("--ipc=container:%s", id), "busybox")
}

func (s *DockerSuite) TestCreateByImageID(c *check.C) {
	imageName := "testcreatebyimageid"
	imageID, err := buildImage(imageName,
		`FROM busybox
		MAINTAINER dockerio`,
		true)
	if err != nil {
		c.Fatal(err)
	}
	truncatedImageID := stringid.TruncateID(imageID)

	dockerCmd(c, "create", imageID)
	dockerCmd(c, "create", truncatedImageID)
	dockerCmd(c, "create", fmt.Sprintf("%s:%s", imageName, truncatedImageID))

	// Ensure this fails
	out, exit, _ := dockerCmdWithError("create", fmt.Sprintf("%s:%s", imageName, imageID))
	if exit == 0 {
		c.Fatalf("expected non-zero exit code; received %d", exit)
	}

	if expected := "Error parsing reference"; !strings.Contains(out, expected) {
		c.Fatalf(`Expected %q in output; got: %s`, expected, out)
	}

	out, exit, _ = dockerCmdWithError("create", fmt.Sprintf("%s:%s", "wrongimage", truncatedImageID))
	if exit == 0 {
		c.Fatalf("expected non-zero exit code; received %d", exit)
	}

	if expected := "Unable to find image"; !strings.Contains(out, expected) {
		c.Fatalf(`Expected %q in output; got: %s`, expected, out)
	}
}

func (s *DockerTrustSuite) TestTrustedCreate(c *check.C) {
	repoName := s.setupTrustedImage(c, "trusted-create")

	// Try create
	createCmd := exec.Command(dockerBinary, "create", repoName)
	s.trustedCmd(createCmd)
	out, _, err := runCommandWithOutput(createCmd)
	c.Assert(err, check.IsNil)
	c.Assert(string(out), checker.Contains, "Tagging", check.Commentf("Missing expected output on trusted push:\n%s", out))

	dockerCmd(c, "rmi", repoName)

	// Try untrusted create to ensure we pushed the tag to the registry
	createCmd = exec.Command(dockerBinary, "create", "--disable-content-trust=true", repoName)
	s.trustedCmd(createCmd)
	out, _, err = runCommandWithOutput(createCmd)
	c.Assert(err, check.IsNil)
	c.Assert(string(out), checker.Contains, "Status: Downloaded", check.Commentf("Missing expected output on trusted create with --disable-content-trust:\n%s", out))

}

func (s *DockerTrustSuite) TestUntrustedCreate(c *check.C) {
	repoName := fmt.Sprintf("%v/dockercliuntrusted/createtest", privateRegistryURL)
	withTagName := fmt.Sprintf("%s:latest", repoName)
	// tag the image and upload it to the private registry
	dockerCmd(c, "tag", "busybox", withTagName)
	dockerCmd(c, "push", withTagName)
	dockerCmd(c, "rmi", withTagName)

	// Try trusted create on untrusted tag
	createCmd := exec.Command(dockerBinary, "create", withTagName)
	s.trustedCmd(createCmd)
	out, _, err := runCommandWithOutput(createCmd)
	c.Assert(err, check.Not(check.IsNil))
	c.Assert(string(out), checker.Contains, fmt.Sprintf("does not have trust data for %s", repoName), check.Commentf("Missing expected output on trusted create:\n%s", out))

}

func (s *DockerTrustSuite) TestTrustedIsolatedCreate(c *check.C) {
	repoName := s.setupTrustedImage(c, "trusted-isolated-create")

	// Try create
	createCmd := exec.Command(dockerBinary, "--config", "/tmp/docker-isolated-create", "create", repoName)
	s.trustedCmd(createCmd)
	out, _, err := runCommandWithOutput(createCmd)
	c.Assert(err, check.IsNil)
	c.Assert(string(out), checker.Contains, "Tagging", check.Commentf("Missing expected output on trusted push:\n%s", out))

	dockerCmd(c, "rmi", repoName)
}

func (s *DockerTrustSuite) TestCreateWhenCertExpired(c *check.C) {
	c.Skip("Currently changes system time, causing instability")
	repoName := s.setupTrustedImage(c, "trusted-create-expired")

	// Certificates have 10 years of expiration
	elevenYearsFromNow := time.Now().Add(time.Hour * 24 * 365 * 11)

	runAtDifferentDate(elevenYearsFromNow, func() {
		// Try create
		createCmd := exec.Command(dockerBinary, "create", repoName)
		s.trustedCmd(createCmd)
		out, _, err := runCommandWithOutput(createCmd)
		c.Assert(err, check.Not(check.IsNil))
		c.Assert(string(out), checker.Contains, "could not validate the path to a trusted root", check.Commentf("Missing expected output on trusted create in the distant future:\n%s", out))
	})

	runAtDifferentDate(elevenYearsFromNow, func() {
		// Try create
		createCmd := exec.Command(dockerBinary, "create", "--disable-content-trust", repoName)
		s.trustedCmd(createCmd)
		out, _, err := runCommandWithOutput(createCmd)
		c.Assert(err, check.Not(check.IsNil))
		c.Assert(string(out), checker.Contains, "Status: Downloaded", check.Commentf("Missing expected output on trusted create in the distant future:\n%s", out))

	})
}

func (s *DockerTrustSuite) TestTrustedCreateFromBadTrustServer(c *check.C) {
	repoName := fmt.Sprintf("%v/dockerclievilcreate/trusted:latest", privateRegistryURL)
	evilLocalConfigDir, err := ioutil.TempDir("", "evilcreate-local-config-dir")
	c.Assert(err, check.IsNil)

	// tag the image and upload it to the private registry
	dockerCmd(c, "tag", "busybox", repoName)

	pushCmd := exec.Command(dockerBinary, "push", repoName)
	s.trustedCmd(pushCmd)
	out, _, err := runCommandWithOutput(pushCmd)
	c.Assert(err, check.IsNil)
	c.Assert(string(out), checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push:\n%s", out))

	dockerCmd(c, "rmi", repoName)

	// Try create
	createCmd := exec.Command(dockerBinary, "create", repoName)
	s.trustedCmd(createCmd)
	out, _, err = runCommandWithOutput(createCmd)
	c.Assert(err, check.IsNil)
	c.Assert(string(out), checker.Contains, "Tagging", check.Commentf("Missing expected output on trusted push:\n%s", out))

	dockerCmd(c, "rmi", repoName)

	// Kill the notary server, start a new "evil" one.
	s.not.Close()
	s.not, err = newTestNotary(c)
	c.Assert(err, check.IsNil)

	// In order to make an evil server, lets re-init a client (with a different trust dir) and push new data.
	// tag an image and upload it to the private registry
	dockerCmd(c, "--config", evilLocalConfigDir, "tag", "busybox", repoName)

	// Push up to the new server
	pushCmd = exec.Command(dockerBinary, "--config", evilLocalConfigDir, "push", repoName)
	s.trustedCmd(pushCmd)
	out, _, err = runCommandWithOutput(pushCmd)
	c.Assert(err, check.IsNil)
	c.Assert(string(out), checker.Contains, "Signing and pushing trust metadata", check.Commentf("Missing expected output on trusted push:\n%s", out))

	// Now, try creating with the original client from this new trust server. This should fallback to our cached timestamp and metadata.
	createCmd = exec.Command(dockerBinary, "create", repoName)
	s.trustedCmd(createCmd)
	out, _, err = runCommandWithOutput(createCmd)
	if err != nil {
		c.Fatalf("Error falling back to cached trust data: %s\n%s", err, out)
	}
	if !strings.Contains(string(out), "Error while downloading remote metadata, using cached timestamp") {
		c.Fatalf("Missing expected output on trusted create:\n%s", out)
	}

}

func (s *DockerSuite) TestCreateStopSignal(c *check.C) {
	name := "test_create_stop_signal"
	dockerCmd(c, "create", "--name", name, "--stop-signal", "9", "busybox")

	res := inspectFieldJSON(c, name, "Config.StopSignal")
	c.Assert(res, checker.Contains, "9")

}

func (s *DockerSuite) TestCreateWithWorkdir(c *check.C) {
	// TODO Windows. This requires further investigation for porting to
	// Windows CI. Currently fails.
	if daemonPlatform == "windows" {
		c.Skip("Fails on Windows CI")
	}
	name := "foo"

	prefix, slash := getPrefixAndSlashFromDaemonPlatform()
	dir := prefix + slash + "home" + slash + "foo" + slash + "bar"

	dockerCmd(c, "create", "--name", name, "-w", dir, "busybox")
	dockerCmd(c, "cp", fmt.Sprintf("%s:%s", name, dir), prefix+slash+"tmp")
}

func (s *DockerSuite) TestCreateWithInvalidLogOpts(c *check.C) {
	name := "test-invalidate-log-opts"
	out, _, err := dockerCmdWithError("create", "--name", name, "--log-opt", "invalid=true", "busybox")
	c.Assert(err, checker.NotNil)
	c.Assert(out, checker.Contains, "unknown log opt")

	out, _ = dockerCmd(c, "ps", "-a")
	c.Assert(out, checker.Not(checker.Contains), name)
}

// #20972
func (s *DockerSuite) TestCreate64ByteHexID(c *check.C) {
	out := inspectField(c, "busybox", "Id")
	imageID := strings.TrimPrefix(strings.TrimSpace(string(out)), "sha256:")

	dockerCmd(c, "create", imageID)
}