docker_cli_run_unix_test.go 37 KB

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