docker_cli_run_unix_test.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  1. // +build !windows
  2. package main
  3. import (
  4. "bufio"
  5. "encoding/json"
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "syscall"
  16. "time"
  17. "github.com/docker/docker/pkg/homedir"
  18. "github.com/docker/docker/pkg/integration/checker"
  19. "github.com/docker/docker/pkg/mount"
  20. "github.com/docker/docker/pkg/parsers"
  21. "github.com/docker/docker/pkg/sysinfo"
  22. "github.com/go-check/check"
  23. "github.com/kr/pty"
  24. )
  25. // #6509
  26. func (s *DockerSuite) TestRunRedirectStdout(c *check.C) {
  27. checkRedirect := func(command string) {
  28. _, tty, err := pty.Open()
  29. c.Assert(err, checker.IsNil, check.Commentf("Could not open pty"))
  30. cmd := exec.Command("sh", "-c", command)
  31. cmd.Stdin = tty
  32. cmd.Stdout = tty
  33. cmd.Stderr = tty
  34. c.Assert(cmd.Start(), checker.IsNil)
  35. ch := make(chan error)
  36. go func() {
  37. ch <- cmd.Wait()
  38. close(ch)
  39. }()
  40. select {
  41. case <-time.After(10 * time.Second):
  42. c.Fatal("command timeout")
  43. case err := <-ch:
  44. c.Assert(err, checker.IsNil, check.Commentf("wait err"))
  45. }
  46. }
  47. checkRedirect(dockerBinary + " run -i busybox cat /etc/passwd | grep -q root")
  48. checkRedirect(dockerBinary + " run busybox cat /etc/passwd | grep -q root")
  49. }
  50. // Test recursive bind mount works by default
  51. func (s *DockerSuite) TestRunWithVolumesIsRecursive(c *check.C) {
  52. // /tmp gets permission denied
  53. testRequires(c, NotUserNamespace, SameHostDaemon)
  54. tmpDir, err := ioutil.TempDir("", "docker_recursive_mount_test")
  55. c.Assert(err, checker.IsNil)
  56. defer os.RemoveAll(tmpDir)
  57. // Create a temporary tmpfs mount.
  58. tmpfsDir := filepath.Join(tmpDir, "tmpfs")
  59. c.Assert(os.MkdirAll(tmpfsDir, 0777), checker.IsNil, check.Commentf("failed to mkdir at %s", tmpfsDir))
  60. c.Assert(mount.Mount("tmpfs", tmpfsDir, "tmpfs", ""), checker.IsNil, check.Commentf("failed to create a tmpfs mount at %s", tmpfsDir))
  61. f, err := ioutil.TempFile(tmpfsDir, "touch-me")
  62. c.Assert(err, checker.IsNil)
  63. defer f.Close()
  64. runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox:latest", "ls", "/tmp/tmpfs")
  65. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  66. c.Assert(err, checker.IsNil)
  67. c.Assert(out, checker.Contains, filepath.Base(f.Name()), check.Commentf("Recursive bind mount test failed. Expected file not found"))
  68. }
  69. func (s *DockerSuite) TestRunDeviceDirectory(c *check.C) {
  70. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  71. if _, err := os.Stat("/dev/snd"); err != nil {
  72. c.Skip("Host does not have /dev/snd")
  73. }
  74. out, _ := dockerCmd(c, "run", "--device", "/dev/snd:/dev/snd", "busybox", "sh", "-c", "ls /dev/snd/")
  75. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "timer", check.Commentf("expected output /dev/snd/timer"))
  76. out, _ = dockerCmd(c, "run", "--device", "/dev/snd:/dev/othersnd", "busybox", "sh", "-c", "ls /dev/othersnd/")
  77. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "seq", check.Commentf("expected output /dev/othersnd/seq"))
  78. }
  79. // TestRunDetach checks attaching and detaching with the default escape sequence.
  80. func (s *DockerSuite) TestRunAttachDetach(c *check.C) {
  81. name := "attach-detach"
  82. dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
  83. cmd := exec.Command(dockerBinary, "attach", name)
  84. stdout, err := cmd.StdoutPipe()
  85. c.Assert(err, checker.IsNil)
  86. cpty, tty, err := pty.Open()
  87. c.Assert(err, checker.IsNil)
  88. defer cpty.Close()
  89. cmd.Stdin = tty
  90. c.Assert(cmd.Start(), checker.IsNil)
  91. c.Assert(waitRun(name), check.IsNil)
  92. _, err = cpty.Write([]byte("hello\n"))
  93. c.Assert(err, checker.IsNil)
  94. out, err := bufio.NewReader(stdout).ReadString('\n')
  95. c.Assert(err, checker.IsNil)
  96. c.Assert(strings.TrimSpace(out), checker.Equals, "hello")
  97. // escape sequence
  98. _, err = cpty.Write([]byte{16})
  99. c.Assert(err, checker.IsNil)
  100. time.Sleep(100 * time.Millisecond)
  101. _, err = cpty.Write([]byte{17})
  102. c.Assert(err, checker.IsNil)
  103. ch := make(chan struct{})
  104. go func() {
  105. cmd.Wait()
  106. ch <- struct{}{}
  107. }()
  108. select {
  109. case <-ch:
  110. case <-time.After(10 * time.Second):
  111. c.Fatal("timed out waiting for container to exit")
  112. }
  113. running := inspectField(c, name, "State.Running")
  114. c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running"))
  115. }
  116. // TestRunDetach checks attaching and detaching with the escape sequence specified via flags.
  117. func (s *DockerSuite) TestRunAttachDetachFromFlag(c *check.C) {
  118. name := "attach-detach"
  119. keyCtrlA := []byte{1}
  120. keyA := []byte{97}
  121. dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
  122. cmd := exec.Command(dockerBinary, "attach", "--detach-keys='ctrl-a,a'", name)
  123. stdout, err := cmd.StdoutPipe()
  124. if err != nil {
  125. c.Fatal(err)
  126. }
  127. cpty, tty, err := pty.Open()
  128. if err != nil {
  129. c.Fatal(err)
  130. }
  131. defer cpty.Close()
  132. cmd.Stdin = tty
  133. if err := cmd.Start(); err != nil {
  134. c.Fatal(err)
  135. }
  136. c.Assert(waitRun(name), check.IsNil)
  137. if _, err := cpty.Write([]byte("hello\n")); err != nil {
  138. c.Fatal(err)
  139. }
  140. out, err := bufio.NewReader(stdout).ReadString('\n')
  141. if err != nil {
  142. c.Fatal(err)
  143. }
  144. if strings.TrimSpace(out) != "hello" {
  145. c.Fatalf("expected 'hello', got %q", out)
  146. }
  147. // escape sequence
  148. if _, err := cpty.Write(keyCtrlA); err != nil {
  149. c.Fatal(err)
  150. }
  151. time.Sleep(100 * time.Millisecond)
  152. if _, err := cpty.Write(keyA); err != nil {
  153. c.Fatal(err)
  154. }
  155. ch := make(chan struct{})
  156. go func() {
  157. cmd.Wait()
  158. ch <- struct{}{}
  159. }()
  160. select {
  161. case <-ch:
  162. case <-time.After(10 * time.Second):
  163. c.Fatal("timed out waiting for container to exit")
  164. }
  165. running := inspectField(c, name, "State.Running")
  166. c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running"))
  167. }
  168. // TestRunDetach checks attaching and detaching with the escape sequence specified via flags.
  169. func (s *DockerSuite) TestRunAttachDetachFromInvalidFlag(c *check.C) {
  170. name := "attach-detach"
  171. dockerCmd(c, "run", "--name", name, "-itd", "busybox", "top")
  172. c.Assert(waitRun(name), check.IsNil)
  173. // specify an invalid detach key, container will ignore it and use default
  174. cmd := exec.Command(dockerBinary, "attach", "--detach-keys='ctrl-A,a'", name)
  175. stdout, err := cmd.StdoutPipe()
  176. if err != nil {
  177. c.Fatal(err)
  178. }
  179. cpty, tty, err := pty.Open()
  180. if err != nil {
  181. c.Fatal(err)
  182. }
  183. defer cpty.Close()
  184. cmd.Stdin = tty
  185. if err := cmd.Start(); err != nil {
  186. c.Fatal(err)
  187. }
  188. bufReader := bufio.NewReader(stdout)
  189. out, err := bufReader.ReadString('\n')
  190. if err != nil {
  191. c.Fatal(err)
  192. }
  193. // it should print a warning to indicate the detach key flag is invalid
  194. errStr := "Invalid escape keys (ctrl-A,a) provided"
  195. c.Assert(strings.TrimSpace(out), checker.Equals, errStr)
  196. }
  197. // TestRunDetach checks attaching and detaching with the escape sequence specified via config file.
  198. func (s *DockerSuite) TestRunAttachDetachFromConfig(c *check.C) {
  199. keyCtrlA := []byte{1}
  200. keyA := []byte{97}
  201. // Setup config
  202. homeKey := homedir.Key()
  203. homeVal := homedir.Get()
  204. tmpDir, err := ioutil.TempDir("", "fake-home")
  205. c.Assert(err, checker.IsNil)
  206. defer os.RemoveAll(tmpDir)
  207. dotDocker := filepath.Join(tmpDir, ".docker")
  208. os.Mkdir(dotDocker, 0600)
  209. tmpCfg := filepath.Join(dotDocker, "config.json")
  210. defer func() { os.Setenv(homeKey, homeVal) }()
  211. os.Setenv(homeKey, tmpDir)
  212. data := `{
  213. "detachKeys": "ctrl-a,a"
  214. }`
  215. err = ioutil.WriteFile(tmpCfg, []byte(data), 0600)
  216. c.Assert(err, checker.IsNil)
  217. // Then do the work
  218. name := "attach-detach"
  219. dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
  220. cmd := exec.Command(dockerBinary, "attach", name)
  221. stdout, err := cmd.StdoutPipe()
  222. if err != nil {
  223. c.Fatal(err)
  224. }
  225. cpty, tty, err := pty.Open()
  226. if err != nil {
  227. c.Fatal(err)
  228. }
  229. defer cpty.Close()
  230. cmd.Stdin = tty
  231. if err := cmd.Start(); err != nil {
  232. c.Fatal(err)
  233. }
  234. c.Assert(waitRun(name), check.IsNil)
  235. if _, err := cpty.Write([]byte("hello\n")); err != nil {
  236. c.Fatal(err)
  237. }
  238. out, err := bufio.NewReader(stdout).ReadString('\n')
  239. if err != nil {
  240. c.Fatal(err)
  241. }
  242. if strings.TrimSpace(out) != "hello" {
  243. c.Fatalf("expected 'hello', got %q", out)
  244. }
  245. // escape sequence
  246. if _, err := cpty.Write(keyCtrlA); err != nil {
  247. c.Fatal(err)
  248. }
  249. time.Sleep(100 * time.Millisecond)
  250. if _, err := cpty.Write(keyA); err != nil {
  251. c.Fatal(err)
  252. }
  253. ch := make(chan struct{})
  254. go func() {
  255. cmd.Wait()
  256. ch <- struct{}{}
  257. }()
  258. select {
  259. case <-ch:
  260. case <-time.After(10 * time.Second):
  261. c.Fatal("timed out waiting for container to exit")
  262. }
  263. running := inspectField(c, name, "State.Running")
  264. c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running"))
  265. }
  266. // TestRunDetach checks attaching and detaching with the detach flags, making sure it overrides config file
  267. func (s *DockerSuite) TestRunAttachDetachKeysOverrideConfig(c *check.C) {
  268. keyCtrlA := []byte{1}
  269. keyA := []byte{97}
  270. // Setup config
  271. homeKey := homedir.Key()
  272. homeVal := homedir.Get()
  273. tmpDir, err := ioutil.TempDir("", "fake-home")
  274. c.Assert(err, checker.IsNil)
  275. defer os.RemoveAll(tmpDir)
  276. dotDocker := filepath.Join(tmpDir, ".docker")
  277. os.Mkdir(dotDocker, 0600)
  278. tmpCfg := filepath.Join(dotDocker, "config.json")
  279. defer func() { os.Setenv(homeKey, homeVal) }()
  280. os.Setenv(homeKey, tmpDir)
  281. data := `{
  282. "detachKeys": "ctrl-e,e"
  283. }`
  284. err = ioutil.WriteFile(tmpCfg, []byte(data), 0600)
  285. c.Assert(err, checker.IsNil)
  286. // Then do the work
  287. name := "attach-detach"
  288. dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
  289. cmd := exec.Command(dockerBinary, "attach", "--detach-keys='ctrl-a,a'", name)
  290. stdout, err := cmd.StdoutPipe()
  291. if err != nil {
  292. c.Fatal(err)
  293. }
  294. cpty, tty, err := pty.Open()
  295. if err != nil {
  296. c.Fatal(err)
  297. }
  298. defer cpty.Close()
  299. cmd.Stdin = tty
  300. if err := cmd.Start(); err != nil {
  301. c.Fatal(err)
  302. }
  303. c.Assert(waitRun(name), check.IsNil)
  304. if _, err := cpty.Write([]byte("hello\n")); err != nil {
  305. c.Fatal(err)
  306. }
  307. out, err := bufio.NewReader(stdout).ReadString('\n')
  308. if err != nil {
  309. c.Fatal(err)
  310. }
  311. if strings.TrimSpace(out) != "hello" {
  312. c.Fatalf("expected 'hello', got %q", out)
  313. }
  314. // escape sequence
  315. if _, err := cpty.Write(keyCtrlA); err != nil {
  316. c.Fatal(err)
  317. }
  318. time.Sleep(100 * time.Millisecond)
  319. if _, err := cpty.Write(keyA); err != nil {
  320. c.Fatal(err)
  321. }
  322. ch := make(chan struct{})
  323. go func() {
  324. cmd.Wait()
  325. ch <- struct{}{}
  326. }()
  327. select {
  328. case <-ch:
  329. case <-time.After(10 * time.Second):
  330. c.Fatal("timed out waiting for container to exit")
  331. }
  332. running := inspectField(c, name, "State.Running")
  333. c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running"))
  334. }
  335. // "test" should be printed
  336. func (s *DockerSuite) TestRunWithCPUQuota(c *check.C) {
  337. testRequires(c, cpuCfsQuota)
  338. file := "/sys/fs/cgroup/cpu/cpu.cfs_quota_us"
  339. out, _ := dockerCmd(c, "run", "--cpu-quota", "8000", "--name", "test", "busybox", "cat", file)
  340. c.Assert(strings.TrimSpace(out), checker.Equals, "8000")
  341. out = inspectField(c, "test", "HostConfig.CpuQuota")
  342. c.Assert(out, checker.Equals, "8000", check.Commentf("setting the CPU CFS quota failed"))
  343. }
  344. func (s *DockerSuite) TestRunWithCpuPeriod(c *check.C) {
  345. testRequires(c, cpuCfsPeriod)
  346. file := "/sys/fs/cgroup/cpu/cpu.cfs_period_us"
  347. out, _ := dockerCmd(c, "run", "--cpu-period", "50000", "--name", "test", "busybox", "cat", file)
  348. c.Assert(strings.TrimSpace(out), checker.Equals, "50000")
  349. out, _ = dockerCmd(c, "run", "--cpu-period", "0", "busybox", "cat", file)
  350. c.Assert(strings.TrimSpace(out), checker.Equals, "100000")
  351. out = inspectField(c, "test", "HostConfig.CpuPeriod")
  352. c.Assert(out, checker.Equals, "50000", check.Commentf("setting the CPU CFS period failed"))
  353. }
  354. func (s *DockerSuite) TestRunWithInvalidCpuPeriod(c *check.C) {
  355. testRequires(c, cpuCfsPeriod)
  356. out, _, err := dockerCmdWithError("run", "--cpu-period", "900", "busybox", "true")
  357. c.Assert(err, check.NotNil)
  358. expected := "CPU cfs period can not be less than 1ms (i.e. 1000) or larger than 1s (i.e. 1000000)"
  359. c.Assert(out, checker.Contains, expected)
  360. out, _, err = dockerCmdWithError("run", "--cpu-period", "2000000", "busybox", "true")
  361. c.Assert(err, check.NotNil)
  362. c.Assert(out, checker.Contains, expected)
  363. out, _, err = dockerCmdWithError("run", "--cpu-period", "-3", "busybox", "true")
  364. c.Assert(err, check.NotNil)
  365. c.Assert(out, checker.Contains, expected)
  366. }
  367. func (s *DockerSuite) TestRunWithKernelMemory(c *check.C) {
  368. testRequires(c, kernelMemorySupport)
  369. file := "/sys/fs/cgroup/memory/memory.kmem.limit_in_bytes"
  370. stdout, _, _ := dockerCmdWithStdoutStderr(c, "run", "--kernel-memory", "50M", "--name", "test1", "busybox", "cat", file)
  371. c.Assert(strings.TrimSpace(stdout), checker.Equals, "52428800")
  372. out := inspectField(c, "test1", "HostConfig.KernelMemory")
  373. c.Assert(out, check.Equals, "52428800")
  374. }
  375. func (s *DockerSuite) TestRunWithInvalidKernelMemory(c *check.C) {
  376. testRequires(c, kernelMemorySupport)
  377. out, _, err := dockerCmdWithError("run", "--kernel-memory", "2M", "busybox", "true")
  378. c.Assert(err, check.NotNil)
  379. expected := "Minimum kernel memory limit allowed is 4MB"
  380. c.Assert(out, checker.Contains, expected)
  381. out, _, err = dockerCmdWithError("run", "--kernel-memory", "-16m", "--name", "test2", "busybox", "echo", "test")
  382. c.Assert(err, check.NotNil)
  383. expected = "invalid size"
  384. c.Assert(out, checker.Contains, expected)
  385. }
  386. func (s *DockerSuite) TestRunWithCPUShares(c *check.C) {
  387. testRequires(c, cpuShare)
  388. file := "/sys/fs/cgroup/cpu/cpu.shares"
  389. out, _ := dockerCmd(c, "run", "--cpu-shares", "1000", "--name", "test", "busybox", "cat", file)
  390. c.Assert(strings.TrimSpace(out), checker.Equals, "1000")
  391. out = inspectField(c, "test", "HostConfig.CPUShares")
  392. c.Assert(out, check.Equals, "1000")
  393. }
  394. // "test" should be printed
  395. func (s *DockerSuite) TestRunEchoStdoutWithCPUSharesAndMemoryLimit(c *check.C) {
  396. testRequires(c, cpuShare)
  397. testRequires(c, memoryLimitSupport)
  398. out, _, _ := dockerCmdWithStdoutStderr(c, "run", "--cpu-shares", "1000", "-m", "32m", "busybox", "echo", "test")
  399. c.Assert(out, checker.Equals, "test\n", check.Commentf("container should've printed 'test'"))
  400. }
  401. func (s *DockerSuite) TestRunWithCpusetCpus(c *check.C) {
  402. testRequires(c, cgroupCpuset)
  403. file := "/sys/fs/cgroup/cpuset/cpuset.cpus"
  404. out, _ := dockerCmd(c, "run", "--cpuset-cpus", "0", "--name", "test", "busybox", "cat", file)
  405. c.Assert(strings.TrimSpace(out), checker.Equals, "0")
  406. out = inspectField(c, "test", "HostConfig.CpusetCpus")
  407. c.Assert(out, check.Equals, "0")
  408. }
  409. func (s *DockerSuite) TestRunWithCpusetMems(c *check.C) {
  410. testRequires(c, cgroupCpuset)
  411. file := "/sys/fs/cgroup/cpuset/cpuset.mems"
  412. out, _ := dockerCmd(c, "run", "--cpuset-mems", "0", "--name", "test", "busybox", "cat", file)
  413. c.Assert(strings.TrimSpace(out), checker.Equals, "0")
  414. out = inspectField(c, "test", "HostConfig.CpusetMems")
  415. c.Assert(out, check.Equals, "0")
  416. }
  417. func (s *DockerSuite) TestRunWithBlkioWeight(c *check.C) {
  418. testRequires(c, blkioWeight)
  419. file := "/sys/fs/cgroup/blkio/blkio.weight"
  420. out, _ := dockerCmd(c, "run", "--blkio-weight", "300", "--name", "test", "busybox", "cat", file)
  421. c.Assert(strings.TrimSpace(out), checker.Equals, "300")
  422. out = inspectField(c, "test", "HostConfig.BlkioWeight")
  423. c.Assert(out, check.Equals, "300")
  424. }
  425. func (s *DockerSuite) TestRunWithInvalidBlkioWeight(c *check.C) {
  426. testRequires(c, blkioWeight)
  427. out, _, err := dockerCmdWithError("run", "--blkio-weight", "5", "busybox", "true")
  428. c.Assert(err, check.NotNil, check.Commentf(out))
  429. expected := "Range of blkio weight is from 10 to 1000"
  430. c.Assert(out, checker.Contains, expected)
  431. }
  432. func (s *DockerSuite) TestRunWithInvalidPathforBlkioWeightDevice(c *check.C) {
  433. testRequires(c, blkioWeight)
  434. out, _, err := dockerCmdWithError("run", "--blkio-weight-device", "/dev/sdX:100", "busybox", "true")
  435. c.Assert(err, check.NotNil, check.Commentf(out))
  436. }
  437. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceReadBps(c *check.C) {
  438. testRequires(c, blkioWeight)
  439. out, _, err := dockerCmdWithError("run", "--device-read-bps", "/dev/sdX:500", "busybox", "true")
  440. c.Assert(err, check.NotNil, check.Commentf(out))
  441. }
  442. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceWriteBps(c *check.C) {
  443. testRequires(c, blkioWeight)
  444. out, _, err := dockerCmdWithError("run", "--device-write-bps", "/dev/sdX:500", "busybox", "true")
  445. c.Assert(err, check.NotNil, check.Commentf(out))
  446. }
  447. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceReadIOps(c *check.C) {
  448. testRequires(c, blkioWeight)
  449. out, _, err := dockerCmdWithError("run", "--device-read-iops", "/dev/sdX:500", "busybox", "true")
  450. c.Assert(err, check.NotNil, check.Commentf(out))
  451. }
  452. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceWriteIOps(c *check.C) {
  453. testRequires(c, blkioWeight)
  454. out, _, err := dockerCmdWithError("run", "--device-write-iops", "/dev/sdX:500", "busybox", "true")
  455. c.Assert(err, check.NotNil, check.Commentf(out))
  456. }
  457. func (s *DockerSuite) TestRunOOMExitCode(c *check.C) {
  458. testRequires(c, oomControl)
  459. errChan := make(chan error)
  460. go func() {
  461. defer close(errChan)
  462. //changing memory to 40MB from 4MB due to an issue with GCCGO that test fails to start the container.
  463. out, exitCode, _ := dockerCmdWithError("run", "-m", "40MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done")
  464. if expected := 137; exitCode != expected {
  465. errChan <- fmt.Errorf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out)
  466. }
  467. }()
  468. select {
  469. case err := <-errChan:
  470. c.Assert(err, check.IsNil)
  471. case <-time.After(600 * time.Second):
  472. c.Fatal("Timeout waiting for container to die on OOM")
  473. }
  474. }
  475. func (s *DockerSuite) TestRunWithMemoryLimit(c *check.C) {
  476. testRequires(c, memoryLimitSupport)
  477. file := "/sys/fs/cgroup/memory/memory.limit_in_bytes"
  478. stdout, _, _ := dockerCmdWithStdoutStderr(c, "run", "-m", "32M", "--name", "test", "busybox", "cat", file)
  479. c.Assert(strings.TrimSpace(stdout), checker.Equals, "33554432")
  480. out := inspectField(c, "test", "HostConfig.Memory")
  481. c.Assert(out, check.Equals, "33554432")
  482. }
  483. // TestRunWithoutMemoryswapLimit sets memory limit and disables swap
  484. // memory limit, this means the processes in the container can use
  485. // 16M memory and as much swap memory as they need (if the host
  486. // supports swap memory).
  487. func (s *DockerSuite) TestRunWithoutMemoryswapLimit(c *check.C) {
  488. testRequires(c, DaemonIsLinux)
  489. testRequires(c, memoryLimitSupport)
  490. testRequires(c, swapMemorySupport)
  491. dockerCmd(c, "run", "-m", "32m", "--memory-swap", "-1", "busybox", "true")
  492. }
  493. func (s *DockerSuite) TestRunWithSwappiness(c *check.C) {
  494. testRequires(c, memorySwappinessSupport)
  495. file := "/sys/fs/cgroup/memory/memory.swappiness"
  496. out, _ := dockerCmd(c, "run", "--memory-swappiness", "0", "--name", "test", "busybox", "cat", file)
  497. c.Assert(strings.TrimSpace(out), checker.Equals, "0")
  498. out = inspectField(c, "test", "HostConfig.MemorySwappiness")
  499. c.Assert(out, check.Equals, "0")
  500. }
  501. func (s *DockerSuite) TestRunWithSwappinessInvalid(c *check.C) {
  502. testRequires(c, memorySwappinessSupport)
  503. out, _, err := dockerCmdWithError("run", "--memory-swappiness", "101", "busybox", "true")
  504. c.Assert(err, check.NotNil)
  505. expected := "Valid memory swappiness range is 0-100"
  506. c.Assert(out, checker.Contains, expected, check.Commentf("Expected output to contain %q, not %q", out, expected))
  507. out, _, err = dockerCmdWithError("run", "--memory-swappiness", "-10", "busybox", "true")
  508. c.Assert(err, check.NotNil)
  509. c.Assert(out, checker.Contains, expected, check.Commentf("Expected output to contain %q, not %q", out, expected))
  510. }
  511. func (s *DockerSuite) TestRunWithMemoryReservation(c *check.C) {
  512. testRequires(c, memoryReservationSupport)
  513. file := "/sys/fs/cgroup/memory/memory.soft_limit_in_bytes"
  514. out, _ := dockerCmd(c, "run", "--memory-reservation", "200M", "--name", "test", "busybox", "cat", file)
  515. c.Assert(strings.TrimSpace(out), checker.Equals, "209715200")
  516. out = inspectField(c, "test", "HostConfig.MemoryReservation")
  517. c.Assert(out, check.Equals, "209715200")
  518. }
  519. func (s *DockerSuite) TestRunWithMemoryReservationInvalid(c *check.C) {
  520. testRequires(c, memoryLimitSupport)
  521. testRequires(c, memoryReservationSupport)
  522. out, _, err := dockerCmdWithError("run", "-m", "500M", "--memory-reservation", "800M", "busybox", "true")
  523. c.Assert(err, check.NotNil)
  524. expected := "Minimum memory limit should be larger than memory reservation limit"
  525. c.Assert(strings.TrimSpace(out), checker.Contains, expected, check.Commentf("run container should fail with invalid memory reservation"))
  526. out, _, err = dockerCmdWithError("run", "--memory-reservation", "1k", "busybox", "true")
  527. c.Assert(err, check.NotNil)
  528. expected = "Minimum memory reservation allowed is 4MB"
  529. c.Assert(strings.TrimSpace(out), checker.Contains, expected, check.Commentf("run container should fail with invalid memory reservation"))
  530. }
  531. func (s *DockerSuite) TestStopContainerSignal(c *check.C) {
  532. 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`)
  533. containerID := strings.TrimSpace(out)
  534. c.Assert(waitRun(containerID), checker.IsNil)
  535. dockerCmd(c, "stop", containerID)
  536. out, _ = dockerCmd(c, "logs", containerID)
  537. c.Assert(out, checker.Contains, "exit trapped", check.Commentf("Expected `exit trapped` in the log"))
  538. }
  539. func (s *DockerSuite) TestRunSwapLessThanMemoryLimit(c *check.C) {
  540. testRequires(c, memoryLimitSupport)
  541. testRequires(c, swapMemorySupport)
  542. out, _, err := dockerCmdWithError("run", "-m", "16m", "--memory-swap", "15m", "busybox", "echo", "test")
  543. expected := "Minimum memoryswap limit should be larger than memory limit"
  544. c.Assert(err, check.NotNil)
  545. c.Assert(out, checker.Contains, expected)
  546. }
  547. func (s *DockerSuite) TestRunInvalidCpusetCpusFlagValue(c *check.C) {
  548. testRequires(c, cgroupCpuset, SameHostDaemon)
  549. sysInfo := sysinfo.New(true)
  550. cpus, err := parsers.ParseUintList(sysInfo.Cpus)
  551. c.Assert(err, check.IsNil)
  552. var invalid int
  553. for i := 0; i <= len(cpus)+1; i++ {
  554. if !cpus[i] {
  555. invalid = i
  556. break
  557. }
  558. }
  559. out, _, err := dockerCmdWithError("run", "--cpuset-cpus", strconv.Itoa(invalid), "busybox", "true")
  560. c.Assert(err, check.NotNil)
  561. expected := fmt.Sprintf("Error response from daemon: Requested CPUs are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Cpus)
  562. c.Assert(out, checker.Contains, expected)
  563. }
  564. func (s *DockerSuite) TestRunInvalidCpusetMemsFlagValue(c *check.C) {
  565. testRequires(c, cgroupCpuset)
  566. sysInfo := sysinfo.New(true)
  567. mems, err := parsers.ParseUintList(sysInfo.Mems)
  568. c.Assert(err, check.IsNil)
  569. var invalid int
  570. for i := 0; i <= len(mems)+1; i++ {
  571. if !mems[i] {
  572. invalid = i
  573. break
  574. }
  575. }
  576. out, _, err := dockerCmdWithError("run", "--cpuset-mems", strconv.Itoa(invalid), "busybox", "true")
  577. c.Assert(err, check.NotNil)
  578. expected := fmt.Sprintf("Error response from daemon: Requested memory nodes are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Mems)
  579. c.Assert(out, checker.Contains, expected)
  580. }
  581. func (s *DockerSuite) TestRunInvalidCPUShares(c *check.C) {
  582. testRequires(c, cpuShare, DaemonIsLinux)
  583. out, _, err := dockerCmdWithError("run", "--cpu-shares", "1", "busybox", "echo", "test")
  584. c.Assert(err, check.NotNil, check.Commentf(out))
  585. expected := "The minimum allowed cpu-shares is 2"
  586. c.Assert(out, checker.Contains, expected)
  587. out, _, err = dockerCmdWithError("run", "--cpu-shares", "-1", "busybox", "echo", "test")
  588. c.Assert(err, check.NotNil, check.Commentf(out))
  589. expected = "shares: invalid argument"
  590. c.Assert(out, checker.Contains, expected)
  591. out, _, err = dockerCmdWithError("run", "--cpu-shares", "99999999", "busybox", "echo", "test")
  592. c.Assert(err, check.NotNil, check.Commentf(out))
  593. expected = "The maximum allowed cpu-shares is"
  594. c.Assert(out, checker.Contains, expected)
  595. }
  596. func (s *DockerSuite) TestRunWithDefaultShmSize(c *check.C) {
  597. testRequires(c, DaemonIsLinux)
  598. name := "shm-default"
  599. out, _ := dockerCmd(c, "run", "--name", name, "busybox", "mount")
  600. shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  601. if !shmRegex.MatchString(out) {
  602. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  603. }
  604. shmSize := inspectField(c, name, "HostConfig.ShmSize")
  605. c.Assert(shmSize, check.Equals, "67108864")
  606. }
  607. func (s *DockerSuite) TestRunWithShmSize(c *check.C) {
  608. testRequires(c, DaemonIsLinux)
  609. name := "shm"
  610. out, _ := dockerCmd(c, "run", "--name", name, "--shm-size=1G", "busybox", "mount")
  611. shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=1048576k`)
  612. if !shmRegex.MatchString(out) {
  613. c.Fatalf("Expected shm of 1GB in mount command, got %v", out)
  614. }
  615. shmSize := inspectField(c, name, "HostConfig.ShmSize")
  616. c.Assert(shmSize, check.Equals, "1073741824")
  617. }
  618. func (s *DockerSuite) TestRunTmpfsMountsEnsureOrdered(c *check.C) {
  619. tmpFile, err := ioutil.TempFile("", "test")
  620. c.Assert(err, check.IsNil)
  621. defer tmpFile.Close()
  622. out, _ := dockerCmd(c, "run", "--tmpfs", "/run", "-v", tmpFile.Name()+":/run/test", "busybox", "ls", "/run")
  623. c.Assert(out, checker.Contains, "test")
  624. }
  625. func (s *DockerSuite) TestRunTmpfsMounts(c *check.C) {
  626. // TODO Windows (Post TP5): This test cannot run on a Windows daemon as
  627. // Windows does not support tmpfs mounts.
  628. testRequires(c, DaemonIsLinux)
  629. if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run", "busybox", "touch", "/run/somefile"); err != nil {
  630. c.Fatalf("/run directory not mounted on tmpfs %q %s", err, out)
  631. }
  632. if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run:noexec", "busybox", "touch", "/run/somefile"); err != nil {
  633. c.Fatalf("/run directory not mounted on tmpfs %q %s", err, out)
  634. }
  635. if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run:noexec,nosuid,rw,size=5k,mode=700", "busybox", "touch", "/run/somefile"); err != nil {
  636. c.Fatalf("/run failed to mount on tmpfs with valid options %q %s", err, out)
  637. }
  638. if _, _, err := dockerCmdWithError("run", "--tmpfs", "/run:foobar", "busybox", "touch", "/run/somefile"); err == nil {
  639. c.Fatalf("/run mounted on tmpfs when it should have vailed within invalid mount option")
  640. }
  641. if _, _, err := dockerCmdWithError("run", "--tmpfs", "/run", "-v", "/run:/run", "busybox", "touch", "/run/somefile"); err == nil {
  642. c.Fatalf("Should have generated an error saying Duplicate mount points")
  643. }
  644. }
  645. func (s *DockerSuite) TestRunSysctls(c *check.C) {
  646. testRequires(c, DaemonIsLinux)
  647. var err error
  648. out, _ := dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=1", "--name", "test", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward")
  649. c.Assert(strings.TrimSpace(out), check.Equals, "1")
  650. out = inspectFieldJSON(c, "test", "HostConfig.Sysctls")
  651. sysctls := make(map[string]string)
  652. err = json.Unmarshal([]byte(out), &sysctls)
  653. c.Assert(err, check.IsNil)
  654. c.Assert(sysctls["net.ipv4.ip_forward"], check.Equals, "1")
  655. out, _ = dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=0", "--name", "test1", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward")
  656. c.Assert(strings.TrimSpace(out), check.Equals, "0")
  657. out = inspectFieldJSON(c, "test1", "HostConfig.Sysctls")
  658. err = json.Unmarshal([]byte(out), &sysctls)
  659. c.Assert(err, check.IsNil)
  660. c.Assert(sysctls["net.ipv4.ip_forward"], check.Equals, "0")
  661. runCmd := exec.Command(dockerBinary, "run", "--sysctl", "kernel.foobar=1", "--name", "test2", "busybox", "cat", "/proc/sys/kernel/foobar")
  662. out, _, _ = runCommandWithOutput(runCmd)
  663. if !strings.Contains(out, "invalid value") {
  664. c.Fatalf("expected --sysctl to fail, got %s", out)
  665. }
  666. }
  667. // TestRunSeccompProfileDenyUnshare checks that 'docker run --security-opt seccomp=/tmp/profile.json debian:jessie unshare' exits with operation not permitted.
  668. func (s *DockerSuite) TestRunSeccompProfileDenyUnshare(c *check.C) {
  669. testRequires(c, SameHostDaemon, seccompEnabled, NotArm, Apparmor)
  670. jsonData := `{
  671. "defaultAction": "SCMP_ACT_ALLOW",
  672. "syscalls": [
  673. {
  674. "name": "unshare",
  675. "action": "SCMP_ACT_ERRNO"
  676. }
  677. ]
  678. }`
  679. tmpFile, err := ioutil.TempFile("", "profile.json")
  680. defer tmpFile.Close()
  681. if err != nil {
  682. c.Fatal(err)
  683. }
  684. if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
  685. c.Fatal(err)
  686. }
  687. 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")
  688. out, _, _ := runCommandWithOutput(runCmd)
  689. if !strings.Contains(out, "Operation not permitted") {
  690. c.Fatalf("expected unshare with seccomp profile denied to fail, got %s", out)
  691. }
  692. }
  693. // TestRunSeccompProfileDenyChmod checks that 'docker run --security-opt seccomp=/tmp/profile.json busybox chmod 400 /etc/hostname' exits with operation not permitted.
  694. func (s *DockerSuite) TestRunSeccompProfileDenyChmod(c *check.C) {
  695. testRequires(c, SameHostDaemon, seccompEnabled)
  696. jsonData := `{
  697. "defaultAction": "SCMP_ACT_ALLOW",
  698. "syscalls": [
  699. {
  700. "name": "chmod",
  701. "action": "SCMP_ACT_ERRNO"
  702. }
  703. ]
  704. }`
  705. tmpFile, err := ioutil.TempFile("", "profile.json")
  706. c.Assert(err, check.IsNil)
  707. defer tmpFile.Close()
  708. if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
  709. c.Fatal(err)
  710. }
  711. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "400", "/etc/hostname")
  712. out, _, _ := runCommandWithOutput(runCmd)
  713. if !strings.Contains(out, "Operation not permitted") {
  714. c.Fatalf("expected chmod with seccomp profile denied to fail, got %s", out)
  715. }
  716. }
  717. // TestRunSeccompProfileDenyUnshareUserns checks that 'docker run debian:jessie unshare --map-root-user --user sh -c whoami' with a specific profile to
  718. // deny unhare of a userns exits with operation not permitted.
  719. func (s *DockerSuite) TestRunSeccompProfileDenyUnshareUserns(c *check.C) {
  720. testRequires(c, SameHostDaemon, seccompEnabled, NotArm, Apparmor)
  721. // from sched.h
  722. jsonData := fmt.Sprintf(`{
  723. "defaultAction": "SCMP_ACT_ALLOW",
  724. "syscalls": [
  725. {
  726. "name": "unshare",
  727. "action": "SCMP_ACT_ERRNO",
  728. "args": [
  729. {
  730. "index": 0,
  731. "value": %d,
  732. "op": "SCMP_CMP_EQ"
  733. }
  734. ]
  735. }
  736. ]
  737. }`, uint64(0x10000000))
  738. tmpFile, err := ioutil.TempFile("", "profile.json")
  739. defer tmpFile.Close()
  740. if err != nil {
  741. c.Fatal(err)
  742. }
  743. if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
  744. c.Fatal(err)
  745. }
  746. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "apparmor=unconfined", "--security-opt", "seccomp="+tmpFile.Name(), "debian:jessie", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami")
  747. out, _, _ := runCommandWithOutput(runCmd)
  748. if !strings.Contains(out, "Operation not permitted") {
  749. c.Fatalf("expected unshare userns with seccomp profile denied to fail, got %s", out)
  750. }
  751. }
  752. // TestRunSeccompProfileDenyCloneUserns checks that 'docker run syscall-test'
  753. // with a the default seccomp profile exits with operation not permitted.
  754. func (s *DockerSuite) TestRunSeccompProfileDenyCloneUserns(c *check.C) {
  755. testRequires(c, SameHostDaemon, seccompEnabled)
  756. runCmd := exec.Command(dockerBinary, "run", "syscall-test", "userns-test", "id")
  757. out, _, err := runCommandWithOutput(runCmd)
  758. if err == nil || !strings.Contains(out, "clone failed: Operation not permitted") {
  759. c.Fatalf("expected clone userns with default seccomp profile denied to fail, got %s: %v", out, err)
  760. }
  761. }
  762. // TestRunSeccompUnconfinedCloneUserns checks that
  763. // 'docker run --security-opt seccomp=unconfined syscall-test' allows creating a userns.
  764. func (s *DockerSuite) TestRunSeccompUnconfinedCloneUserns(c *check.C) {
  765. testRequires(c, SameHostDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace)
  766. // make sure running w privileged is ok
  767. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "syscall-test", "userns-test", "id")
  768. if out, _, err := runCommandWithOutput(runCmd); err != nil || !strings.Contains(out, "nobody") {
  769. c.Fatalf("expected clone userns with --security-opt seccomp=unconfined to succeed, got %s: %v", out, err)
  770. }
  771. }
  772. // TestRunSeccompAllowPrivCloneUserns checks that 'docker run --privileged syscall-test'
  773. // allows creating a userns.
  774. func (s *DockerSuite) TestRunSeccompAllowPrivCloneUserns(c *check.C) {
  775. testRequires(c, SameHostDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace)
  776. // make sure running w privileged is ok
  777. runCmd := exec.Command(dockerBinary, "run", "--privileged", "syscall-test", "userns-test", "id")
  778. if out, _, err := runCommandWithOutput(runCmd); err != nil || !strings.Contains(out, "nobody") {
  779. c.Fatalf("expected clone userns with --privileged to succeed, got %s: %v", out, err)
  780. }
  781. }
  782. // TestRunSeccompAllowSetrlimit checks that 'docker run debian:jessie ulimit -v 1048510' succeeds.
  783. func (s *DockerSuite) TestRunSeccompAllowSetrlimit(c *check.C) {
  784. testRequires(c, SameHostDaemon, seccompEnabled)
  785. // ulimit uses setrlimit, so we want to make sure we don't break it
  786. runCmd := exec.Command(dockerBinary, "run", "debian:jessie", "bash", "-c", "ulimit -v 1048510")
  787. if out, _, err := runCommandWithOutput(runCmd); err != nil {
  788. c.Fatalf("expected ulimit with seccomp to succeed, got %s: %v", out, err)
  789. }
  790. }
  791. func (s *DockerSuite) TestRunSeccompDefaultProfile(c *check.C) {
  792. testRequires(c, SameHostDaemon, seccompEnabled, NotUserNamespace)
  793. var group sync.WaitGroup
  794. group.Add(11)
  795. errChan := make(chan error, 4)
  796. go func() {
  797. out, _, err := dockerCmdWithError("run", "syscall-test", "acct-test")
  798. if err == nil || !strings.Contains(out, "Operation not permitted") {
  799. errChan <- fmt.Errorf("expected Operation not permitted, got: %s", out)
  800. }
  801. group.Done()
  802. }()
  803. go func() {
  804. out, _, err := dockerCmdWithError("run", "--cap-add", "sys_admin", "syscall-test", "acct-test")
  805. if err == nil || !strings.Contains(out, "Operation not permitted") {
  806. errChan <- fmt.Errorf("expected Operation not permitted, got: %s", out)
  807. }
  808. group.Done()
  809. }()
  810. go func() {
  811. out, _, err := dockerCmdWithError("run", "--cap-add", "sys_pacct", "syscall-test", "acct-test")
  812. if err == nil || !strings.Contains(out, "No such file or directory") {
  813. errChan <- fmt.Errorf("expected No such file or directory, got: %s", out)
  814. }
  815. group.Done()
  816. }()
  817. go func() {
  818. out, _, err := dockerCmdWithError("run", "--cap-add", "ALL", "syscall-test", "acct-test")
  819. if err == nil || !strings.Contains(out, "No such file or directory") {
  820. errChan <- fmt.Errorf("expected No such file or directory, got: %s", out)
  821. }
  822. group.Done()
  823. }()
  824. go func() {
  825. out, _, err := dockerCmdWithError("run", "--cap-drop", "ALL", "--cap-add", "sys_pacct", "syscall-test", "acct-test")
  826. if err == nil || !strings.Contains(out, "No such file or directory") {
  827. errChan <- fmt.Errorf("expected No such file or directory, got: %s", out)
  828. }
  829. group.Done()
  830. }()
  831. go func() {
  832. out, _, err := dockerCmdWithError("run", "syscall-test", "ns-test", "echo", "hello0")
  833. if err == nil || !strings.Contains(out, "Operation not permitted") {
  834. errChan <- fmt.Errorf("expected Operation not permitted, got: %s", out)
  835. }
  836. group.Done()
  837. }()
  838. go func() {
  839. out, _, err := dockerCmdWithError("run", "--cap-add", "sys_admin", "syscall-test", "ns-test", "echo", "hello1")
  840. if err != nil || !strings.Contains(out, "hello1") {
  841. errChan <- fmt.Errorf("expected hello1, got: %s, %v", out, err)
  842. }
  843. group.Done()
  844. }()
  845. go func() {
  846. out, _, err := dockerCmdWithError("run", "--cap-drop", "all", "--cap-add", "sys_admin", "syscall-test", "ns-test", "echo", "hello2")
  847. if err != nil || !strings.Contains(out, "hello2") {
  848. errChan <- fmt.Errorf("expected hello2, got: %s, %v", out, err)
  849. }
  850. group.Done()
  851. }()
  852. go func() {
  853. out, _, err := dockerCmdWithError("run", "--cap-add", "ALL", "syscall-test", "ns-test", "echo", "hello3")
  854. if err != nil || !strings.Contains(out, "hello3") {
  855. errChan <- fmt.Errorf("expected hello3, got: %s, %v", out, err)
  856. }
  857. group.Done()
  858. }()
  859. go func() {
  860. out, _, err := dockerCmdWithError("run", "--cap-add", "ALL", "--security-opt", "seccomp=unconfined", "syscall-test", "acct-test")
  861. if err == nil || !strings.Contains(out, "No such file or directory") {
  862. errChan <- fmt.Errorf("expected No such file or directory, got: %s", out)
  863. }
  864. group.Done()
  865. }()
  866. go func() {
  867. out, _, err := dockerCmdWithError("run", "--cap-add", "ALL", "--security-opt", "seccomp=unconfined", "syscall-test", "ns-test", "echo", "hello4")
  868. if err != nil || !strings.Contains(out, "hello4") {
  869. errChan <- fmt.Errorf("expected hello4, got: %s, %v", out, err)
  870. }
  871. group.Done()
  872. }()
  873. group.Wait()
  874. close(errChan)
  875. for err := range errChan {
  876. c.Assert(err, checker.IsNil)
  877. }
  878. }
  879. // TestRunNoNewPrivSetuid checks that --security-opt=no-new-privileges prevents
  880. // effective uid transtions on executing setuid binaries.
  881. func (s *DockerSuite) TestRunNoNewPrivSetuid(c *check.C) {
  882. testRequires(c, DaemonIsLinux, NotUserNamespace, SameHostDaemon)
  883. // test that running a setuid binary results in no effective uid transition
  884. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "no-new-privileges", "--user", "1000", "nnp-test", "/usr/bin/nnp-test")
  885. if out, _, err := runCommandWithOutput(runCmd); err != nil || !strings.Contains(out, "EUID=1000") {
  886. c.Fatalf("expected output to contain EUID=1000, got %s: %v", out, err)
  887. }
  888. }
  889. func (s *DockerSuite) TestRunApparmorProcDirectory(c *check.C) {
  890. testRequires(c, SameHostDaemon, Apparmor)
  891. // running w seccomp unconfined tests the apparmor profile
  892. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/cgroup")
  893. if out, _, err := runCommandWithOutput(runCmd); err == nil || !(strings.Contains(out, "Permission denied") || strings.Contains(out, "Operation not permitted")) {
  894. c.Fatalf("expected chmod 777 /proc/1/cgroup to fail, got %s: %v", out, err)
  895. }
  896. runCmd = exec.Command(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/attr/current")
  897. if out, _, err := runCommandWithOutput(runCmd); err == nil || !(strings.Contains(out, "Permission denied") || strings.Contains(out, "Operation not permitted")) {
  898. c.Fatalf("expected chmod 777 /proc/1/attr/current to fail, got %s: %v", out, err)
  899. }
  900. }
  901. // make sure the default profile can be successfully parsed (using unshare as it is
  902. // something which we know is blocked in the default profile)
  903. func (s *DockerSuite) TestRunSeccompWithDefaultProfile(c *check.C) {
  904. testRequires(c, SameHostDaemon, seccompEnabled)
  905. out, _, err := dockerCmdWithError("run", "--security-opt", "seccomp=../profiles/seccomp/default.json", "debian:jessie", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami")
  906. c.Assert(err, checker.NotNil, check.Commentf(out))
  907. c.Assert(strings.TrimSpace(out), checker.Equals, "unshare: unshare failed: Operation not permitted")
  908. }
  909. // TestRunDeviceSymlink checks run with device that follows symlink (#13840 and #22271)
  910. func (s *DockerSuite) TestRunDeviceSymlink(c *check.C) {
  911. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm, SameHostDaemon)
  912. if _, err := os.Stat("/dev/zero"); err != nil {
  913. c.Skip("Host does not have /dev/zero")
  914. }
  915. // Create a temporary directory to create symlink
  916. tmpDir, err := ioutil.TempDir("", "docker_device_follow_symlink_tests")
  917. c.Assert(err, checker.IsNil)
  918. defer os.RemoveAll(tmpDir)
  919. // Create a symbolic link to /dev/zero
  920. symZero := filepath.Join(tmpDir, "zero")
  921. err = os.Symlink("/dev/zero", symZero)
  922. c.Assert(err, checker.IsNil)
  923. // Create a temporary file "temp" inside tmpDir, write some data to "tmpDir/temp",
  924. // then create a symlink "tmpDir/file" to the temporary file "tmpDir/temp".
  925. tmpFile := filepath.Join(tmpDir, "temp")
  926. err = ioutil.WriteFile(tmpFile, []byte("temp"), 0666)
  927. c.Assert(err, checker.IsNil)
  928. symFile := filepath.Join(tmpDir, "file")
  929. err = os.Symlink(tmpFile, symFile)
  930. c.Assert(err, checker.IsNil)
  931. // Create a symbolic link to /dev/zero, this time with a relative path (#22271)
  932. err = os.Symlink("zero", "/dev/symzero")
  933. if err != nil {
  934. c.Fatal("/dev/symzero creation failed")
  935. }
  936. // We need to remove this symbolic link here as it is created in /dev/, not temporary directory as above
  937. defer os.Remove("/dev/symzero")
  938. // md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23
  939. out, _ := dockerCmd(c, "run", "--device", symZero+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  940. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "bb7df04e1b0a2570657527a7e108ae23", check.Commentf("expected output bb7df04e1b0a2570657527a7e108ae23"))
  941. // symlink "tmpDir/file" to a file "tmpDir/temp" will result in an error as it is not a device.
  942. out, _, err = dockerCmdWithError("run", "--device", symFile+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  943. c.Assert(err, check.NotNil)
  944. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "not a device node", check.Commentf("expected output 'not a device node'"))
  945. // md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23 (this time check with relative path backed, see #22271)
  946. out, _ = dockerCmd(c, "run", "--device", "/dev/symzero:/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  947. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "bb7df04e1b0a2570657527a7e108ae23", check.Commentf("expected output bb7df04e1b0a2570657527a7e108ae23"))
  948. }
  949. // TestRunPidsLimit makes sure the pids cgroup is set with --pids-limit
  950. func (s *DockerSuite) TestRunPidsLimit(c *check.C) {
  951. testRequires(c, pidsLimit)
  952. file := "/sys/fs/cgroup/pids/pids.max"
  953. out, _ := dockerCmd(c, "run", "--name", "skittles", "--pids-limit", "2", "busybox", "cat", file)
  954. c.Assert(strings.TrimSpace(out), checker.Equals, "2")
  955. out = inspectField(c, "skittles", "HostConfig.PidsLimit")
  956. c.Assert(out, checker.Equals, "2", check.Commentf("setting the pids limit failed"))
  957. }
  958. func (s *DockerSuite) TestRunPrivilegedAllowedDevices(c *check.C) {
  959. testRequires(c, DaemonIsLinux, NotUserNamespace)
  960. file := "/sys/fs/cgroup/devices/devices.list"
  961. out, _ := dockerCmd(c, "run", "--privileged", "busybox", "cat", file)
  962. c.Logf("out: %q", out)
  963. c.Assert(strings.TrimSpace(out), checker.Equals, "a *:* rwm")
  964. }
  965. func (s *DockerSuite) TestRunUserDeviceAllowed(c *check.C) {
  966. testRequires(c, DaemonIsLinux)
  967. fi, err := os.Stat("/dev/snd/timer")
  968. if err != nil {
  969. c.Skip("Host does not have /dev/snd/timer")
  970. }
  971. stat, ok := fi.Sys().(*syscall.Stat_t)
  972. if !ok {
  973. c.Skip("Could not stat /dev/snd/timer")
  974. }
  975. file := "/sys/fs/cgroup/devices/devices.list"
  976. out, _ := dockerCmd(c, "run", "--device", "/dev/snd/timer:w", "busybox", "cat", file)
  977. c.Assert(out, checker.Contains, fmt.Sprintf("c %d:%d w", stat.Rdev/256, stat.Rdev%256))
  978. }