docker_cli_run_unix_test.go 45 KB

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