docker_cli_run_unix_test.go 31 KB

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