docker_cli_run_unix_test.go 45 KB

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