docker_cli_run_unix_test.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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 = inspectField(c, "test", "HostConfig.CpuPeriod")
  350. c.Assert(out, checker.Equals, "50000", check.Commentf("setting the CPU CFS period failed"))
  351. }
  352. func (s *DockerSuite) TestRunWithKernelMemory(c *check.C) {
  353. testRequires(c, kernelMemorySupport)
  354. file := "/sys/fs/cgroup/memory/memory.kmem.limit_in_bytes"
  355. stdout, _, _ := dockerCmdWithStdoutStderr(c, "run", "--kernel-memory", "50M", "--name", "test1", "busybox", "cat", file)
  356. c.Assert(strings.TrimSpace(stdout), checker.Equals, "52428800")
  357. out := inspectField(c, "test1", "HostConfig.KernelMemory")
  358. c.Assert(out, check.Equals, "52428800")
  359. }
  360. func (s *DockerSuite) TestRunWithInvalidKernelMemory(c *check.C) {
  361. testRequires(c, kernelMemorySupport)
  362. out, _, err := dockerCmdWithError("run", "--kernel-memory", "2M", "busybox", "true")
  363. c.Assert(err, check.NotNil)
  364. expected := "Minimum kernel memory limit allowed is 4MB"
  365. c.Assert(out, checker.Contains, expected)
  366. out, _, err = dockerCmdWithError("run", "--kernel-memory", "-16m", "--name", "test2", "busybox", "echo", "test")
  367. c.Assert(err, check.NotNil)
  368. expected = "invalid size"
  369. c.Assert(out, checker.Contains, expected)
  370. }
  371. func (s *DockerSuite) TestRunWithCPUShares(c *check.C) {
  372. testRequires(c, cpuShare)
  373. file := "/sys/fs/cgroup/cpu/cpu.shares"
  374. out, _ := dockerCmd(c, "run", "--cpu-shares", "1000", "--name", "test", "busybox", "cat", file)
  375. c.Assert(strings.TrimSpace(out), checker.Equals, "1000")
  376. out = inspectField(c, "test", "HostConfig.CPUShares")
  377. c.Assert(out, check.Equals, "1000")
  378. }
  379. // "test" should be printed
  380. func (s *DockerSuite) TestRunEchoStdoutWithCPUSharesAndMemoryLimit(c *check.C) {
  381. testRequires(c, cpuShare)
  382. testRequires(c, memoryLimitSupport)
  383. out, _, _ := dockerCmdWithStdoutStderr(c, "run", "--cpu-shares", "1000", "-m", "32m", "busybox", "echo", "test")
  384. c.Assert(out, checker.Equals, "test\n", check.Commentf("container should've printed 'test'"))
  385. }
  386. func (s *DockerSuite) TestRunWithCpusetCpus(c *check.C) {
  387. testRequires(c, cgroupCpuset)
  388. file := "/sys/fs/cgroup/cpuset/cpuset.cpus"
  389. out, _ := dockerCmd(c, "run", "--cpuset-cpus", "0", "--name", "test", "busybox", "cat", file)
  390. c.Assert(strings.TrimSpace(out), checker.Equals, "0")
  391. out = inspectField(c, "test", "HostConfig.CpusetCpus")
  392. c.Assert(out, check.Equals, "0")
  393. }
  394. func (s *DockerSuite) TestRunWithCpusetMems(c *check.C) {
  395. testRequires(c, cgroupCpuset)
  396. file := "/sys/fs/cgroup/cpuset/cpuset.mems"
  397. out, _ := dockerCmd(c, "run", "--cpuset-mems", "0", "--name", "test", "busybox", "cat", file)
  398. c.Assert(strings.TrimSpace(out), checker.Equals, "0")
  399. out = inspectField(c, "test", "HostConfig.CpusetMems")
  400. c.Assert(out, check.Equals, "0")
  401. }
  402. func (s *DockerSuite) TestRunWithBlkioWeight(c *check.C) {
  403. testRequires(c, blkioWeight)
  404. file := "/sys/fs/cgroup/blkio/blkio.weight"
  405. out, _ := dockerCmd(c, "run", "--blkio-weight", "300", "--name", "test", "busybox", "cat", file)
  406. c.Assert(strings.TrimSpace(out), checker.Equals, "300")
  407. out = inspectField(c, "test", "HostConfig.BlkioWeight")
  408. c.Assert(out, check.Equals, "300")
  409. }
  410. func (s *DockerSuite) TestRunWithInvalidBlkioWeight(c *check.C) {
  411. testRequires(c, blkioWeight)
  412. out, _, err := dockerCmdWithError("run", "--blkio-weight", "5", "busybox", "true")
  413. c.Assert(err, check.NotNil, check.Commentf(out))
  414. expected := "Range of blkio weight is from 10 to 1000"
  415. c.Assert(out, checker.Contains, expected)
  416. }
  417. func (s *DockerSuite) TestRunWithInvalidPathforBlkioWeightDevice(c *check.C) {
  418. testRequires(c, blkioWeight)
  419. out, _, err := dockerCmdWithError("run", "--blkio-weight-device", "/dev/sdX:100", "busybox", "true")
  420. c.Assert(err, check.NotNil, check.Commentf(out))
  421. }
  422. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceReadBps(c *check.C) {
  423. testRequires(c, blkioWeight)
  424. out, _, err := dockerCmdWithError("run", "--device-read-bps", "/dev/sdX:500", "busybox", "true")
  425. c.Assert(err, check.NotNil, check.Commentf(out))
  426. }
  427. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceWriteBps(c *check.C) {
  428. testRequires(c, blkioWeight)
  429. out, _, err := dockerCmdWithError("run", "--device-write-bps", "/dev/sdX:500", "busybox", "true")
  430. c.Assert(err, check.NotNil, check.Commentf(out))
  431. }
  432. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceReadIOps(c *check.C) {
  433. testRequires(c, blkioWeight)
  434. out, _, err := dockerCmdWithError("run", "--device-read-iops", "/dev/sdX:500", "busybox", "true")
  435. c.Assert(err, check.NotNil, check.Commentf(out))
  436. }
  437. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceWriteIOps(c *check.C) {
  438. testRequires(c, blkioWeight)
  439. out, _, err := dockerCmdWithError("run", "--device-write-iops", "/dev/sdX:500", "busybox", "true")
  440. c.Assert(err, check.NotNil, check.Commentf(out))
  441. }
  442. func (s *DockerSuite) TestRunOOMExitCode(c *check.C) {
  443. testRequires(c, oomControl)
  444. errChan := make(chan error)
  445. go func() {
  446. defer close(errChan)
  447. //changing memory to 40MB from 4MB due to an issue with GCCGO that test fails to start the container.
  448. out, exitCode, _ := dockerCmdWithError("run", "-m", "40MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done")
  449. if expected := 137; exitCode != expected {
  450. errChan <- fmt.Errorf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out)
  451. }
  452. }()
  453. select {
  454. case err := <-errChan:
  455. c.Assert(err, check.IsNil)
  456. case <-time.After(600 * time.Second):
  457. c.Fatal("Timeout waiting for container to die on OOM")
  458. }
  459. }
  460. func (s *DockerSuite) TestRunWithMemoryLimit(c *check.C) {
  461. testRequires(c, memoryLimitSupport)
  462. file := "/sys/fs/cgroup/memory/memory.limit_in_bytes"
  463. stdout, _, _ := dockerCmdWithStdoutStderr(c, "run", "-m", "32M", "--name", "test", "busybox", "cat", file)
  464. c.Assert(strings.TrimSpace(stdout), checker.Equals, "33554432")
  465. out := inspectField(c, "test", "HostConfig.Memory")
  466. c.Assert(out, check.Equals, "33554432")
  467. }
  468. // TestRunWithoutMemoryswapLimit sets memory limit and disables swap
  469. // memory limit, this means the processes in the container can use
  470. // 16M memory and as much swap memory as they need (if the host
  471. // supports swap memory).
  472. func (s *DockerSuite) TestRunWithoutMemoryswapLimit(c *check.C) {
  473. testRequires(c, DaemonIsLinux)
  474. testRequires(c, memoryLimitSupport)
  475. testRequires(c, swapMemorySupport)
  476. dockerCmd(c, "run", "-m", "32m", "--memory-swap", "-1", "busybox", "true")
  477. }
  478. func (s *DockerSuite) TestRunWithSwappiness(c *check.C) {
  479. testRequires(c, memorySwappinessSupport)
  480. file := "/sys/fs/cgroup/memory/memory.swappiness"
  481. out, _ := dockerCmd(c, "run", "--memory-swappiness", "0", "--name", "test", "busybox", "cat", file)
  482. c.Assert(strings.TrimSpace(out), checker.Equals, "0")
  483. out = inspectField(c, "test", "HostConfig.MemorySwappiness")
  484. c.Assert(out, check.Equals, "0")
  485. }
  486. func (s *DockerSuite) TestRunWithSwappinessInvalid(c *check.C) {
  487. testRequires(c, memorySwappinessSupport)
  488. out, _, err := dockerCmdWithError("run", "--memory-swappiness", "101", "busybox", "true")
  489. c.Assert(err, check.NotNil)
  490. expected := "Valid memory swappiness range is 0-100"
  491. c.Assert(out, checker.Contains, expected, check.Commentf("Expected output to contain %q, not %q", out, expected))
  492. out, _, err = dockerCmdWithError("run", "--memory-swappiness", "-10", "busybox", "true")
  493. c.Assert(err, check.NotNil)
  494. c.Assert(out, checker.Contains, expected, check.Commentf("Expected output to contain %q, not %q", out, expected))
  495. }
  496. func (s *DockerSuite) TestRunWithMemoryReservation(c *check.C) {
  497. testRequires(c, memoryReservationSupport)
  498. file := "/sys/fs/cgroup/memory/memory.soft_limit_in_bytes"
  499. out, _ := dockerCmd(c, "run", "--memory-reservation", "200M", "--name", "test", "busybox", "cat", file)
  500. c.Assert(strings.TrimSpace(out), checker.Equals, "209715200")
  501. out = inspectField(c, "test", "HostConfig.MemoryReservation")
  502. c.Assert(out, check.Equals, "209715200")
  503. }
  504. func (s *DockerSuite) TestRunWithMemoryReservationInvalid(c *check.C) {
  505. testRequires(c, memoryLimitSupport)
  506. testRequires(c, memoryReservationSupport)
  507. out, _, err := dockerCmdWithError("run", "-m", "500M", "--memory-reservation", "800M", "busybox", "true")
  508. c.Assert(err, check.NotNil)
  509. expected := "Minimum memory limit should be larger than memory reservation limit"
  510. c.Assert(strings.TrimSpace(out), checker.Contains, expected, check.Commentf("run container should fail with invalid memory reservation"))
  511. out, _, err = dockerCmdWithError("run", "--memory-reservation", "1k", "busybox", "true")
  512. c.Assert(err, check.NotNil)
  513. expected = "Minimum memory reservation allowed is 4MB"
  514. c.Assert(strings.TrimSpace(out), checker.Contains, expected, check.Commentf("run container should fail with invalid memory reservation"))
  515. }
  516. func (s *DockerSuite) TestStopContainerSignal(c *check.C) {
  517. 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`)
  518. containerID := strings.TrimSpace(out)
  519. c.Assert(waitRun(containerID), checker.IsNil)
  520. dockerCmd(c, "stop", containerID)
  521. out, _ = dockerCmd(c, "logs", containerID)
  522. c.Assert(out, checker.Contains, "exit trapped", check.Commentf("Expected `exit trapped` in the log"))
  523. }
  524. func (s *DockerSuite) TestRunSwapLessThanMemoryLimit(c *check.C) {
  525. testRequires(c, memoryLimitSupport)
  526. testRequires(c, swapMemorySupport)
  527. out, _, err := dockerCmdWithError("run", "-m", "16m", "--memory-swap", "15m", "busybox", "echo", "test")
  528. expected := "Minimum memoryswap limit should be larger than memory limit"
  529. c.Assert(err, check.NotNil)
  530. c.Assert(out, checker.Contains, expected)
  531. }
  532. func (s *DockerSuite) TestRunInvalidCpusetCpusFlagValue(c *check.C) {
  533. testRequires(c, cgroupCpuset, SameHostDaemon)
  534. sysInfo := sysinfo.New(true)
  535. cpus, err := parsers.ParseUintList(sysInfo.Cpus)
  536. c.Assert(err, check.IsNil)
  537. var invalid int
  538. for i := 0; i <= len(cpus)+1; i++ {
  539. if !cpus[i] {
  540. invalid = i
  541. break
  542. }
  543. }
  544. out, _, err := dockerCmdWithError("run", "--cpuset-cpus", strconv.Itoa(invalid), "busybox", "true")
  545. c.Assert(err, check.NotNil)
  546. expected := fmt.Sprintf("Error response from daemon: Requested CPUs are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Cpus)
  547. c.Assert(out, checker.Contains, expected)
  548. }
  549. func (s *DockerSuite) TestRunInvalidCpusetMemsFlagValue(c *check.C) {
  550. testRequires(c, cgroupCpuset)
  551. sysInfo := sysinfo.New(true)
  552. mems, err := parsers.ParseUintList(sysInfo.Mems)
  553. c.Assert(err, check.IsNil)
  554. var invalid int
  555. for i := 0; i <= len(mems)+1; i++ {
  556. if !mems[i] {
  557. invalid = i
  558. break
  559. }
  560. }
  561. out, _, err := dockerCmdWithError("run", "--cpuset-mems", strconv.Itoa(invalid), "busybox", "true")
  562. c.Assert(err, check.NotNil)
  563. expected := fmt.Sprintf("Error response from daemon: Requested memory nodes are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Mems)
  564. c.Assert(out, checker.Contains, expected)
  565. }
  566. func (s *DockerSuite) TestRunInvalidCPUShares(c *check.C) {
  567. testRequires(c, cpuShare, DaemonIsLinux)
  568. out, _, err := dockerCmdWithError("run", "--cpu-shares", "1", "busybox", "echo", "test")
  569. c.Assert(err, check.NotNil, check.Commentf(out))
  570. expected := "The minimum allowed cpu-shares is 2"
  571. c.Assert(out, checker.Contains, expected)
  572. out, _, err = dockerCmdWithError("run", "--cpu-shares", "-1", "busybox", "echo", "test")
  573. c.Assert(err, check.NotNil, check.Commentf(out))
  574. expected = "shares: invalid argument"
  575. c.Assert(out, checker.Contains, expected)
  576. out, _, err = dockerCmdWithError("run", "--cpu-shares", "99999999", "busybox", "echo", "test")
  577. c.Assert(err, check.NotNil, check.Commentf(out))
  578. expected = "The maximum allowed cpu-shares is"
  579. c.Assert(out, checker.Contains, expected)
  580. }
  581. func (s *DockerSuite) TestRunWithDefaultShmSize(c *check.C) {
  582. testRequires(c, DaemonIsLinux)
  583. name := "shm-default"
  584. out, _ := dockerCmd(c, "run", "--name", name, "busybox", "mount")
  585. shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  586. if !shmRegex.MatchString(out) {
  587. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  588. }
  589. shmSize := inspectField(c, name, "HostConfig.ShmSize")
  590. c.Assert(shmSize, check.Equals, "67108864")
  591. }
  592. func (s *DockerSuite) TestRunWithShmSize(c *check.C) {
  593. testRequires(c, DaemonIsLinux)
  594. name := "shm"
  595. out, _ := dockerCmd(c, "run", "--name", name, "--shm-size=1G", "busybox", "mount")
  596. shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=1048576k`)
  597. if !shmRegex.MatchString(out) {
  598. c.Fatalf("Expected shm of 1GB in mount command, got %v", out)
  599. }
  600. shmSize := inspectField(c, name, "HostConfig.ShmSize")
  601. c.Assert(shmSize, check.Equals, "1073741824")
  602. }
  603. func (s *DockerSuite) TestRunTmpfsMounts(c *check.C) {
  604. // TODO Windows (Post TP5): This test cannot run on a Windows daemon as
  605. // Windows does not support tmpfs mounts.
  606. testRequires(c, DaemonIsLinux)
  607. if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run", "busybox", "touch", "/run/somefile"); err != nil {
  608. c.Fatalf("/run directory not mounted on tmpfs %q %s", err, out)
  609. }
  610. if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run:noexec", "busybox", "touch", "/run/somefile"); err != nil {
  611. c.Fatalf("/run directory not mounted on tmpfs %q %s", err, out)
  612. }
  613. if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run:noexec,nosuid,rw,size=5k,mode=700", "busybox", "touch", "/run/somefile"); err != nil {
  614. c.Fatalf("/run failed to mount on tmpfs with valid options %q %s", err, out)
  615. }
  616. if _, _, err := dockerCmdWithError("run", "--tmpfs", "/run:foobar", "busybox", "touch", "/run/somefile"); err == nil {
  617. c.Fatalf("/run mounted on tmpfs when it should have vailed within invalid mount option")
  618. }
  619. if _, _, err := dockerCmdWithError("run", "--tmpfs", "/run", "-v", "/run:/run", "busybox", "touch", "/run/somefile"); err == nil {
  620. c.Fatalf("Should have generated an error saying Duplicate mount points")
  621. }
  622. }
  623. func (s *DockerSuite) TestRunSysctls(c *check.C) {
  624. testRequires(c, DaemonIsLinux)
  625. var err error
  626. out, _ := dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=1", "--name", "test", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward")
  627. c.Assert(strings.TrimSpace(out), check.Equals, "1")
  628. out = inspectFieldJSON(c, "test", "HostConfig.Sysctls")
  629. sysctls := make(map[string]string)
  630. err = json.Unmarshal([]byte(out), &sysctls)
  631. c.Assert(err, check.IsNil)
  632. c.Assert(sysctls["net.ipv4.ip_forward"], check.Equals, "1")
  633. out, _ = dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=0", "--name", "test1", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward")
  634. c.Assert(strings.TrimSpace(out), check.Equals, "0")
  635. out = inspectFieldJSON(c, "test1", "HostConfig.Sysctls")
  636. err = json.Unmarshal([]byte(out), &sysctls)
  637. c.Assert(err, check.IsNil)
  638. c.Assert(sysctls["net.ipv4.ip_forward"], check.Equals, "0")
  639. runCmd := exec.Command(dockerBinary, "run", "--sysctl", "kernel.foobar=1", "--name", "test2", "busybox", "cat", "/proc/sys/kernel/foobar")
  640. out, _, _ = runCommandWithOutput(runCmd)
  641. if !strings.Contains(out, "invalid value") {
  642. c.Fatalf("expected --sysctl to fail, got %s", out)
  643. }
  644. }
  645. // TestRunSeccompProfileDenyUnshare checks that 'docker run --security-opt seccomp=/tmp/profile.json debian:jessie unshare' exits with operation not permitted.
  646. func (s *DockerSuite) TestRunSeccompProfileDenyUnshare(c *check.C) {
  647. testRequires(c, SameHostDaemon, seccompEnabled, NotArm, Apparmor)
  648. jsonData := `{
  649. "defaultAction": "SCMP_ACT_ALLOW",
  650. "syscalls": [
  651. {
  652. "name": "unshare",
  653. "action": "SCMP_ACT_ERRNO"
  654. }
  655. ]
  656. }`
  657. tmpFile, err := ioutil.TempFile("", "profile.json")
  658. defer tmpFile.Close()
  659. if err != nil {
  660. c.Fatal(err)
  661. }
  662. if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
  663. c.Fatal(err)
  664. }
  665. 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")
  666. out, _, _ := runCommandWithOutput(runCmd)
  667. if !strings.Contains(out, "Operation not permitted") {
  668. c.Fatalf("expected unshare with seccomp profile denied to fail, got %s", out)
  669. }
  670. }
  671. // TestRunSeccompProfileDenyChmod checks that 'docker run --security-opt seccomp=/tmp/profile.json busybox chmod 400 /etc/hostname' exits with operation not permitted.
  672. func (s *DockerSuite) TestRunSeccompProfileDenyChmod(c *check.C) {
  673. testRequires(c, SameHostDaemon, seccompEnabled)
  674. jsonData := `{
  675. "defaultAction": "SCMP_ACT_ALLOW",
  676. "syscalls": [
  677. {
  678. "name": "chmod",
  679. "action": "SCMP_ACT_ERRNO"
  680. }
  681. ]
  682. }`
  683. tmpFile, err := ioutil.TempFile("", "profile.json")
  684. defer tmpFile.Close()
  685. if err != nil {
  686. c.Fatal(err)
  687. }
  688. if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
  689. c.Fatal(err)
  690. }
  691. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "400", "/etc/hostname")
  692. out, _, _ := runCommandWithOutput(runCmd)
  693. if !strings.Contains(out, "Operation not permitted") {
  694. c.Fatalf("expected chmod with seccomp profile denied to fail, got %s", out)
  695. }
  696. }
  697. // TestRunSeccompProfileDenyUnshareUserns checks that 'docker run debian:jessie unshare --map-root-user --user sh -c whoami' with a specific profile to
  698. // deny unhare of a userns exits with operation not permitted.
  699. func (s *DockerSuite) TestRunSeccompProfileDenyUnshareUserns(c *check.C) {
  700. testRequires(c, SameHostDaemon, seccompEnabled, NotArm, Apparmor)
  701. // from sched.h
  702. jsonData := fmt.Sprintf(`{
  703. "defaultAction": "SCMP_ACT_ALLOW",
  704. "syscalls": [
  705. {
  706. "name": "unshare",
  707. "action": "SCMP_ACT_ERRNO",
  708. "args": [
  709. {
  710. "index": 0,
  711. "value": %d,
  712. "op": "SCMP_CMP_EQ"
  713. }
  714. ]
  715. }
  716. ]
  717. }`, uint64(0x10000000))
  718. tmpFile, err := ioutil.TempFile("", "profile.json")
  719. defer tmpFile.Close()
  720. if err != nil {
  721. c.Fatal(err)
  722. }
  723. if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
  724. c.Fatal(err)
  725. }
  726. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "apparmor=unconfined", "--security-opt", "seccomp="+tmpFile.Name(), "debian:jessie", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami")
  727. out, _, _ := runCommandWithOutput(runCmd)
  728. if !strings.Contains(out, "Operation not permitted") {
  729. c.Fatalf("expected unshare userns with seccomp profile denied to fail, got %s", out)
  730. }
  731. }
  732. // TestRunSeccompProfileDenyCloneUserns checks that 'docker run syscall-test'
  733. // with a the default seccomp profile exits with operation not permitted.
  734. func (s *DockerSuite) TestRunSeccompProfileDenyCloneUserns(c *check.C) {
  735. testRequires(c, SameHostDaemon, seccompEnabled)
  736. runCmd := exec.Command(dockerBinary, "run", "syscall-test", "userns-test", "id")
  737. out, _, err := runCommandWithOutput(runCmd)
  738. if err == nil || !strings.Contains(out, "clone failed: Operation not permitted") {
  739. c.Fatalf("expected clone userns with default seccomp profile denied to fail, got %s: %v", out, err)
  740. }
  741. }
  742. // TestRunSeccompUnconfinedCloneUserns checks that
  743. // 'docker run --security-opt seccomp=unconfined syscall-test' allows creating a userns.
  744. func (s *DockerSuite) TestRunSeccompUnconfinedCloneUserns(c *check.C) {
  745. testRequires(c, SameHostDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace)
  746. // make sure running w privileged is ok
  747. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "syscall-test", "userns-test", "id")
  748. if out, _, err := runCommandWithOutput(runCmd); err != nil || !strings.Contains(out, "nobody") {
  749. c.Fatalf("expected clone userns with --security-opt seccomp=unconfined to succeed, got %s: %v", out, err)
  750. }
  751. }
  752. // TestRunSeccompAllowPrivCloneUserns checks that 'docker run --privileged syscall-test'
  753. // allows creating a userns.
  754. func (s *DockerSuite) TestRunSeccompAllowPrivCloneUserns(c *check.C) {
  755. testRequires(c, SameHostDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace)
  756. // make sure running w privileged is ok
  757. runCmd := exec.Command(dockerBinary, "run", "--privileged", "syscall-test", "userns-test", "id")
  758. if out, _, err := runCommandWithOutput(runCmd); err != nil || !strings.Contains(out, "nobody") {
  759. c.Fatalf("expected clone userns with --privileged to succeed, got %s: %v", out, err)
  760. }
  761. }
  762. // TestRunSeccompAllowSetrlimit checks that 'docker run debian:jessie ulimit -v 1048510' succeeds.
  763. func (s *DockerSuite) TestRunSeccompAllowSetrlimit(c *check.C) {
  764. testRequires(c, SameHostDaemon, seccompEnabled)
  765. // ulimit uses setrlimit, so we want to make sure we don't break it
  766. runCmd := exec.Command(dockerBinary, "run", "debian:jessie", "bash", "-c", "ulimit -v 1048510")
  767. if out, _, err := runCommandWithOutput(runCmd); err != nil {
  768. c.Fatalf("expected ulimit with seccomp to succeed, got %s: %v", out, err)
  769. }
  770. }
  771. func (s *DockerSuite) TestRunSeccompDefaultProfile(c *check.C) {
  772. testRequires(c, SameHostDaemon, seccompEnabled, NotUserNamespace)
  773. var group sync.WaitGroup
  774. group.Add(4)
  775. errChan := make(chan error, 4)
  776. go func() {
  777. out, _, err := dockerCmdWithError("run", "--cap-add", "ALL", "syscall-test", "acct-test")
  778. if err == nil || !strings.Contains(out, "Operation not permitted") {
  779. errChan <- fmt.Errorf("expected Operation not permitted, got: %s", out)
  780. }
  781. group.Done()
  782. }()
  783. go func() {
  784. out, _, err := dockerCmdWithError("run", "--cap-add", "ALL", "syscall-test", "ns-test", "echo", "hello")
  785. if err == nil || !strings.Contains(out, "Operation not permitted") {
  786. errChan <- fmt.Errorf("expected Operation not permitted, got: %s", out)
  787. }
  788. group.Done()
  789. }()
  790. go func() {
  791. out, _, err := dockerCmdWithError("run", "--cap-add", "ALL", "--security-opt", "seccomp=unconfined", "syscall-test", "acct-test")
  792. if err == nil || !strings.Contains(out, "No such file or directory") {
  793. errChan <- fmt.Errorf("expected No such file or directory, got: %s", out)
  794. }
  795. group.Done()
  796. }()
  797. go func() {
  798. out, _, err := dockerCmdWithError("run", "--cap-add", "ALL", "--security-opt", "seccomp=unconfined", "syscall-test", "ns-test", "echo", "hello")
  799. if err != nil || !strings.Contains(out, "hello") {
  800. errChan <- fmt.Errorf("expected hello, got: %s, %v", out, err)
  801. }
  802. group.Done()
  803. }()
  804. group.Wait()
  805. close(errChan)
  806. for err := range errChan {
  807. c.Assert(err, checker.IsNil)
  808. }
  809. }
  810. // TestRunNoNewPrivSetuid checks that --security-opt=no-new-privileges prevents
  811. // effective uid transtions on executing setuid binaries.
  812. func (s *DockerSuite) TestRunNoNewPrivSetuid(c *check.C) {
  813. testRequires(c, DaemonIsLinux, NotUserNamespace, SameHostDaemon)
  814. // test that running a setuid binary results in no effective uid transition
  815. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "no-new-privileges", "--user", "1000", "nnp-test", "/usr/bin/nnp-test")
  816. if out, _, err := runCommandWithOutput(runCmd); err != nil || !strings.Contains(out, "EUID=1000") {
  817. c.Fatalf("expected output to contain EUID=1000, got %s: %v", out, err)
  818. }
  819. }
  820. func (s *DockerSuite) TestRunApparmorProcDirectory(c *check.C) {
  821. testRequires(c, SameHostDaemon, Apparmor)
  822. // running w seccomp unconfined tests the apparmor profile
  823. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/cgroup")
  824. if out, _, err := runCommandWithOutput(runCmd); err == nil || !(strings.Contains(out, "Permission denied") || strings.Contains(out, "Operation not permitted")) {
  825. c.Fatalf("expected chmod 777 /proc/1/cgroup to fail, got %s: %v", out, err)
  826. }
  827. runCmd = exec.Command(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/attr/current")
  828. if out, _, err := runCommandWithOutput(runCmd); err == nil || !(strings.Contains(out, "Permission denied") || strings.Contains(out, "Operation not permitted")) {
  829. c.Fatalf("expected chmod 777 /proc/1/attr/current to fail, got %s: %v", out, err)
  830. }
  831. }
  832. // make sure the default profile can be successfully parsed (using unshare as it is
  833. // something which we know is blocked in the default profile)
  834. func (s *DockerSuite) TestRunSeccompWithDefaultProfile(c *check.C) {
  835. testRequires(c, SameHostDaemon, seccompEnabled)
  836. out, _, err := dockerCmdWithError("run", "--security-opt", "seccomp=../profiles/seccomp/default.json", "debian:jessie", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami")
  837. c.Assert(err, checker.NotNil, check.Commentf(out))
  838. c.Assert(strings.TrimSpace(out), checker.Equals, "unshare: unshare failed: Operation not permitted")
  839. }
  840. // TestRunDeviceSymlink checks run with device that follows symlink (#13840)
  841. func (s *DockerSuite) TestRunDeviceSymlink(c *check.C) {
  842. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm, SameHostDaemon)
  843. if _, err := os.Stat("/dev/zero"); err != nil {
  844. c.Skip("Host does not have /dev/zero")
  845. }
  846. // Create a temporary directory to create symlink
  847. tmpDir, err := ioutil.TempDir("", "docker_device_follow_symlink_tests")
  848. c.Assert(err, checker.IsNil)
  849. defer os.RemoveAll(tmpDir)
  850. // Create a symbolic link to /dev/zero
  851. symZero := filepath.Join(tmpDir, "zero")
  852. err = os.Symlink("/dev/zero", symZero)
  853. c.Assert(err, checker.IsNil)
  854. // Create a temporary file "temp" inside tmpDir, write some data to "tmpDir/temp",
  855. // then create a symlink "tmpDir/file" to the temporary file "tmpDir/temp".
  856. tmpFile := filepath.Join(tmpDir, "temp")
  857. err = ioutil.WriteFile(tmpFile, []byte("temp"), 0666)
  858. c.Assert(err, checker.IsNil)
  859. symFile := filepath.Join(tmpDir, "file")
  860. err = os.Symlink(tmpFile, symFile)
  861. c.Assert(err, checker.IsNil)
  862. // md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23
  863. out, _ := dockerCmd(c, "run", "--device", symZero+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  864. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "bb7df04e1b0a2570657527a7e108ae23", check.Commentf("expected output bb7df04e1b0a2570657527a7e108ae23"))
  865. // symlink "tmpDir/file" to a file "tmpDir/temp" will result in an error as it is not a device.
  866. out, _, err = dockerCmdWithError("run", "--device", symFile+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  867. c.Assert(err, check.NotNil)
  868. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "not a device node", check.Commentf("expected output 'not a device node'"))
  869. }
  870. // TestRunPidsLimit makes sure the pids cgroup is set with --pids-limit
  871. func (s *DockerSuite) TestRunPidsLimit(c *check.C) {
  872. testRequires(c, pidsLimit)
  873. file := "/sys/fs/cgroup/pids/pids.max"
  874. out, _ := dockerCmd(c, "run", "--name", "skittles", "--pids-limit", "2", "busybox", "cat", file)
  875. c.Assert(strings.TrimSpace(out), checker.Equals, "2")
  876. out = inspectField(c, "skittles", "HostConfig.PidsLimit")
  877. c.Assert(out, checker.Equals, "2", check.Commentf("setting the pids limit failed"))
  878. }
  879. func (s *DockerSuite) TestRunPrivilegedAllowedDevices(c *check.C) {
  880. testRequires(c, DaemonIsLinux, NotUserNamespace)
  881. file := "/sys/fs/cgroup/devices/devices.list"
  882. out, _ := dockerCmd(c, "run", "--privileged", "busybox", "cat", file)
  883. c.Logf("out: %q", out)
  884. c.Assert(strings.TrimSpace(out), checker.Equals, "a *:* rwm")
  885. }
  886. func (s *DockerSuite) TestRunUserDeviceAllowed(c *check.C) {
  887. testRequires(c, DaemonIsLinux)
  888. fi, err := os.Stat("/dev/snd/timer")
  889. if err != nil {
  890. c.Skip("Host does not have /dev/snd/timer")
  891. }
  892. stat, ok := fi.Sys().(*syscall.Stat_t)
  893. if !ok {
  894. c.Skip("Could not stat /dev/snd/timer")
  895. }
  896. file := "/sys/fs/cgroup/devices/devices.list"
  897. out, _ := dockerCmd(c, "run", "--device", "/dev/snd/timer:w", "busybox", "cat", file)
  898. c.Assert(out, checker.Contains, fmt.Sprintf("c %d:%d w", stat.Rdev/256, stat.Rdev%256))
  899. }