docker_cli_run_unix_test.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. // +build !windows
  2. package main
  3. import (
  4. "bufio"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/docker/docker/pkg/homedir"
  15. "github.com/docker/docker/pkg/integration/checker"
  16. "github.com/docker/docker/pkg/mount"
  17. "github.com/docker/docker/pkg/parsers"
  18. "github.com/docker/docker/pkg/sysinfo"
  19. "github.com/go-check/check"
  20. "github.com/kr/pty"
  21. )
  22. // #6509
  23. func (s *DockerSuite) TestRunRedirectStdout(c *check.C) {
  24. checkRedirect := func(command string) {
  25. _, tty, err := pty.Open()
  26. c.Assert(err, checker.IsNil, check.Commentf("Could not open pty"))
  27. cmd := exec.Command("sh", "-c", command)
  28. cmd.Stdin = tty
  29. cmd.Stdout = tty
  30. cmd.Stderr = tty
  31. c.Assert(cmd.Start(), checker.IsNil)
  32. ch := make(chan error)
  33. go func() {
  34. ch <- cmd.Wait()
  35. close(ch)
  36. }()
  37. select {
  38. case <-time.After(10 * time.Second):
  39. c.Fatal("command timeout")
  40. case err := <-ch:
  41. c.Assert(err, checker.IsNil, check.Commentf("wait err"))
  42. }
  43. }
  44. checkRedirect(dockerBinary + " run -i busybox cat /etc/passwd | grep -q root")
  45. checkRedirect(dockerBinary + " run busybox cat /etc/passwd | grep -q root")
  46. }
  47. // Test recursive bind mount works by default
  48. func (s *DockerSuite) TestRunWithVolumesIsRecursive(c *check.C) {
  49. // /tmp gets permission denied
  50. testRequires(c, NotUserNamespace)
  51. tmpDir, err := ioutil.TempDir("", "docker_recursive_mount_test")
  52. c.Assert(err, checker.IsNil)
  53. defer os.RemoveAll(tmpDir)
  54. // Create a temporary tmpfs mount.
  55. tmpfsDir := filepath.Join(tmpDir, "tmpfs")
  56. c.Assert(os.MkdirAll(tmpfsDir, 0777), checker.IsNil, check.Commentf("failed to mkdir at %s", tmpfsDir))
  57. c.Assert(mount.Mount("tmpfs", tmpfsDir, "tmpfs", ""), checker.IsNil, check.Commentf("failed to create a tmpfs mount at %s", tmpfsDir))
  58. f, err := ioutil.TempFile(tmpfsDir, "touch-me")
  59. c.Assert(err, checker.IsNil)
  60. defer f.Close()
  61. runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox:latest", "ls", "/tmp/tmpfs")
  62. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  63. c.Assert(err, checker.IsNil)
  64. c.Assert(out, checker.Contains, filepath.Base(f.Name()), check.Commentf("Recursive bind mount test failed. Expected file not found"))
  65. }
  66. func (s *DockerSuite) TestRunDeviceDirectory(c *check.C) {
  67. testRequires(c, DaemonIsLinux, NotUserNamespace)
  68. if _, err := os.Stat("/dev/snd"); err != nil {
  69. c.Skip("Host does not have /dev/snd")
  70. }
  71. out, _ := dockerCmd(c, "run", "--device", "/dev/snd:/dev/snd", "busybox", "sh", "-c", "ls /dev/snd/")
  72. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "timer", check.Commentf("expected output /dev/snd/timer"))
  73. out, _ = dockerCmd(c, "run", "--device", "/dev/snd:/dev/othersnd", "busybox", "sh", "-c", "ls /dev/othersnd/")
  74. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "seq", check.Commentf("expected output /dev/othersnd/seq"))
  75. }
  76. // TestRunDetach checks attaching and detaching with the default escape sequence.
  77. func (s *DockerSuite) TestRunAttachDetach(c *check.C) {
  78. name := "attach-detach"
  79. dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
  80. cmd := exec.Command(dockerBinary, "attach", name)
  81. stdout, err := cmd.StdoutPipe()
  82. c.Assert(err, checker.IsNil)
  83. cpty, tty, err := pty.Open()
  84. c.Assert(err, checker.IsNil)
  85. defer cpty.Close()
  86. cmd.Stdin = tty
  87. c.Assert(cmd.Start(), checker.IsNil)
  88. c.Assert(waitRun(name), check.IsNil)
  89. _, err = cpty.Write([]byte("hello\n"))
  90. c.Assert(err, checker.IsNil)
  91. out, err := bufio.NewReader(stdout).ReadString('\n')
  92. c.Assert(err, checker.IsNil)
  93. c.Assert(strings.TrimSpace(out), checker.Equals, "hello")
  94. // escape sequence
  95. _, err = cpty.Write([]byte{16})
  96. c.Assert(err, checker.IsNil)
  97. time.Sleep(100 * time.Millisecond)
  98. _, err = cpty.Write([]byte{17})
  99. c.Assert(err, checker.IsNil)
  100. ch := make(chan struct{})
  101. go func() {
  102. cmd.Wait()
  103. ch <- struct{}{}
  104. }()
  105. select {
  106. case <-ch:
  107. case <-time.After(10 * time.Second):
  108. c.Fatal("timed out waiting for container to exit")
  109. }
  110. running, err := inspectField(name, "State.Running")
  111. c.Assert(err, checker.IsNil)
  112. c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running"))
  113. }
  114. // TestRunDetach checks attaching and detaching with the escape sequence specified via flags.
  115. func (s *DockerSuite) TestRunAttachDetachFromFlag(c *check.C) {
  116. name := "attach-detach"
  117. keyCtrlA := []byte{1}
  118. keyA := []byte{97}
  119. dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
  120. cmd := exec.Command(dockerBinary, "attach", "--detach-keys='ctrl-a,a'", name)
  121. stdout, err := cmd.StdoutPipe()
  122. if err != nil {
  123. c.Fatal(err)
  124. }
  125. cpty, tty, err := pty.Open()
  126. if err != nil {
  127. c.Fatal(err)
  128. }
  129. defer cpty.Close()
  130. cmd.Stdin = tty
  131. if err := cmd.Start(); err != nil {
  132. c.Fatal(err)
  133. }
  134. c.Assert(waitRun(name), check.IsNil)
  135. if _, err := cpty.Write([]byte("hello\n")); err != nil {
  136. c.Fatal(err)
  137. }
  138. out, err := bufio.NewReader(stdout).ReadString('\n')
  139. if err != nil {
  140. c.Fatal(err)
  141. }
  142. if strings.TrimSpace(out) != "hello" {
  143. c.Fatalf("expected 'hello', got %q", out)
  144. }
  145. // escape sequence
  146. if _, err := cpty.Write(keyCtrlA); err != nil {
  147. c.Fatal(err)
  148. }
  149. time.Sleep(100 * time.Millisecond)
  150. if _, err := cpty.Write(keyA); err != nil {
  151. c.Fatal(err)
  152. }
  153. ch := make(chan struct{})
  154. go func() {
  155. cmd.Wait()
  156. ch <- struct{}{}
  157. }()
  158. select {
  159. case <-ch:
  160. case <-time.After(10 * time.Second):
  161. c.Fatal("timed out waiting for container to exit")
  162. }
  163. running, err := inspectField(name, "State.Running")
  164. c.Assert(err, checker.IsNil)
  165. c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running"))
  166. }
  167. // TestRunDetach checks attaching and detaching with the escape sequence specified via config file.
  168. func (s *DockerSuite) TestRunAttachDetachFromConfig(c *check.C) {
  169. keyCtrlA := []byte{1}
  170. keyA := []byte{97}
  171. // Setup config
  172. homeKey := homedir.Key()
  173. homeVal := homedir.Get()
  174. tmpDir, err := ioutil.TempDir("", "fake-home")
  175. c.Assert(err, checker.IsNil)
  176. defer os.RemoveAll(tmpDir)
  177. dotDocker := filepath.Join(tmpDir, ".docker")
  178. os.Mkdir(dotDocker, 0600)
  179. tmpCfg := filepath.Join(dotDocker, "config.json")
  180. defer func() { os.Setenv(homeKey, homeVal) }()
  181. os.Setenv(homeKey, tmpDir)
  182. data := `{
  183. "detachKeys": "ctrl-a,a"
  184. }`
  185. err = ioutil.WriteFile(tmpCfg, []byte(data), 0600)
  186. c.Assert(err, checker.IsNil)
  187. // Then do the work
  188. name := "attach-detach"
  189. dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
  190. cmd := exec.Command(dockerBinary, "attach", name)
  191. stdout, err := cmd.StdoutPipe()
  192. if err != nil {
  193. c.Fatal(err)
  194. }
  195. cpty, tty, err := pty.Open()
  196. if err != nil {
  197. c.Fatal(err)
  198. }
  199. defer cpty.Close()
  200. cmd.Stdin = tty
  201. if err := cmd.Start(); err != nil {
  202. c.Fatal(err)
  203. }
  204. c.Assert(waitRun(name), check.IsNil)
  205. if _, err := cpty.Write([]byte("hello\n")); err != nil {
  206. c.Fatal(err)
  207. }
  208. out, err := bufio.NewReader(stdout).ReadString('\n')
  209. if err != nil {
  210. c.Fatal(err)
  211. }
  212. if strings.TrimSpace(out) != "hello" {
  213. c.Fatalf("expected 'hello', got %q", out)
  214. }
  215. // escape sequence
  216. if _, err := cpty.Write(keyCtrlA); err != nil {
  217. c.Fatal(err)
  218. }
  219. time.Sleep(100 * time.Millisecond)
  220. if _, err := cpty.Write(keyA); err != nil {
  221. c.Fatal(err)
  222. }
  223. ch := make(chan struct{})
  224. go func() {
  225. cmd.Wait()
  226. ch <- struct{}{}
  227. }()
  228. select {
  229. case <-ch:
  230. case <-time.After(10 * time.Second):
  231. c.Fatal("timed out waiting for container to exit")
  232. }
  233. running, err := inspectField(name, "State.Running")
  234. c.Assert(err, checker.IsNil)
  235. c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running"))
  236. }
  237. // TestRunDetach checks attaching and detaching with the detach flags, making sure it overrides config file
  238. func (s *DockerSuite) TestRunAttachDetachKeysOverrideConfig(c *check.C) {
  239. keyCtrlA := []byte{1}
  240. keyA := []byte{97}
  241. // Setup config
  242. homeKey := homedir.Key()
  243. homeVal := homedir.Get()
  244. tmpDir, err := ioutil.TempDir("", "fake-home")
  245. c.Assert(err, checker.IsNil)
  246. defer os.RemoveAll(tmpDir)
  247. dotDocker := filepath.Join(tmpDir, ".docker")
  248. os.Mkdir(dotDocker, 0600)
  249. tmpCfg := filepath.Join(dotDocker, "config.json")
  250. defer func() { os.Setenv(homeKey, homeVal) }()
  251. os.Setenv(homeKey, tmpDir)
  252. data := `{
  253. "detachKeys": "ctrl-e,e"
  254. }`
  255. err = ioutil.WriteFile(tmpCfg, []byte(data), 0600)
  256. c.Assert(err, checker.IsNil)
  257. // Then do the work
  258. name := "attach-detach"
  259. dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
  260. cmd := exec.Command(dockerBinary, "attach", "--detach-keys='ctrl-a,a'", name)
  261. stdout, err := cmd.StdoutPipe()
  262. if err != nil {
  263. c.Fatal(err)
  264. }
  265. cpty, tty, err := pty.Open()
  266. if err != nil {
  267. c.Fatal(err)
  268. }
  269. defer cpty.Close()
  270. cmd.Stdin = tty
  271. if err := cmd.Start(); err != nil {
  272. c.Fatal(err)
  273. }
  274. c.Assert(waitRun(name), check.IsNil)
  275. if _, err := cpty.Write([]byte("hello\n")); err != nil {
  276. c.Fatal(err)
  277. }
  278. out, err := bufio.NewReader(stdout).ReadString('\n')
  279. if err != nil {
  280. c.Fatal(err)
  281. }
  282. if strings.TrimSpace(out) != "hello" {
  283. c.Fatalf("expected 'hello', got %q", out)
  284. }
  285. // escape sequence
  286. if _, err := cpty.Write(keyCtrlA); err != nil {
  287. c.Fatal(err)
  288. }
  289. time.Sleep(100 * time.Millisecond)
  290. if _, err := cpty.Write(keyA); err != nil {
  291. c.Fatal(err)
  292. }
  293. ch := make(chan struct{})
  294. go func() {
  295. cmd.Wait()
  296. ch <- struct{}{}
  297. }()
  298. select {
  299. case <-ch:
  300. case <-time.After(10 * time.Second):
  301. c.Fatal("timed out waiting for container to exit")
  302. }
  303. running, err := inspectField(name, "State.Running")
  304. c.Assert(err, checker.IsNil)
  305. c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running"))
  306. }
  307. // "test" should be printed
  308. func (s *DockerSuite) TestRunWithCPUQuota(c *check.C) {
  309. testRequires(c, cpuCfsQuota)
  310. file := "/sys/fs/cgroup/cpu/cpu.cfs_quota_us"
  311. out, _ := dockerCmd(c, "run", "--cpu-quota", "8000", "--name", "test", "busybox", "cat", file)
  312. c.Assert(strings.TrimSpace(out), checker.Equals, "8000")
  313. out, err := inspectField("test", "HostConfig.CpuQuota")
  314. c.Assert(err, check.IsNil)
  315. c.Assert(out, checker.Equals, "8000", check.Commentf("setting the CPU CFS quota failed"))
  316. }
  317. func (s *DockerSuite) TestRunWithCpuPeriod(c *check.C) {
  318. testRequires(c, cpuCfsPeriod)
  319. file := "/sys/fs/cgroup/cpu/cpu.cfs_period_us"
  320. out, _ := dockerCmd(c, "run", "--cpu-period", "50000", "--name", "test", "busybox", "cat", file)
  321. c.Assert(strings.TrimSpace(out), checker.Equals, "50000")
  322. out, err := inspectField("test", "HostConfig.CpuPeriod")
  323. c.Assert(err, check.IsNil)
  324. c.Assert(out, checker.Equals, "50000", check.Commentf("setting the CPU CFS period failed"))
  325. }
  326. func (s *DockerSuite) TestRunWithKernelMemory(c *check.C) {
  327. testRequires(c, kernelMemorySupport)
  328. file := "/sys/fs/cgroup/memory/memory.kmem.limit_in_bytes"
  329. stdout, _, _ := dockerCmdWithStdoutStderr(c, "run", "--kernel-memory", "50M", "--name", "test1", "busybox", "cat", file)
  330. c.Assert(strings.TrimSpace(stdout), checker.Equals, "52428800")
  331. out, err := inspectField("test1", "HostConfig.KernelMemory")
  332. c.Assert(err, check.IsNil)
  333. c.Assert(out, check.Equals, "52428800")
  334. }
  335. func (s *DockerSuite) TestRunWithInvalidKernelMemory(c *check.C) {
  336. testRequires(c, kernelMemorySupport)
  337. out, _, err := dockerCmdWithError("run", "--kernel-memory", "2M", "busybox", "true")
  338. c.Assert(err, check.NotNil)
  339. expected := "Minimum kernel memory limit allowed is 4MB"
  340. c.Assert(out, checker.Contains, expected)
  341. out, _, err = dockerCmdWithError("run", "--kernel-memory", "-16m", "--name", "test2", "busybox", "echo", "test")
  342. c.Assert(err, check.NotNil)
  343. expected = "invalid size"
  344. c.Assert(out, checker.Contains, expected)
  345. }
  346. func (s *DockerSuite) TestRunWithCPUShares(c *check.C) {
  347. testRequires(c, cpuShare)
  348. file := "/sys/fs/cgroup/cpu/cpu.shares"
  349. out, _ := dockerCmd(c, "run", "--cpu-shares", "1000", "--name", "test", "busybox", "cat", file)
  350. c.Assert(strings.TrimSpace(out), checker.Equals, "1000")
  351. out, err := inspectField("test", "HostConfig.CPUShares")
  352. c.Assert(err, check.IsNil)
  353. c.Assert(out, check.Equals, "1000")
  354. }
  355. // "test" should be printed
  356. func (s *DockerSuite) TestRunEchoStdoutWithCPUSharesAndMemoryLimit(c *check.C) {
  357. testRequires(c, cpuShare)
  358. testRequires(c, memoryLimitSupport)
  359. out, _, _ := dockerCmdWithStdoutStderr(c, "run", "--cpu-shares", "1000", "-m", "32m", "busybox", "echo", "test")
  360. c.Assert(out, checker.Equals, "test\n", check.Commentf("container should've printed 'test'"))
  361. }
  362. func (s *DockerSuite) TestRunWithCpusetCpus(c *check.C) {
  363. testRequires(c, cgroupCpuset)
  364. file := "/sys/fs/cgroup/cpuset/cpuset.cpus"
  365. out, _ := dockerCmd(c, "run", "--cpuset-cpus", "0", "--name", "test", "busybox", "cat", file)
  366. c.Assert(strings.TrimSpace(out), checker.Equals, "0")
  367. out, err := inspectField("test", "HostConfig.CpusetCpus")
  368. c.Assert(err, check.IsNil)
  369. c.Assert(out, check.Equals, "0")
  370. }
  371. func (s *DockerSuite) TestRunWithCpusetMems(c *check.C) {
  372. testRequires(c, cgroupCpuset)
  373. file := "/sys/fs/cgroup/cpuset/cpuset.mems"
  374. out, _ := dockerCmd(c, "run", "--cpuset-mems", "0", "--name", "test", "busybox", "cat", file)
  375. c.Assert(strings.TrimSpace(out), checker.Equals, "0")
  376. out, err := inspectField("test", "HostConfig.CpusetMems")
  377. c.Assert(err, check.IsNil)
  378. c.Assert(out, check.Equals, "0")
  379. }
  380. func (s *DockerSuite) TestRunWithBlkioWeight(c *check.C) {
  381. testRequires(c, blkioWeight)
  382. file := "/sys/fs/cgroup/blkio/blkio.weight"
  383. out, _ := dockerCmd(c, "run", "--blkio-weight", "300", "--name", "test", "busybox", "cat", file)
  384. c.Assert(strings.TrimSpace(out), checker.Equals, "300")
  385. out, err := inspectField("test", "HostConfig.BlkioWeight")
  386. c.Assert(err, check.IsNil)
  387. c.Assert(out, check.Equals, "300")
  388. }
  389. func (s *DockerSuite) TestRunWithInvalidBlkioWeight(c *check.C) {
  390. testRequires(c, blkioWeight)
  391. out, _, err := dockerCmdWithError("run", "--blkio-weight", "5", "busybox", "true")
  392. c.Assert(err, check.NotNil, check.Commentf(out))
  393. expected := "Range of blkio weight is from 10 to 1000"
  394. c.Assert(out, checker.Contains, expected)
  395. }
  396. func (s *DockerSuite) TestRunWithInvalidPathforBlkioWeightDevice(c *check.C) {
  397. testRequires(c, blkioWeight)
  398. out, _, err := dockerCmdWithError("run", "--blkio-weight-device", "/dev/sdX:100", "busybox", "true")
  399. c.Assert(err, check.NotNil, check.Commentf(out))
  400. }
  401. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceReadBps(c *check.C) {
  402. testRequires(c, blkioWeight)
  403. out, _, err := dockerCmdWithError("run", "--device-read-bps", "/dev/sdX:500", "busybox", "true")
  404. c.Assert(err, check.NotNil, check.Commentf(out))
  405. }
  406. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceWriteBps(c *check.C) {
  407. testRequires(c, blkioWeight)
  408. out, _, err := dockerCmdWithError("run", "--device-write-bps", "/dev/sdX:500", "busybox", "true")
  409. c.Assert(err, check.NotNil, check.Commentf(out))
  410. }
  411. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceReadIOps(c *check.C) {
  412. testRequires(c, blkioWeight)
  413. out, _, err := dockerCmdWithError("run", "--device-read-iops", "/dev/sdX:500", "busybox", "true")
  414. c.Assert(err, check.NotNil, check.Commentf(out))
  415. }
  416. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceWriteIOps(c *check.C) {
  417. testRequires(c, blkioWeight)
  418. out, _, err := dockerCmdWithError("run", "--device-write-iops", "/dev/sdX:500", "busybox", "true")
  419. c.Assert(err, check.NotNil, check.Commentf(out))
  420. }
  421. func (s *DockerSuite) TestRunOOMExitCode(c *check.C) {
  422. testRequires(c, oomControl)
  423. errChan := make(chan error)
  424. go func() {
  425. defer close(errChan)
  426. //changing memory to 40MB from 4MB due to an issue with GCCGO that test fails to start the container.
  427. out, exitCode, _ := dockerCmdWithError("run", "-m", "40MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done")
  428. if expected := 137; exitCode != expected {
  429. errChan <- fmt.Errorf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out)
  430. }
  431. }()
  432. select {
  433. case err := <-errChan:
  434. c.Assert(err, check.IsNil)
  435. case <-time.After(600 * time.Second):
  436. c.Fatal("Timeout waiting for container to die on OOM")
  437. }
  438. }
  439. func (s *DockerSuite) TestRunWithMemoryLimit(c *check.C) {
  440. testRequires(c, memoryLimitSupport)
  441. file := "/sys/fs/cgroup/memory/memory.limit_in_bytes"
  442. stdout, _, _ := dockerCmdWithStdoutStderr(c, "run", "-m", "32M", "--name", "test", "busybox", "cat", file)
  443. c.Assert(strings.TrimSpace(stdout), checker.Equals, "33554432")
  444. out, err := inspectField("test", "HostConfig.Memory")
  445. c.Assert(err, check.IsNil)
  446. c.Assert(out, check.Equals, "33554432")
  447. }
  448. // TestRunWithoutMemoryswapLimit sets memory limit and disables swap
  449. // memory limit, this means the processes in the container can use
  450. // 16M memory and as much swap memory as they need (if the host
  451. // supports swap memory).
  452. func (s *DockerSuite) TestRunWithoutMemoryswapLimit(c *check.C) {
  453. testRequires(c, DaemonIsLinux)
  454. testRequires(c, memoryLimitSupport)
  455. testRequires(c, swapMemorySupport)
  456. dockerCmd(c, "run", "-m", "32m", "--memory-swap", "-1", "busybox", "true")
  457. }
  458. func (s *DockerSuite) TestRunWithSwappiness(c *check.C) {
  459. testRequires(c, memorySwappinessSupport)
  460. file := "/sys/fs/cgroup/memory/memory.swappiness"
  461. out, _ := dockerCmd(c, "run", "--memory-swappiness", "0", "--name", "test", "busybox", "cat", file)
  462. c.Assert(strings.TrimSpace(out), checker.Equals, "0")
  463. out, err := inspectField("test", "HostConfig.MemorySwappiness")
  464. c.Assert(err, check.IsNil)
  465. c.Assert(out, check.Equals, "0")
  466. }
  467. func (s *DockerSuite) TestRunWithSwappinessInvalid(c *check.C) {
  468. testRequires(c, memorySwappinessSupport)
  469. out, _, err := dockerCmdWithError("run", "--memory-swappiness", "101", "busybox", "true")
  470. c.Assert(err, check.NotNil)
  471. expected := "Valid memory swappiness range is 0-100"
  472. c.Assert(out, checker.Contains, expected, check.Commentf("Expected output to contain %q, not %q", out, expected))
  473. out, _, err = dockerCmdWithError("run", "--memory-swappiness", "-10", "busybox", "true")
  474. c.Assert(err, check.NotNil)
  475. c.Assert(out, checker.Contains, expected, check.Commentf("Expected output to contain %q, not %q", out, expected))
  476. }
  477. func (s *DockerSuite) TestRunWithMemoryReservation(c *check.C) {
  478. testRequires(c, memoryReservationSupport)
  479. file := "/sys/fs/cgroup/memory/memory.soft_limit_in_bytes"
  480. out, _ := dockerCmd(c, "run", "--memory-reservation", "200M", "--name", "test", "busybox", "cat", file)
  481. c.Assert(strings.TrimSpace(out), checker.Equals, "209715200")
  482. out, err := inspectField("test", "HostConfig.MemoryReservation")
  483. c.Assert(err, check.IsNil)
  484. c.Assert(out, check.Equals, "209715200")
  485. }
  486. func (s *DockerSuite) TestRunWithMemoryReservationInvalid(c *check.C) {
  487. testRequires(c, memoryLimitSupport)
  488. testRequires(c, memoryReservationSupport)
  489. out, _, err := dockerCmdWithError("run", "-m", "500M", "--memory-reservation", "800M", "busybox", "true")
  490. c.Assert(err, check.NotNil)
  491. expected := "Minimum memory limit should be larger than memory reservation limit"
  492. c.Assert(strings.TrimSpace(out), checker.Contains, expected, check.Commentf("run container should fail with invalid memory reservation"))
  493. }
  494. func (s *DockerSuite) TestStopContainerSignal(c *check.C) {
  495. out, _ := dockerCmd(c, "run", "--stop-signal", "SIGUSR1", "-d", "busybox", "/bin/sh", "-c", `trap 'echo "exit trapped"; exit 0' USR1; while true; do sleep 1; done`)
  496. containerID := strings.TrimSpace(out)
  497. c.Assert(waitRun(containerID), checker.IsNil)
  498. dockerCmd(c, "stop", containerID)
  499. out, _ = dockerCmd(c, "logs", containerID)
  500. c.Assert(out, checker.Contains, "exit trapped", check.Commentf("Expected `exit trapped` in the log"))
  501. }
  502. func (s *DockerSuite) TestRunSwapLessThanMemoryLimit(c *check.C) {
  503. testRequires(c, memoryLimitSupport)
  504. testRequires(c, swapMemorySupport)
  505. out, _, err := dockerCmdWithError("run", "-m", "16m", "--memory-swap", "15m", "busybox", "echo", "test")
  506. expected := "Minimum memoryswap limit should be larger than memory limit"
  507. c.Assert(err, check.NotNil)
  508. c.Assert(out, checker.Contains, expected)
  509. }
  510. func (s *DockerSuite) TestRunInvalidCpusetCpusFlagValue(c *check.C) {
  511. testRequires(c, cgroupCpuset)
  512. sysInfo := sysinfo.New(true)
  513. cpus, err := parsers.ParseUintList(sysInfo.Cpus)
  514. c.Assert(err, check.IsNil)
  515. var invalid int
  516. for i := 0; i <= len(cpus)+1; i++ {
  517. if !cpus[i] {
  518. invalid = i
  519. break
  520. }
  521. }
  522. out, _, err := dockerCmdWithError("run", "--cpuset-cpus", strconv.Itoa(invalid), "busybox", "true")
  523. c.Assert(err, check.NotNil)
  524. expected := fmt.Sprintf("Error response from daemon: Requested CPUs are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Cpus)
  525. c.Assert(out, checker.Contains, expected)
  526. }
  527. func (s *DockerSuite) TestRunInvalidCpusetMemsFlagValue(c *check.C) {
  528. testRequires(c, cgroupCpuset)
  529. sysInfo := sysinfo.New(true)
  530. mems, err := parsers.ParseUintList(sysInfo.Mems)
  531. c.Assert(err, check.IsNil)
  532. var invalid int
  533. for i := 0; i <= len(mems)+1; i++ {
  534. if !mems[i] {
  535. invalid = i
  536. break
  537. }
  538. }
  539. out, _, err := dockerCmdWithError("run", "--cpuset-mems", strconv.Itoa(invalid), "busybox", "true")
  540. c.Assert(err, check.NotNil)
  541. expected := fmt.Sprintf("Error response from daemon: Requested memory nodes are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Mems)
  542. c.Assert(out, checker.Contains, expected)
  543. }
  544. func (s *DockerSuite) TestRunInvalidCPUShares(c *check.C) {
  545. testRequires(c, cpuShare, DaemonIsLinux)
  546. out, _, err := dockerCmdWithError("run", "--cpu-shares", "1", "busybox", "echo", "test")
  547. c.Assert(err, check.NotNil, check.Commentf(out))
  548. expected := "The minimum allowed cpu-shares is 2"
  549. c.Assert(out, checker.Contains, expected)
  550. out, _, err = dockerCmdWithError("run", "--cpu-shares", "-1", "busybox", "echo", "test")
  551. c.Assert(err, check.NotNil, check.Commentf(out))
  552. expected = "shares: invalid argument"
  553. c.Assert(out, checker.Contains, expected)
  554. out, _, err = dockerCmdWithError("run", "--cpu-shares", "99999999", "busybox", "echo", "test")
  555. c.Assert(err, check.NotNil, check.Commentf(out))
  556. expected = "The maximum allowed cpu-shares is"
  557. c.Assert(out, checker.Contains, expected)
  558. }
  559. func (s *DockerSuite) TestRunWithDefaultShmSize(c *check.C) {
  560. testRequires(c, DaemonIsLinux)
  561. name := "shm-default"
  562. out, _ := dockerCmd(c, "run", "--name", name, "busybox", "mount")
  563. shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  564. if !shmRegex.MatchString(out) {
  565. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  566. }
  567. shmSize, err := inspectField(name, "HostConfig.ShmSize")
  568. c.Assert(err, check.IsNil)
  569. c.Assert(shmSize, check.Equals, "67108864")
  570. }
  571. func (s *DockerSuite) TestRunWithShmSize(c *check.C) {
  572. testRequires(c, DaemonIsLinux)
  573. name := "shm"
  574. out, _ := dockerCmd(c, "run", "--name", name, "--shm-size=1G", "busybox", "mount")
  575. shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=1048576k`)
  576. if !shmRegex.MatchString(out) {
  577. c.Fatalf("Expected shm of 1GB in mount command, got %v", out)
  578. }
  579. shmSize, err := inspectField(name, "HostConfig.ShmSize")
  580. c.Assert(err, check.IsNil)
  581. c.Assert(shmSize, check.Equals, "1073741824")
  582. }
  583. func (s *DockerSuite) TestRunTmpfsMounts(c *check.C) {
  584. // TODO Windows (Post TP4): This test cannot run on a Windows daemon as
  585. // Windows does not support tmpfs mounts.
  586. testRequires(c, DaemonIsLinux)
  587. if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run", "busybox", "touch", "/run/somefile"); err != nil {
  588. c.Fatalf("/run directory not mounted on tmpfs %q %s", err, out)
  589. }
  590. if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run:noexec", "busybox", "touch", "/run/somefile"); err != nil {
  591. c.Fatalf("/run directory not mounted on tmpfs %q %s", err, out)
  592. }
  593. if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run:noexec,nosuid,rw,size=5k,mode=700", "busybox", "touch", "/run/somefile"); err != nil {
  594. c.Fatalf("/run failed to mount on tmpfs with valid options %q %s", err, out)
  595. }
  596. if _, _, err := dockerCmdWithError("run", "--tmpfs", "/run:foobar", "busybox", "touch", "/run/somefile"); err == nil {
  597. c.Fatalf("/run mounted on tmpfs when it should have vailed within invalid mount option")
  598. }
  599. if _, _, err := dockerCmdWithError("run", "--tmpfs", "/run", "-v", "/run:/run", "busybox", "touch", "/run/somefile"); err == nil {
  600. c.Fatalf("Should have generated an error saying Duplicate mount points")
  601. }
  602. }
  603. // TestRunSeccompProfileDenyUnshare checks that 'docker run --security-opt seccomp:/tmp/profile.json jess/unshare unshare' exits with operation not permitted.
  604. func (s *DockerSuite) TestRunSeccompProfileDenyUnshare(c *check.C) {
  605. testRequires(c, SameHostDaemon, seccompEnabled)
  606. jsonData := `{
  607. "defaultAction": "SCMP_ACT_ALLOW",
  608. "syscalls": [
  609. {
  610. "name": "unshare",
  611. "action": "SCMP_ACT_ERRNO"
  612. }
  613. ]
  614. }`
  615. tmpFile, err := ioutil.TempFile("", "profile.json")
  616. defer tmpFile.Close()
  617. if err != nil {
  618. c.Fatal(err)
  619. }
  620. if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
  621. c.Fatal(err)
  622. }
  623. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "apparmor:unconfined", "--security-opt", "seccomp:"+tmpFile.Name(), "debian:jessie", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc")
  624. out, _, _ := runCommandWithOutput(runCmd)
  625. if !strings.Contains(out, "Operation not permitted") {
  626. c.Fatalf("expected unshare with seccomp profile denied to fail, got %s", out)
  627. }
  628. }
  629. // TestRunSeccompProfileDenyChmod checks that 'docker run --security-opt seccomp:/tmp/profile.json busybox chmod 400 /etc/hostname' exits with operation not permitted.
  630. func (s *DockerSuite) TestRunSeccompProfileDenyChmod(c *check.C) {
  631. testRequires(c, SameHostDaemon, seccompEnabled)
  632. jsonData := `{
  633. "defaultAction": "SCMP_ACT_ALLOW",
  634. "syscalls": [
  635. {
  636. "name": "chmod",
  637. "action": "SCMP_ACT_ERRNO"
  638. }
  639. ]
  640. }`
  641. tmpFile, err := ioutil.TempFile("", "profile.json")
  642. defer tmpFile.Close()
  643. if err != nil {
  644. c.Fatal(err)
  645. }
  646. if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
  647. c.Fatal(err)
  648. }
  649. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "seccomp:"+tmpFile.Name(), "busybox", "chmod", "400", "/etc/hostname")
  650. out, _, _ := runCommandWithOutput(runCmd)
  651. if !strings.Contains(out, "Operation not permitted") {
  652. c.Fatalf("expected chmod with seccomp profile denied to fail, got %s", out)
  653. }
  654. }
  655. // TestRunSeccompProfileDenyUnshareUserns checks that 'docker run jess/unshare unshare --map-root-user --user sh -c whoami' with a specific profile to
  656. // deny unhare of a userns exits with operation not permitted.
  657. func (s *DockerSuite) TestRunSeccompProfileDenyUnshareUserns(c *check.C) {
  658. testRequires(c, SameHostDaemon, seccompEnabled)
  659. // from sched.h
  660. jsonData := fmt.Sprintf(`{
  661. "defaultAction": "SCMP_ACT_ALLOW",
  662. "syscalls": [
  663. {
  664. "name": "unshare",
  665. "action": "SCMP_ACT_ERRNO",
  666. "args": [
  667. {
  668. "index": 0,
  669. "value": %d,
  670. "op": "SCMP_CMP_EQ"
  671. }
  672. ]
  673. }
  674. ]
  675. }`, uint64(0x10000000))
  676. tmpFile, err := ioutil.TempFile("", "profile.json")
  677. defer tmpFile.Close()
  678. if err != nil {
  679. c.Fatal(err)
  680. }
  681. if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
  682. c.Fatal(err)
  683. }
  684. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "apparmor:unconfined", "--security-opt", "seccomp:"+tmpFile.Name(), "debian:jessie", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami")
  685. out, _, _ := runCommandWithOutput(runCmd)
  686. if !strings.Contains(out, "Operation not permitted") {
  687. c.Fatalf("expected unshare userns with seccomp profile denied to fail, got %s", out)
  688. }
  689. }
  690. // TestRunSeccompProfileDenyCloneUserns checks that 'docker run userns-test'
  691. // with a the default seccomp profile exits with operation not permitted.
  692. func (s *DockerSuite) TestRunSeccompProfileDenyCloneUserns(c *check.C) {
  693. testRequires(c, SameHostDaemon, seccompEnabled)
  694. runCmd := exec.Command(dockerBinary, "run", "userns-test", "id")
  695. out, _, err := runCommandWithOutput(runCmd)
  696. if err == nil || !strings.Contains(out, "clone failed: Operation not permitted") {
  697. c.Fatalf("expected clone userns with default seccomp profile denied to fail, got %s: %v", out, err)
  698. }
  699. }
  700. // TestRunSeccompUnconfinedCloneUserns checks that
  701. // 'docker run --security-opt seccomp:unconfined userns-test' allows creating a userns.
  702. func (s *DockerSuite) TestRunSeccompUnconfinedCloneUserns(c *check.C) {
  703. testRequires(c, SameHostDaemon, seccompEnabled, NotUserNamespace)
  704. // make sure running w privileged is ok
  705. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "seccomp:unconfined", "userns-test", "id")
  706. if out, _, err := runCommandWithOutput(runCmd); err != nil || !strings.Contains(out, "nobody") {
  707. c.Fatalf("expected clone userns with --security-opt seccomp:unconfined to succeed, got %s: %v", out, err)
  708. }
  709. }
  710. // TestRunSeccompAllowPrivCloneUserns checks that 'docker run --privileged userns-test'
  711. // allows creating a userns.
  712. func (s *DockerSuite) TestRunSeccompAllowPrivCloneUserns(c *check.C) {
  713. testRequires(c, SameHostDaemon, seccompEnabled, NotUserNamespace)
  714. // make sure running w privileged is ok
  715. runCmd := exec.Command(dockerBinary, "run", "--privileged", "userns-test", "id")
  716. if out, _, err := runCommandWithOutput(runCmd); err != nil || !strings.Contains(out, "nobody") {
  717. c.Fatalf("expected clone userns with --privileged to succeed, got %s: %v", out, err)
  718. }
  719. }
  720. // TestRunSeccompAllowAptKey checks that 'docker run debian:jessie apt-key' succeeds.
  721. func (s *DockerSuite) TestRunSeccompAllowAptKey(c *check.C) {
  722. testRequires(c, SameHostDaemon, seccompEnabled)
  723. // apt-key uses setrlimit & getrlimit, so we want to make sure we don't break it
  724. runCmd := exec.Command(dockerBinary, "run", "debian:jessie", "apt-key", "adv", "--keyserver", "hkp://p80.pool.sks-keyservers.net:80", "--recv-keys", "E871F18B51E0147C77796AC81196BA81F6B0FC61")
  725. if out, _, err := runCommandWithOutput(runCmd); err != nil {
  726. c.Fatalf("expected apt-key with seccomp to succeed, got %s: %v", out, err)
  727. }
  728. }