docker_cli_run_unix_test.go 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  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"}
  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. c.Assert(out, checker.Not(checker.Contains), "size=")
  702. expectedOptions = []string{"rw", "nosuid", "nodev", "noexec", "relatime"}
  703. out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
  704. for _, option := range expectedOptions {
  705. c.Assert(out, checker.Contains, option)
  706. }
  707. c.Assert(out, checker.Not(checker.Contains), "size=")
  708. expectedOptions = []string{"rw", "nosuid", "nodev", "relatime", "size=8192k"}
  709. out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw,exec,size=8192k", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
  710. for _, option := range expectedOptions {
  711. c.Assert(out, checker.Contains, option)
  712. }
  713. expectedOptions = []string{"rw", "nosuid", "nodev", "noexec", "relatime", "size=4096k"}
  714. out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw,size=8192k,exec,size=4096k,noexec", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
  715. for _, option := range expectedOptions {
  716. c.Assert(out, checker.Contains, option)
  717. }
  718. // We use debian:jessie as there is no findmnt in busybox. Also the output will be in the format of
  719. // TARGET PROPAGATION
  720. // /tmp shared
  721. // so we only capture `shared` here.
  722. expectedOptions = []string{"shared"}
  723. out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:shared", "debian:jessie", "findmnt", "-o", "TARGET,PROPAGATION", "/tmp")
  724. for _, option := range expectedOptions {
  725. c.Assert(out, checker.Contains, option)
  726. }
  727. }
  728. func (s *DockerSuite) TestRunSysctls(c *check.C) {
  729. testRequires(c, DaemonIsLinux)
  730. var err error
  731. out, _ := dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=1", "--name", "test", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward")
  732. c.Assert(strings.TrimSpace(out), check.Equals, "1")
  733. out = inspectFieldJSON(c, "test", "HostConfig.Sysctls")
  734. sysctls := make(map[string]string)
  735. err = json.Unmarshal([]byte(out), &sysctls)
  736. c.Assert(err, check.IsNil)
  737. c.Assert(sysctls["net.ipv4.ip_forward"], check.Equals, "1")
  738. out, _ = dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=0", "--name", "test1", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward")
  739. c.Assert(strings.TrimSpace(out), check.Equals, "0")
  740. out = inspectFieldJSON(c, "test1", "HostConfig.Sysctls")
  741. err = json.Unmarshal([]byte(out), &sysctls)
  742. c.Assert(err, check.IsNil)
  743. c.Assert(sysctls["net.ipv4.ip_forward"], check.Equals, "0")
  744. runCmd := exec.Command(dockerBinary, "run", "--sysctl", "kernel.foobar=1", "--name", "test2", "busybox", "cat", "/proc/sys/kernel/foobar")
  745. out, _, _ = runCommandWithOutput(runCmd)
  746. if !strings.Contains(out, "invalid argument") {
  747. c.Fatalf("expected --sysctl to fail, got %s", out)
  748. }
  749. }
  750. // TestRunSeccompProfileDenyUnshare checks that 'docker run --security-opt seccomp=/tmp/profile.json debian:jessie unshare' exits with operation not permitted.
  751. func (s *DockerSuite) TestRunSeccompProfileDenyUnshare(c *check.C) {
  752. testRequires(c, SameHostDaemon, seccompEnabled, NotArm, Apparmor)
  753. jsonData := `{
  754. "defaultAction": "SCMP_ACT_ALLOW",
  755. "syscalls": [
  756. {
  757. "name": "unshare",
  758. "action": "SCMP_ACT_ERRNO"
  759. }
  760. ]
  761. }`
  762. tmpFile, err := ioutil.TempFile("", "profile.json")
  763. defer tmpFile.Close()
  764. if err != nil {
  765. c.Fatal(err)
  766. }
  767. if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
  768. c.Fatal(err)
  769. }
  770. 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")
  771. out, _, _ := runCommandWithOutput(runCmd)
  772. if !strings.Contains(out, "Operation not permitted") {
  773. c.Fatalf("expected unshare with seccomp profile denied to fail, got %s", out)
  774. }
  775. }
  776. // TestRunSeccompProfileDenyChmod checks that 'docker run --security-opt seccomp=/tmp/profile.json busybox chmod 400 /etc/hostname' exits with operation not permitted.
  777. func (s *DockerSuite) TestRunSeccompProfileDenyChmod(c *check.C) {
  778. testRequires(c, SameHostDaemon, seccompEnabled)
  779. jsonData := `{
  780. "defaultAction": "SCMP_ACT_ALLOW",
  781. "syscalls": [
  782. {
  783. "name": "chmod",
  784. "action": "SCMP_ACT_ERRNO"
  785. }
  786. ]
  787. }`
  788. tmpFile, err := ioutil.TempFile("", "profile.json")
  789. c.Assert(err, check.IsNil)
  790. defer tmpFile.Close()
  791. if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
  792. c.Fatal(err)
  793. }
  794. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "400", "/etc/hostname")
  795. out, _, _ := runCommandWithOutput(runCmd)
  796. if !strings.Contains(out, "Operation not permitted") {
  797. c.Fatalf("expected chmod with seccomp profile denied to fail, got %s", out)
  798. }
  799. }
  800. // TestRunSeccompProfileDenyUnshareUserns checks that 'docker run debian:jessie unshare --map-root-user --user sh -c whoami' with a specific profile to
  801. // deny unhare of a userns exits with operation not permitted.
  802. func (s *DockerSuite) TestRunSeccompProfileDenyUnshareUserns(c *check.C) {
  803. testRequires(c, SameHostDaemon, seccompEnabled, NotArm, Apparmor)
  804. // from sched.h
  805. jsonData := fmt.Sprintf(`{
  806. "defaultAction": "SCMP_ACT_ALLOW",
  807. "syscalls": [
  808. {
  809. "name": "unshare",
  810. "action": "SCMP_ACT_ERRNO",
  811. "args": [
  812. {
  813. "index": 0,
  814. "value": %d,
  815. "op": "SCMP_CMP_EQ"
  816. }
  817. ]
  818. }
  819. ]
  820. }`, uint64(0x10000000))
  821. tmpFile, err := ioutil.TempFile("", "profile.json")
  822. defer tmpFile.Close()
  823. if err != nil {
  824. c.Fatal(err)
  825. }
  826. if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
  827. c.Fatal(err)
  828. }
  829. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "apparmor=unconfined", "--security-opt", "seccomp="+tmpFile.Name(), "debian:jessie", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami")
  830. out, _, _ := runCommandWithOutput(runCmd)
  831. if !strings.Contains(out, "Operation not permitted") {
  832. c.Fatalf("expected unshare userns with seccomp profile denied to fail, got %s", out)
  833. }
  834. }
  835. // TestRunSeccompProfileDenyCloneUserns checks that 'docker run syscall-test'
  836. // with a the default seccomp profile exits with operation not permitted.
  837. func (s *DockerSuite) TestRunSeccompProfileDenyCloneUserns(c *check.C) {
  838. testRequires(c, SameHostDaemon, seccompEnabled)
  839. runCmd := exec.Command(dockerBinary, "run", "syscall-test", "userns-test", "id")
  840. out, _, err := runCommandWithOutput(runCmd)
  841. if err == nil || !strings.Contains(out, "clone failed: Operation not permitted") {
  842. c.Fatalf("expected clone userns with default seccomp profile denied to fail, got %s: %v", out, err)
  843. }
  844. }
  845. // TestRunSeccompUnconfinedCloneUserns checks that
  846. // 'docker run --security-opt seccomp=unconfined syscall-test' allows creating a userns.
  847. func (s *DockerSuite) TestRunSeccompUnconfinedCloneUserns(c *check.C) {
  848. testRequires(c, SameHostDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace)
  849. // make sure running w privileged is ok
  850. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "syscall-test", "userns-test", "id")
  851. if out, _, err := runCommandWithOutput(runCmd); err != nil || !strings.Contains(out, "nobody") {
  852. c.Fatalf("expected clone userns with --security-opt seccomp=unconfined to succeed, got %s: %v", out, err)
  853. }
  854. }
  855. // TestRunSeccompAllowPrivCloneUserns checks that 'docker run --privileged syscall-test'
  856. // allows creating a userns.
  857. func (s *DockerSuite) TestRunSeccompAllowPrivCloneUserns(c *check.C) {
  858. testRequires(c, SameHostDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace)
  859. // make sure running w privileged is ok
  860. runCmd := exec.Command(dockerBinary, "run", "--privileged", "syscall-test", "userns-test", "id")
  861. if out, _, err := runCommandWithOutput(runCmd); err != nil || !strings.Contains(out, "nobody") {
  862. c.Fatalf("expected clone userns with --privileged to succeed, got %s: %v", out, err)
  863. }
  864. }
  865. // TestRunSeccompAllowSetrlimit checks that 'docker run debian:jessie ulimit -v 1048510' succeeds.
  866. func (s *DockerSuite) TestRunSeccompAllowSetrlimit(c *check.C) {
  867. testRequires(c, SameHostDaemon, seccompEnabled)
  868. // ulimit uses setrlimit, so we want to make sure we don't break it
  869. runCmd := exec.Command(dockerBinary, "run", "debian:jessie", "bash", "-c", "ulimit -v 1048510")
  870. if out, _, err := runCommandWithOutput(runCmd); err != nil {
  871. c.Fatalf("expected ulimit with seccomp to succeed, got %s: %v", out, err)
  872. }
  873. }
  874. func (s *DockerSuite) TestRunSeccompDefaultProfileAcct(c *check.C) {
  875. testRequires(c, SameHostDaemon, seccompEnabled, NotUserNamespace)
  876. var group sync.WaitGroup
  877. group.Add(5)
  878. errChan := make(chan error, 5)
  879. go func() {
  880. out, _, err := dockerCmdWithError("run", "syscall-test", "acct-test")
  881. if err == nil || !strings.Contains(out, "Operation not permitted") {
  882. errChan <- fmt.Errorf("goroutine 0: expected Operation not permitted, got: %s", out)
  883. }
  884. group.Done()
  885. }()
  886. go func() {
  887. out, _, err := dockerCmdWithError("run", "--cap-add", "sys_admin", "syscall-test", "acct-test")
  888. if err == nil || !strings.Contains(out, "Operation not permitted") {
  889. errChan <- fmt.Errorf("goroutine 1: expected Operation not permitted, got: %s", out)
  890. }
  891. group.Done()
  892. }()
  893. go func() {
  894. out, _, err := dockerCmdWithError("run", "--cap-add", "sys_pacct", "syscall-test", "acct-test")
  895. if err == nil || !strings.Contains(out, "No such file or directory") {
  896. errChan <- fmt.Errorf("goroutine 2: expected No such file or directory, got: %s", out)
  897. }
  898. group.Done()
  899. }()
  900. go func() {
  901. out, _, err := dockerCmdWithError("run", "--cap-add", "ALL", "syscall-test", "acct-test")
  902. if err == nil || !strings.Contains(out, "No such file or directory") {
  903. errChan <- fmt.Errorf("goroutine 3: expected No such file or directory, got: %s", out)
  904. }
  905. group.Done()
  906. }()
  907. go func() {
  908. out, _, err := dockerCmdWithError("run", "--cap-drop", "ALL", "--cap-add", "sys_pacct", "syscall-test", "acct-test")
  909. if err == nil || !strings.Contains(out, "No such file or directory") {
  910. errChan <- fmt.Errorf("goroutine 4: expected No such file or directory, got: %s", out)
  911. }
  912. group.Done()
  913. }()
  914. group.Wait()
  915. close(errChan)
  916. for err := range errChan {
  917. c.Assert(err, checker.IsNil)
  918. }
  919. }
  920. func (s *DockerSuite) TestRunSeccompDefaultProfileNS(c *check.C) {
  921. testRequires(c, SameHostDaemon, seccompEnabled, NotUserNamespace)
  922. var group sync.WaitGroup
  923. group.Add(6)
  924. errChan := make(chan error, 6)
  925. go func() {
  926. out, _, err := dockerCmdWithError("run", "syscall-test", "ns-test", "echo", "hello0")
  927. if err == nil || !strings.Contains(out, "Operation not permitted") {
  928. errChan <- fmt.Errorf("goroutine 0: expected Operation not permitted, got: %s", out)
  929. }
  930. group.Done()
  931. }()
  932. go func() {
  933. out, _, err := dockerCmdWithError("run", "--cap-add", "sys_admin", "syscall-test", "ns-test", "echo", "hello1")
  934. if err != nil || !strings.Contains(out, "hello1") {
  935. errChan <- fmt.Errorf("goroutine 1: expected hello1, got: %s, %v", out, err)
  936. }
  937. group.Done()
  938. }()
  939. go func() {
  940. out, _, err := dockerCmdWithError("run", "--cap-drop", "all", "--cap-add", "sys_admin", "syscall-test", "ns-test", "echo", "hello2")
  941. if err != nil || !strings.Contains(out, "hello2") {
  942. errChan <- fmt.Errorf("goroutine 2: expected hello2, got: %s, %v", out, err)
  943. }
  944. group.Done()
  945. }()
  946. go func() {
  947. out, _, err := dockerCmdWithError("run", "--cap-add", "ALL", "syscall-test", "ns-test", "echo", "hello3")
  948. if err != nil || !strings.Contains(out, "hello3") {
  949. errChan <- fmt.Errorf("goroutine 3: expected hello3, got: %s, %v", out, err)
  950. }
  951. group.Done()
  952. }()
  953. go func() {
  954. out, _, err := dockerCmdWithError("run", "--cap-add", "ALL", "--security-opt", "seccomp=unconfined", "syscall-test", "acct-test")
  955. if err == nil || !strings.Contains(out, "No such file or directory") {
  956. errChan <- fmt.Errorf("goroutine 4: expected No such file or directory, got: %s", out)
  957. }
  958. group.Done()
  959. }()
  960. go func() {
  961. out, _, err := dockerCmdWithError("run", "--cap-add", "ALL", "--security-opt", "seccomp=unconfined", "syscall-test", "ns-test", "echo", "hello4")
  962. if err != nil || !strings.Contains(out, "hello4") {
  963. errChan <- fmt.Errorf("goroutine 5: expected hello4, got: %s, %v", out, err)
  964. }
  965. group.Done()
  966. }()
  967. group.Wait()
  968. close(errChan)
  969. for err := range errChan {
  970. c.Assert(err, checker.IsNil)
  971. }
  972. }
  973. // TestRunNoNewPrivSetuid checks that --security-opt=no-new-privileges prevents
  974. // effective uid transtions on executing setuid binaries.
  975. func (s *DockerSuite) TestRunNoNewPrivSetuid(c *check.C) {
  976. testRequires(c, DaemonIsLinux, NotUserNamespace, SameHostDaemon)
  977. // test that running a setuid binary results in no effective uid transition
  978. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "no-new-privileges", "--user", "1000", "nnp-test", "/usr/bin/nnp-test")
  979. if out, _, err := runCommandWithOutput(runCmd); err != nil || !strings.Contains(out, "EUID=1000") {
  980. c.Fatalf("expected output to contain EUID=1000, got %s: %v", out, err)
  981. }
  982. }
  983. func (s *DockerSuite) TestRunApparmorProcDirectory(c *check.C) {
  984. testRequires(c, SameHostDaemon, Apparmor)
  985. // running w seccomp unconfined tests the apparmor profile
  986. runCmd := exec.Command(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/cgroup")
  987. if out, _, err := runCommandWithOutput(runCmd); err == nil || !(strings.Contains(out, "Permission denied") || strings.Contains(out, "Operation not permitted")) {
  988. c.Fatalf("expected chmod 777 /proc/1/cgroup to fail, got %s: %v", out, err)
  989. }
  990. runCmd = exec.Command(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/attr/current")
  991. if out, _, err := runCommandWithOutput(runCmd); err == nil || !(strings.Contains(out, "Permission denied") || strings.Contains(out, "Operation not permitted")) {
  992. c.Fatalf("expected chmod 777 /proc/1/attr/current to fail, got %s: %v", out, err)
  993. }
  994. }
  995. // make sure the default profile can be successfully parsed (using unshare as it is
  996. // something which we know is blocked in the default profile)
  997. func (s *DockerSuite) TestRunSeccompWithDefaultProfile(c *check.C) {
  998. testRequires(c, SameHostDaemon, seccompEnabled, NotArm, NotPpc64le, NotS390X)
  999. out, _, err := dockerCmdWithError("run", "--security-opt", "seccomp=../profiles/seccomp/default.json", "debian:jessie", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami")
  1000. c.Assert(err, checker.NotNil, check.Commentf(out))
  1001. c.Assert(strings.TrimSpace(out), checker.Equals, "unshare: unshare failed: Operation not permitted")
  1002. }
  1003. // TestRunDeviceSymlink checks run with device that follows symlink (#13840 and #22271)
  1004. func (s *DockerSuite) TestRunDeviceSymlink(c *check.C) {
  1005. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm, SameHostDaemon)
  1006. if _, err := os.Stat("/dev/zero"); err != nil {
  1007. c.Skip("Host does not have /dev/zero")
  1008. }
  1009. // Create a temporary directory to create symlink
  1010. tmpDir, err := ioutil.TempDir("", "docker_device_follow_symlink_tests")
  1011. c.Assert(err, checker.IsNil)
  1012. defer os.RemoveAll(tmpDir)
  1013. // Create a symbolic link to /dev/zero
  1014. symZero := filepath.Join(tmpDir, "zero")
  1015. err = os.Symlink("/dev/zero", symZero)
  1016. c.Assert(err, checker.IsNil)
  1017. // Create a temporary file "temp" inside tmpDir, write some data to "tmpDir/temp",
  1018. // then create a symlink "tmpDir/file" to the temporary file "tmpDir/temp".
  1019. tmpFile := filepath.Join(tmpDir, "temp")
  1020. err = ioutil.WriteFile(tmpFile, []byte("temp"), 0666)
  1021. c.Assert(err, checker.IsNil)
  1022. symFile := filepath.Join(tmpDir, "file")
  1023. err = os.Symlink(tmpFile, symFile)
  1024. c.Assert(err, checker.IsNil)
  1025. // Create a symbolic link to /dev/zero, this time with a relative path (#22271)
  1026. err = os.Symlink("zero", "/dev/symzero")
  1027. if err != nil {
  1028. c.Fatal("/dev/symzero creation failed")
  1029. }
  1030. // We need to remove this symbolic link here as it is created in /dev/, not temporary directory as above
  1031. defer os.Remove("/dev/symzero")
  1032. // md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23
  1033. out, _ := dockerCmd(c, "run", "--device", symZero+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  1034. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "bb7df04e1b0a2570657527a7e108ae23", check.Commentf("expected output bb7df04e1b0a2570657527a7e108ae23"))
  1035. // symlink "tmpDir/file" to a file "tmpDir/temp" will result in an error as it is not a device.
  1036. out, _, err = dockerCmdWithError("run", "--device", symFile+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  1037. c.Assert(err, check.NotNil)
  1038. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "not a device node", check.Commentf("expected output 'not a device node'"))
  1039. // md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23 (this time check with relative path backed, see #22271)
  1040. out, _ = dockerCmd(c, "run", "--device", "/dev/symzero:/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  1041. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "bb7df04e1b0a2570657527a7e108ae23", check.Commentf("expected output bb7df04e1b0a2570657527a7e108ae23"))
  1042. }
  1043. // TestRunPidsLimit makes sure the pids cgroup is set with --pids-limit
  1044. func (s *DockerSuite) TestRunPidsLimit(c *check.C) {
  1045. testRequires(c, pidsLimit)
  1046. file := "/sys/fs/cgroup/pids/pids.max"
  1047. out, _ := dockerCmd(c, "run", "--name", "skittles", "--pids-limit", "2", "busybox", "cat", file)
  1048. c.Assert(strings.TrimSpace(out), checker.Equals, "2")
  1049. out = inspectField(c, "skittles", "HostConfig.PidsLimit")
  1050. c.Assert(out, checker.Equals, "2", check.Commentf("setting the pids limit failed"))
  1051. }
  1052. func (s *DockerSuite) TestRunPrivilegedAllowedDevices(c *check.C) {
  1053. testRequires(c, DaemonIsLinux, NotUserNamespace)
  1054. file := "/sys/fs/cgroup/devices/devices.list"
  1055. out, _ := dockerCmd(c, "run", "--privileged", "busybox", "cat", file)
  1056. c.Logf("out: %q", out)
  1057. c.Assert(strings.TrimSpace(out), checker.Equals, "a *:* rwm")
  1058. }
  1059. func (s *DockerSuite) TestRunUserDeviceAllowed(c *check.C) {
  1060. testRequires(c, DaemonIsLinux)
  1061. fi, err := os.Stat("/dev/snd/timer")
  1062. if err != nil {
  1063. c.Skip("Host does not have /dev/snd/timer")
  1064. }
  1065. stat, ok := fi.Sys().(*syscall.Stat_t)
  1066. if !ok {
  1067. c.Skip("Could not stat /dev/snd/timer")
  1068. }
  1069. file := "/sys/fs/cgroup/devices/devices.list"
  1070. out, _ := dockerCmd(c, "run", "--device", "/dev/snd/timer:w", "busybox", "cat", file)
  1071. c.Assert(out, checker.Contains, fmt.Sprintf("c %d:%d w", stat.Rdev/256, stat.Rdev%256))
  1072. }