docker_cli_run_unix_test.go 45 KB

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