docker_cli_run_unix_test.go 46 KB

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