docker_cli_run_unix_test.go 43 KB

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