docker_cli_run_unix_test.go 36 KB

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