docker_cli_run_unix_test.go 40 KB

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