docker_cli_run_unix_test.go 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576
  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/integration-cli/checker"
  17. "github.com/docker/docker/integration-cli/cli"
  18. "github.com/docker/docker/integration-cli/cli/build"
  19. "github.com/docker/docker/pkg/homedir"
  20. "github.com/docker/docker/pkg/mount"
  21. "github.com/docker/docker/pkg/parsers"
  22. "github.com/docker/docker/pkg/sysinfo"
  23. "github.com/go-check/check"
  24. "github.com/gotestyourself/gotestyourself/icmd"
  25. "github.com/kr/pty"
  26. )
  27. // #6509
  28. func (s *DockerSuite) TestRunRedirectStdout(c *check.C) {
  29. checkRedirect := func(command string) {
  30. _, tty, err := pty.Open()
  31. c.Assert(err, checker.IsNil, check.Commentf("Could not open pty"))
  32. cmd := exec.Command("sh", "-c", command)
  33. cmd.Stdin = tty
  34. cmd.Stdout = tty
  35. cmd.Stderr = tty
  36. c.Assert(cmd.Start(), checker.IsNil)
  37. ch := make(chan error)
  38. go func() {
  39. ch <- cmd.Wait()
  40. close(ch)
  41. }()
  42. select {
  43. case <-time.After(10 * time.Second):
  44. c.Fatal("command timeout")
  45. case err := <-ch:
  46. c.Assert(err, checker.IsNil, check.Commentf("wait err"))
  47. }
  48. }
  49. checkRedirect(dockerBinary + " run -i busybox cat /etc/passwd | grep -q root")
  50. checkRedirect(dockerBinary + " run busybox cat /etc/passwd | grep -q root")
  51. }
  52. // Test recursive bind mount works by default
  53. func (s *DockerSuite) TestRunWithVolumesIsRecursive(c *check.C) {
  54. // /tmp gets permission denied
  55. testRequires(c, NotUserNamespace, SameHostDaemon)
  56. tmpDir, err := ioutil.TempDir("", "docker_recursive_mount_test")
  57. c.Assert(err, checker.IsNil)
  58. defer os.RemoveAll(tmpDir)
  59. // Create a temporary tmpfs mount.
  60. tmpfsDir := filepath.Join(tmpDir, "tmpfs")
  61. c.Assert(os.MkdirAll(tmpfsDir, 0777), checker.IsNil, check.Commentf("failed to mkdir at %s", tmpfsDir))
  62. c.Assert(mount.Mount("tmpfs", tmpfsDir, "tmpfs", ""), checker.IsNil, check.Commentf("failed to create a tmpfs mount at %s", tmpfsDir))
  63. f, err := ioutil.TempFile(tmpfsDir, "touch-me")
  64. c.Assert(err, checker.IsNil)
  65. defer f.Close()
  66. out, _ := dockerCmd(c, "run", "--name", "test-data", "--volume", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox:latest", "ls", "/tmp/tmpfs")
  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. // TestRunAttachDetach 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. // TestRunAttachDetachFromFlag 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. // TestRunAttachDetachFromInvalidFlag 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 detach keys (ctrl-A,a) provided"
  199. c.Assert(strings.TrimSpace(out), checker.Equals, errStr)
  200. }
  201. // TestRunAttachDetachFromConfig 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. // TestRunAttachDetachKeysOverrideConfig 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. cli.DockerCmd(c, "run", "--kernel-memory", "50M", "--name", "test1", "busybox", "cat", file).Assert(c, icmd.Expected{
  419. Out: "52428800",
  420. })
  421. cli.InspectCmd(c, "test1", cli.Format(".HostConfig.KernelMemory")).Assert(c, icmd.Expected{
  422. Out: "52428800",
  423. })
  424. }
  425. func (s *DockerSuite) TestRunWithInvalidKernelMemory(c *check.C) {
  426. testRequires(c, kernelMemorySupport)
  427. out, _, err := dockerCmdWithError("run", "--kernel-memory", "2M", "busybox", "true")
  428. c.Assert(err, check.NotNil)
  429. expected := "Minimum kernel memory limit allowed is 4MB"
  430. c.Assert(out, checker.Contains, expected)
  431. out, _, err = dockerCmdWithError("run", "--kernel-memory", "-16m", "--name", "test2", "busybox", "echo", "test")
  432. c.Assert(err, check.NotNil)
  433. expected = "invalid size"
  434. c.Assert(out, checker.Contains, expected)
  435. }
  436. func (s *DockerSuite) TestRunWithCPUShares(c *check.C) {
  437. testRequires(c, cpuShare)
  438. file := "/sys/fs/cgroup/cpu/cpu.shares"
  439. out, _ := dockerCmd(c, "run", "--cpu-shares", "1000", "--name", "test", "busybox", "cat", file)
  440. c.Assert(strings.TrimSpace(out), checker.Equals, "1000")
  441. out = inspectField(c, "test", "HostConfig.CPUShares")
  442. c.Assert(out, check.Equals, "1000")
  443. }
  444. // "test" should be printed
  445. func (s *DockerSuite) TestRunEchoStdoutWithCPUSharesAndMemoryLimit(c *check.C) {
  446. testRequires(c, cpuShare)
  447. testRequires(c, memoryLimitSupport)
  448. cli.DockerCmd(c, "run", "--cpu-shares", "1000", "-m", "32m", "busybox", "echo", "test").Assert(c, icmd.Expected{
  449. Out: "test\n",
  450. })
  451. }
  452. func (s *DockerSuite) TestRunWithCpusetCpus(c *check.C) {
  453. testRequires(c, cgroupCpuset)
  454. file := "/sys/fs/cgroup/cpuset/cpuset.cpus"
  455. out, _ := dockerCmd(c, "run", "--cpuset-cpus", "0", "--name", "test", "busybox", "cat", file)
  456. c.Assert(strings.TrimSpace(out), checker.Equals, "0")
  457. out = inspectField(c, "test", "HostConfig.CpusetCpus")
  458. c.Assert(out, check.Equals, "0")
  459. }
  460. func (s *DockerSuite) TestRunWithCpusetMems(c *check.C) {
  461. testRequires(c, cgroupCpuset)
  462. file := "/sys/fs/cgroup/cpuset/cpuset.mems"
  463. out, _ := dockerCmd(c, "run", "--cpuset-mems", "0", "--name", "test", "busybox", "cat", file)
  464. c.Assert(strings.TrimSpace(out), checker.Equals, "0")
  465. out = inspectField(c, "test", "HostConfig.CpusetMems")
  466. c.Assert(out, check.Equals, "0")
  467. }
  468. func (s *DockerSuite) TestRunWithBlkioWeight(c *check.C) {
  469. testRequires(c, blkioWeight)
  470. file := "/sys/fs/cgroup/blkio/blkio.weight"
  471. out, _ := dockerCmd(c, "run", "--blkio-weight", "300", "--name", "test", "busybox", "cat", file)
  472. c.Assert(strings.TrimSpace(out), checker.Equals, "300")
  473. out = inspectField(c, "test", "HostConfig.BlkioWeight")
  474. c.Assert(out, check.Equals, "300")
  475. }
  476. func (s *DockerSuite) TestRunWithInvalidBlkioWeight(c *check.C) {
  477. testRequires(c, blkioWeight)
  478. out, _, err := dockerCmdWithError("run", "--blkio-weight", "5", "busybox", "true")
  479. c.Assert(err, check.NotNil, check.Commentf(out))
  480. expected := "Range of blkio weight is from 10 to 1000"
  481. c.Assert(out, checker.Contains, expected)
  482. }
  483. func (s *DockerSuite) TestRunWithInvalidPathforBlkioWeightDevice(c *check.C) {
  484. testRequires(c, blkioWeight)
  485. out, _, err := dockerCmdWithError("run", "--blkio-weight-device", "/dev/sdX:100", "busybox", "true")
  486. c.Assert(err, check.NotNil, check.Commentf(out))
  487. }
  488. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceReadBps(c *check.C) {
  489. testRequires(c, blkioWeight)
  490. out, _, err := dockerCmdWithError("run", "--device-read-bps", "/dev/sdX:500", "busybox", "true")
  491. c.Assert(err, check.NotNil, check.Commentf(out))
  492. }
  493. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceWriteBps(c *check.C) {
  494. testRequires(c, blkioWeight)
  495. out, _, err := dockerCmdWithError("run", "--device-write-bps", "/dev/sdX:500", "busybox", "true")
  496. c.Assert(err, check.NotNil, check.Commentf(out))
  497. }
  498. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceReadIOps(c *check.C) {
  499. testRequires(c, blkioWeight)
  500. out, _, err := dockerCmdWithError("run", "--device-read-iops", "/dev/sdX:500", "busybox", "true")
  501. c.Assert(err, check.NotNil, check.Commentf(out))
  502. }
  503. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceWriteIOps(c *check.C) {
  504. testRequires(c, blkioWeight)
  505. out, _, err := dockerCmdWithError("run", "--device-write-iops", "/dev/sdX:500", "busybox", "true")
  506. c.Assert(err, check.NotNil, check.Commentf(out))
  507. }
  508. func (s *DockerSuite) TestRunOOMExitCode(c *check.C) {
  509. testRequires(c, memoryLimitSupport, swapMemorySupport)
  510. errChan := make(chan error)
  511. go func() {
  512. defer close(errChan)
  513. out, exitCode, _ := dockerCmdWithError("run", "-m", "4MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done")
  514. if expected := 137; exitCode != expected {
  515. errChan <- fmt.Errorf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out)
  516. }
  517. }()
  518. select {
  519. case err := <-errChan:
  520. c.Assert(err, check.IsNil)
  521. case <-time.After(600 * time.Second):
  522. c.Fatal("Timeout waiting for container to die on OOM")
  523. }
  524. }
  525. func (s *DockerSuite) TestRunWithMemoryLimit(c *check.C) {
  526. testRequires(c, memoryLimitSupport)
  527. file := "/sys/fs/cgroup/memory/memory.limit_in_bytes"
  528. cli.DockerCmd(c, "run", "-m", "32M", "--name", "test", "busybox", "cat", file).Assert(c, icmd.Expected{
  529. Out: "33554432",
  530. })
  531. cli.InspectCmd(c, "test", cli.Format(".HostConfig.Memory")).Assert(c, icmd.Expected{
  532. Out: "33554432",
  533. })
  534. }
  535. // TestRunWithoutMemoryswapLimit sets memory limit and disables swap
  536. // memory limit, this means the processes in the container can use
  537. // 16M memory and as much swap memory as they need (if the host
  538. // supports swap memory).
  539. func (s *DockerSuite) TestRunWithoutMemoryswapLimit(c *check.C) {
  540. testRequires(c, DaemonIsLinux)
  541. testRequires(c, memoryLimitSupport)
  542. testRequires(c, swapMemorySupport)
  543. dockerCmd(c, "run", "-m", "32m", "--memory-swap", "-1", "busybox", "true")
  544. }
  545. func (s *DockerSuite) TestRunWithSwappiness(c *check.C) {
  546. testRequires(c, memorySwappinessSupport)
  547. file := "/sys/fs/cgroup/memory/memory.swappiness"
  548. out, _ := dockerCmd(c, "run", "--memory-swappiness", "0", "--name", "test", "busybox", "cat", file)
  549. c.Assert(strings.TrimSpace(out), checker.Equals, "0")
  550. out = inspectField(c, "test", "HostConfig.MemorySwappiness")
  551. c.Assert(out, check.Equals, "0")
  552. }
  553. func (s *DockerSuite) TestRunWithSwappinessInvalid(c *check.C) {
  554. testRequires(c, memorySwappinessSupport)
  555. out, _, err := dockerCmdWithError("run", "--memory-swappiness", "101", "busybox", "true")
  556. c.Assert(err, check.NotNil)
  557. expected := "Valid memory swappiness range is 0-100"
  558. c.Assert(out, checker.Contains, expected, check.Commentf("Expected output to contain %q, not %q", out, expected))
  559. out, _, err = dockerCmdWithError("run", "--memory-swappiness", "-10", "busybox", "true")
  560. c.Assert(err, check.NotNil)
  561. c.Assert(out, checker.Contains, expected, check.Commentf("Expected output to contain %q, not %q", out, expected))
  562. }
  563. func (s *DockerSuite) TestRunWithMemoryReservation(c *check.C) {
  564. testRequires(c, memoryReservationSupport)
  565. file := "/sys/fs/cgroup/memory/memory.soft_limit_in_bytes"
  566. out, _ := dockerCmd(c, "run", "--memory-reservation", "200M", "--name", "test", "busybox", "cat", file)
  567. c.Assert(strings.TrimSpace(out), checker.Equals, "209715200")
  568. out = inspectField(c, "test", "HostConfig.MemoryReservation")
  569. c.Assert(out, check.Equals, "209715200")
  570. }
  571. func (s *DockerSuite) TestRunWithMemoryReservationInvalid(c *check.C) {
  572. testRequires(c, memoryLimitSupport)
  573. testRequires(c, memoryReservationSupport)
  574. out, _, err := dockerCmdWithError("run", "-m", "500M", "--memory-reservation", "800M", "busybox", "true")
  575. c.Assert(err, check.NotNil)
  576. expected := "Minimum memory limit can not be less than memory reservation limit"
  577. c.Assert(strings.TrimSpace(out), checker.Contains, expected, check.Commentf("run container should fail with invalid memory reservation"))
  578. out, _, err = dockerCmdWithError("run", "--memory-reservation", "1k", "busybox", "true")
  579. c.Assert(err, check.NotNil)
  580. expected = "Minimum memory reservation allowed is 4MB"
  581. c.Assert(strings.TrimSpace(out), checker.Contains, expected, check.Commentf("run container should fail with invalid memory reservation"))
  582. }
  583. func (s *DockerSuite) TestStopContainerSignal(c *check.C) {
  584. 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`)
  585. containerID := strings.TrimSpace(out)
  586. c.Assert(waitRun(containerID), checker.IsNil)
  587. dockerCmd(c, "stop", containerID)
  588. out, _ = dockerCmd(c, "logs", containerID)
  589. c.Assert(out, checker.Contains, "exit trapped", check.Commentf("Expected `exit trapped` in the log"))
  590. }
  591. func (s *DockerSuite) TestRunSwapLessThanMemoryLimit(c *check.C) {
  592. testRequires(c, memoryLimitSupport)
  593. testRequires(c, swapMemorySupport)
  594. out, _, err := dockerCmdWithError("run", "-m", "16m", "--memory-swap", "15m", "busybox", "echo", "test")
  595. expected := "Minimum memoryswap limit should be larger than memory limit"
  596. c.Assert(err, check.NotNil)
  597. c.Assert(out, checker.Contains, expected)
  598. }
  599. func (s *DockerSuite) TestRunInvalidCpusetCpusFlagValue(c *check.C) {
  600. testRequires(c, cgroupCpuset, SameHostDaemon)
  601. sysInfo := sysinfo.New(true)
  602. cpus, err := parsers.ParseUintList(sysInfo.Cpus)
  603. c.Assert(err, check.IsNil)
  604. var invalid int
  605. for i := 0; i <= len(cpus)+1; i++ {
  606. if !cpus[i] {
  607. invalid = i
  608. break
  609. }
  610. }
  611. out, _, err := dockerCmdWithError("run", "--cpuset-cpus", strconv.Itoa(invalid), "busybox", "true")
  612. c.Assert(err, check.NotNil)
  613. expected := fmt.Sprintf("Error response from daemon: Requested CPUs are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Cpus)
  614. c.Assert(out, checker.Contains, expected)
  615. }
  616. func (s *DockerSuite) TestRunInvalidCpusetMemsFlagValue(c *check.C) {
  617. testRequires(c, cgroupCpuset)
  618. sysInfo := sysinfo.New(true)
  619. mems, err := parsers.ParseUintList(sysInfo.Mems)
  620. c.Assert(err, check.IsNil)
  621. var invalid int
  622. for i := 0; i <= len(mems)+1; i++ {
  623. if !mems[i] {
  624. invalid = i
  625. break
  626. }
  627. }
  628. out, _, err := dockerCmdWithError("run", "--cpuset-mems", strconv.Itoa(invalid), "busybox", "true")
  629. c.Assert(err, check.NotNil)
  630. expected := fmt.Sprintf("Error response from daemon: Requested memory nodes are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Mems)
  631. c.Assert(out, checker.Contains, expected)
  632. }
  633. func (s *DockerSuite) TestRunInvalidCPUShares(c *check.C) {
  634. testRequires(c, cpuShare, DaemonIsLinux)
  635. out, _, err := dockerCmdWithError("run", "--cpu-shares", "1", "busybox", "echo", "test")
  636. c.Assert(err, check.NotNil, check.Commentf(out))
  637. expected := "The minimum allowed cpu-shares is 2"
  638. c.Assert(out, checker.Contains, expected)
  639. out, _, err = dockerCmdWithError("run", "--cpu-shares", "-1", "busybox", "echo", "test")
  640. c.Assert(err, check.NotNil, check.Commentf(out))
  641. expected = "shares: invalid argument"
  642. c.Assert(out, checker.Contains, expected)
  643. out, _, err = dockerCmdWithError("run", "--cpu-shares", "99999999", "busybox", "echo", "test")
  644. c.Assert(err, check.NotNil, check.Commentf(out))
  645. expected = "The maximum allowed cpu-shares is"
  646. c.Assert(out, checker.Contains, expected)
  647. }
  648. func (s *DockerSuite) TestRunWithDefaultShmSize(c *check.C) {
  649. testRequires(c, DaemonIsLinux)
  650. name := "shm-default"
  651. out, _ := dockerCmd(c, "run", "--name", name, "busybox", "mount")
  652. shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  653. if !shmRegex.MatchString(out) {
  654. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  655. }
  656. shmSize := inspectField(c, name, "HostConfig.ShmSize")
  657. c.Assert(shmSize, check.Equals, "67108864")
  658. }
  659. func (s *DockerSuite) TestRunWithShmSize(c *check.C) {
  660. testRequires(c, DaemonIsLinux)
  661. name := "shm"
  662. out, _ := dockerCmd(c, "run", "--name", name, "--shm-size=1G", "busybox", "mount")
  663. shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=1048576k`)
  664. if !shmRegex.MatchString(out) {
  665. c.Fatalf("Expected shm of 1GB in mount command, got %v", out)
  666. }
  667. shmSize := inspectField(c, name, "HostConfig.ShmSize")
  668. c.Assert(shmSize, check.Equals, "1073741824")
  669. }
  670. func (s *DockerSuite) TestRunTmpfsMountsEnsureOrdered(c *check.C) {
  671. tmpFile, err := ioutil.TempFile("", "test")
  672. c.Assert(err, check.IsNil)
  673. defer tmpFile.Close()
  674. out, _ := dockerCmd(c, "run", "--tmpfs", "/run", "-v", tmpFile.Name()+":/run/test", "busybox", "ls", "/run")
  675. c.Assert(out, checker.Contains, "test")
  676. }
  677. func (s *DockerSuite) TestRunTmpfsMounts(c *check.C) {
  678. // TODO Windows (Post TP5): This test cannot run on a Windows daemon as
  679. // Windows does not support tmpfs mounts.
  680. testRequires(c, DaemonIsLinux)
  681. if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run", "busybox", "touch", "/run/somefile"); err != nil {
  682. c.Fatalf("/run directory not mounted on tmpfs %q %s", err, out)
  683. }
  684. if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run:noexec", "busybox", "touch", "/run/somefile"); err != nil {
  685. c.Fatalf("/run directory not mounted on tmpfs %q %s", err, out)
  686. }
  687. if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run:noexec,nosuid,rw,size=5k,mode=700", "busybox", "touch", "/run/somefile"); err != nil {
  688. c.Fatalf("/run failed to mount on tmpfs with valid options %q %s", err, out)
  689. }
  690. if _, _, err := dockerCmdWithError("run", "--tmpfs", "/run:foobar", "busybox", "touch", "/run/somefile"); err == nil {
  691. c.Fatalf("/run mounted on tmpfs when it should have vailed within invalid mount option")
  692. }
  693. if _, _, err := dockerCmdWithError("run", "--tmpfs", "/run", "-v", "/run:/run", "busybox", "touch", "/run/somefile"); err == nil {
  694. c.Fatalf("Should have generated an error saying Duplicate mount points")
  695. }
  696. }
  697. func (s *DockerSuite) TestRunTmpfsMountsOverrideImageVolumes(c *check.C) {
  698. name := "img-with-volumes"
  699. buildImageSuccessfully(c, name, build.WithDockerfile(`
  700. FROM busybox
  701. VOLUME /run
  702. RUN touch /run/stuff
  703. `))
  704. out, _ := dockerCmd(c, "run", "--tmpfs", "/run", name, "ls", "/run")
  705. c.Assert(out, checker.Not(checker.Contains), "stuff")
  706. }
  707. // Test case for #22420
  708. func (s *DockerSuite) TestRunTmpfsMountsWithOptions(c *check.C) {
  709. testRequires(c, DaemonIsLinux)
  710. expectedOptions := []string{"rw", "nosuid", "nodev", "noexec", "relatime"}
  711. out, _ := dockerCmd(c, "run", "--tmpfs", "/tmp", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
  712. for _, option := range expectedOptions {
  713. c.Assert(out, checker.Contains, option)
  714. }
  715. c.Assert(out, checker.Not(checker.Contains), "size=")
  716. expectedOptions = []string{"rw", "nosuid", "nodev", "noexec", "relatime"}
  717. out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
  718. for _, option := range expectedOptions {
  719. c.Assert(out, checker.Contains, option)
  720. }
  721. c.Assert(out, checker.Not(checker.Contains), "size=")
  722. expectedOptions = []string{"rw", "nosuid", "nodev", "relatime", "size=8192k"}
  723. out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw,exec,size=8192k", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
  724. for _, option := range expectedOptions {
  725. c.Assert(out, checker.Contains, option)
  726. }
  727. expectedOptions = []string{"rw", "nosuid", "nodev", "noexec", "relatime", "size=4096k"}
  728. out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw,size=8192k,exec,size=4096k,noexec", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
  729. for _, option := range expectedOptions {
  730. c.Assert(out, checker.Contains, option)
  731. }
  732. // We use debian:jessie as there is no findmnt in busybox. Also the output will be in the format of
  733. // TARGET PROPAGATION
  734. // /tmp shared
  735. // so we only capture `shared` here.
  736. expectedOptions = []string{"shared"}
  737. out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:shared", "debian:jessie", "findmnt", "-o", "TARGET,PROPAGATION", "/tmp")
  738. for _, option := range expectedOptions {
  739. c.Assert(out, checker.Contains, option)
  740. }
  741. }
  742. func (s *DockerSuite) TestRunSysctls(c *check.C) {
  743. testRequires(c, DaemonIsLinux)
  744. var err error
  745. out, _ := dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=1", "--name", "test", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward")
  746. c.Assert(strings.TrimSpace(out), check.Equals, "1")
  747. out = inspectFieldJSON(c, "test", "HostConfig.Sysctls")
  748. sysctls := make(map[string]string)
  749. err = json.Unmarshal([]byte(out), &sysctls)
  750. c.Assert(err, check.IsNil)
  751. c.Assert(sysctls["net.ipv4.ip_forward"], check.Equals, "1")
  752. out, _ = dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=0", "--name", "test1", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward")
  753. c.Assert(strings.TrimSpace(out), check.Equals, "0")
  754. out = inspectFieldJSON(c, "test1", "HostConfig.Sysctls")
  755. err = json.Unmarshal([]byte(out), &sysctls)
  756. c.Assert(err, check.IsNil)
  757. c.Assert(sysctls["net.ipv4.ip_forward"], check.Equals, "0")
  758. icmd.RunCommand(dockerBinary, "run", "--sysctl", "kernel.foobar=1", "--name", "test2",
  759. "busybox", "cat", "/proc/sys/kernel/foobar").Assert(c, icmd.Expected{
  760. ExitCode: 125,
  761. Err: "invalid argument",
  762. })
  763. }
  764. // TestRunSeccompProfileDenyUnshare checks that 'docker run --security-opt seccomp=/tmp/profile.json debian:jessie unshare' exits with operation not permitted.
  765. func (s *DockerSuite) TestRunSeccompProfileDenyUnshare(c *check.C) {
  766. testRequires(c, SameHostDaemon, seccompEnabled, NotArm, Apparmor)
  767. jsonData := `{
  768. "defaultAction": "SCMP_ACT_ALLOW",
  769. "syscalls": [
  770. {
  771. "name": "unshare",
  772. "action": "SCMP_ACT_ERRNO"
  773. }
  774. ]
  775. }`
  776. tmpFile, err := ioutil.TempFile("", "profile.json")
  777. if err != nil {
  778. c.Fatal(err)
  779. }
  780. defer tmpFile.Close()
  781. if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
  782. c.Fatal(err)
  783. }
  784. icmd.RunCommand(dockerBinary, "run", "--security-opt", "apparmor=unconfined",
  785. "--security-opt", "seccomp="+tmpFile.Name(),
  786. "debian:jessie", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc").Assert(c, icmd.Expected{
  787. ExitCode: 1,
  788. Err: "Operation not permitted",
  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. icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp="+tmpFile.Name(),
  818. "busybox", "chmod", "400", "/etc/hostname").Assert(c, icmd.Expected{
  819. ExitCode: 1,
  820. Err: "Operation not permitted",
  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 unshare 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. if err != nil {
  846. c.Fatal(err)
  847. }
  848. defer tmpFile.Close()
  849. if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
  850. c.Fatal(err)
  851. }
  852. icmd.RunCommand(dockerBinary, "run",
  853. "--security-opt", "apparmor=unconfined", "--security-opt", "seccomp="+tmpFile.Name(),
  854. "debian:jessie", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami").Assert(c, icmd.Expected{
  855. ExitCode: 1,
  856. Err: "Operation not permitted",
  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. ensureSyscallTest(c)
  864. icmd.RunCommand(dockerBinary, "run", "syscall-test", "userns-test", "id").Assert(c, icmd.Expected{
  865. ExitCode: 1,
  866. Err: "clone failed: Operation not permitted",
  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. ensureSyscallTest(c)
  874. // make sure running w privileged is ok
  875. icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp=unconfined",
  876. "syscall-test", "userns-test", "id").Assert(c, icmd.Expected{
  877. Out: "nobody",
  878. })
  879. }
  880. // TestRunSeccompAllowPrivCloneUserns checks that 'docker run --privileged syscall-test'
  881. // allows creating a userns.
  882. func (s *DockerSuite) TestRunSeccompAllowPrivCloneUserns(c *check.C) {
  883. testRequires(c, SameHostDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace)
  884. ensureSyscallTest(c)
  885. // make sure running w privileged is ok
  886. icmd.RunCommand(dockerBinary, "run", "--privileged", "syscall-test", "userns-test", "id").Assert(c, icmd.Expected{
  887. Out: "nobody",
  888. })
  889. }
  890. // TestRunSeccompProfileAllow32Bit checks that 32 bit code can run on x86_64
  891. // with the default seccomp profile.
  892. func (s *DockerSuite) TestRunSeccompProfileAllow32Bit(c *check.C) {
  893. testRequires(c, SameHostDaemon, seccompEnabled, IsAmd64)
  894. ensureSyscallTest(c)
  895. icmd.RunCommand(dockerBinary, "run", "syscall-test", "exit32-test", "id").Assert(c, icmd.Success)
  896. }
  897. // TestRunSeccompAllowSetrlimit checks that 'docker run debian:jessie ulimit -v 1048510' succeeds.
  898. func (s *DockerSuite) TestRunSeccompAllowSetrlimit(c *check.C) {
  899. testRequires(c, SameHostDaemon, seccompEnabled)
  900. // ulimit uses setrlimit, so we want to make sure we don't break it
  901. icmd.RunCommand(dockerBinary, "run", "debian:jessie", "bash", "-c", "ulimit -v 1048510").Assert(c, icmd.Success)
  902. }
  903. func (s *DockerSuite) TestRunSeccompDefaultProfileAcct(c *check.C) {
  904. testRequires(c, SameHostDaemon, seccompEnabled, NotUserNamespace)
  905. ensureSyscallTest(c)
  906. out, _, err := dockerCmdWithError("run", "syscall-test", "acct-test")
  907. if err == nil || !strings.Contains(out, "Operation not permitted") {
  908. c.Fatalf("test 0: expected Operation not permitted, got: %s", out)
  909. }
  910. out, _, err = dockerCmdWithError("run", "--cap-add", "sys_admin", "syscall-test", "acct-test")
  911. if err == nil || !strings.Contains(out, "Operation not permitted") {
  912. c.Fatalf("test 1: expected Operation not permitted, got: %s", out)
  913. }
  914. out, _, err = dockerCmdWithError("run", "--cap-add", "sys_pacct", "syscall-test", "acct-test")
  915. if err == nil || !strings.Contains(out, "No such file or directory") {
  916. c.Fatalf("test 2: expected No such file or directory, got: %s", out)
  917. }
  918. out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "syscall-test", "acct-test")
  919. if err == nil || !strings.Contains(out, "No such file or directory") {
  920. c.Fatalf("test 3: expected No such file or directory, got: %s", out)
  921. }
  922. out, _, err = dockerCmdWithError("run", "--cap-drop", "ALL", "--cap-add", "sys_pacct", "syscall-test", "acct-test")
  923. if err == nil || !strings.Contains(out, "No such file or directory") {
  924. c.Fatalf("test 4: expected No such file or directory, got: %s", out)
  925. }
  926. }
  927. func (s *DockerSuite) TestRunSeccompDefaultProfileNS(c *check.C) {
  928. testRequires(c, SameHostDaemon, seccompEnabled, NotUserNamespace)
  929. ensureSyscallTest(c)
  930. out, _, err := dockerCmdWithError("run", "syscall-test", "ns-test", "echo", "hello0")
  931. if err == nil || !strings.Contains(out, "Operation not permitted") {
  932. c.Fatalf("test 0: expected Operation not permitted, got: %s", out)
  933. }
  934. out, _, err = dockerCmdWithError("run", "--cap-add", "sys_admin", "syscall-test", "ns-test", "echo", "hello1")
  935. if err != nil || !strings.Contains(out, "hello1") {
  936. c.Fatalf("test 1: expected hello1, got: %s, %v", out, err)
  937. }
  938. out, _, err = dockerCmdWithError("run", "--cap-drop", "all", "--cap-add", "sys_admin", "syscall-test", "ns-test", "echo", "hello2")
  939. if err != nil || !strings.Contains(out, "hello2") {
  940. c.Fatalf("test 2: expected hello2, got: %s, %v", out, err)
  941. }
  942. out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "syscall-test", "ns-test", "echo", "hello3")
  943. if err != nil || !strings.Contains(out, "hello3") {
  944. c.Fatalf("test 3: expected hello3, got: %s, %v", out, err)
  945. }
  946. out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "--security-opt", "seccomp=unconfined", "syscall-test", "acct-test")
  947. if err == nil || !strings.Contains(out, "No such file or directory") {
  948. c.Fatalf("test 4: expected No such file or directory, got: %s", out)
  949. }
  950. out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "--security-opt", "seccomp=unconfined", "syscall-test", "ns-test", "echo", "hello4")
  951. if err != nil || !strings.Contains(out, "hello4") {
  952. c.Fatalf("test 5: expected hello4, got: %s, %v", out, err)
  953. }
  954. }
  955. // TestRunNoNewPrivSetuid checks that --security-opt='no-new-privileges=true' prevents
  956. // effective uid transtions on executing setuid binaries.
  957. func (s *DockerSuite) TestRunNoNewPrivSetuid(c *check.C) {
  958. testRequires(c, DaemonIsLinux, NotUserNamespace, SameHostDaemon)
  959. ensureNNPTest(c)
  960. // test that running a setuid binary results in no effective uid transition
  961. icmd.RunCommand(dockerBinary, "run", "--security-opt", "no-new-privileges=true", "--user", "1000",
  962. "nnp-test", "/usr/bin/nnp-test").Assert(c, icmd.Expected{
  963. Out: "EUID=1000",
  964. })
  965. }
  966. // TestLegacyRunNoNewPrivSetuid checks that --security-opt=no-new-privileges prevents
  967. // effective uid transtions on executing setuid binaries.
  968. func (s *DockerSuite) TestLegacyRunNoNewPrivSetuid(c *check.C) {
  969. testRequires(c, DaemonIsLinux, NotUserNamespace, SameHostDaemon)
  970. ensureNNPTest(c)
  971. // test that running a setuid binary results in no effective uid transition
  972. icmd.RunCommand(dockerBinary, "run", "--security-opt", "no-new-privileges", "--user", "1000",
  973. "nnp-test", "/usr/bin/nnp-test").Assert(c, icmd.Expected{
  974. Out: "EUID=1000",
  975. })
  976. }
  977. func (s *DockerSuite) TestUserNoEffectiveCapabilitiesChown(c *check.C) {
  978. testRequires(c, DaemonIsLinux)
  979. ensureSyscallTest(c)
  980. // test that a root user has default capability CAP_CHOWN
  981. dockerCmd(c, "run", "busybox", "chown", "100", "/tmp")
  982. // test that non root user does not have default capability CAP_CHOWN
  983. icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "chown", "100", "/tmp").Assert(c, icmd.Expected{
  984. ExitCode: 1,
  985. Err: "Operation not permitted",
  986. })
  987. // test that root user can drop default capability CAP_CHOWN
  988. icmd.RunCommand(dockerBinary, "run", "--cap-drop", "chown", "busybox", "chown", "100", "/tmp").Assert(c, icmd.Expected{
  989. ExitCode: 1,
  990. Err: "Operation not permitted",
  991. })
  992. }
  993. func (s *DockerSuite) TestUserNoEffectiveCapabilitiesDacOverride(c *check.C) {
  994. testRequires(c, DaemonIsLinux)
  995. ensureSyscallTest(c)
  996. // test that a root user has default capability CAP_DAC_OVERRIDE
  997. dockerCmd(c, "run", "busybox", "sh", "-c", "echo test > /etc/passwd")
  998. // test that non root user does not have default capability CAP_DAC_OVERRIDE
  999. icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "sh", "-c", "echo test > /etc/passwd").Assert(c, icmd.Expected{
  1000. ExitCode: 1,
  1001. Err: "Permission denied",
  1002. })
  1003. }
  1004. func (s *DockerSuite) TestUserNoEffectiveCapabilitiesFowner(c *check.C) {
  1005. testRequires(c, DaemonIsLinux)
  1006. ensureSyscallTest(c)
  1007. // test that a root user has default capability CAP_FOWNER
  1008. dockerCmd(c, "run", "busybox", "chmod", "777", "/etc/passwd")
  1009. // test that non root user does not have default capability CAP_FOWNER
  1010. icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "chmod", "777", "/etc/passwd").Assert(c, icmd.Expected{
  1011. ExitCode: 1,
  1012. Err: "Operation not permitted",
  1013. })
  1014. // TODO test that root user can drop default capability CAP_FOWNER
  1015. }
  1016. // TODO CAP_KILL
  1017. func (s *DockerSuite) TestUserNoEffectiveCapabilitiesSetuid(c *check.C) {
  1018. testRequires(c, DaemonIsLinux)
  1019. ensureSyscallTest(c)
  1020. // test that a root user has default capability CAP_SETUID
  1021. dockerCmd(c, "run", "syscall-test", "setuid-test")
  1022. // test that non root user does not have default capability CAP_SETUID
  1023. icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "setuid-test").Assert(c, icmd.Expected{
  1024. ExitCode: 1,
  1025. Err: "Operation not permitted",
  1026. })
  1027. // test that root user can drop default capability CAP_SETUID
  1028. icmd.RunCommand(dockerBinary, "run", "--cap-drop", "setuid", "syscall-test", "setuid-test").Assert(c, icmd.Expected{
  1029. ExitCode: 1,
  1030. Err: "Operation not permitted",
  1031. })
  1032. }
  1033. func (s *DockerSuite) TestUserNoEffectiveCapabilitiesSetgid(c *check.C) {
  1034. testRequires(c, DaemonIsLinux)
  1035. ensureSyscallTest(c)
  1036. // test that a root user has default capability CAP_SETGID
  1037. dockerCmd(c, "run", "syscall-test", "setgid-test")
  1038. // test that non root user does not have default capability CAP_SETGID
  1039. icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "setgid-test").Assert(c, icmd.Expected{
  1040. ExitCode: 1,
  1041. Err: "Operation not permitted",
  1042. })
  1043. // test that root user can drop default capability CAP_SETGID
  1044. icmd.RunCommand(dockerBinary, "run", "--cap-drop", "setgid", "syscall-test", "setgid-test").Assert(c, icmd.Expected{
  1045. ExitCode: 1,
  1046. Err: "Operation not permitted",
  1047. })
  1048. }
  1049. // TODO CAP_SETPCAP
  1050. func (s *DockerSuite) TestUserNoEffectiveCapabilitiesNetBindService(c *check.C) {
  1051. testRequires(c, DaemonIsLinux)
  1052. ensureSyscallTest(c)
  1053. // test that a root user has default capability CAP_NET_BIND_SERVICE
  1054. dockerCmd(c, "run", "syscall-test", "socket-test")
  1055. // test that non root user does not have default capability CAP_NET_BIND_SERVICE
  1056. icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "socket-test").Assert(c, icmd.Expected{
  1057. ExitCode: 1,
  1058. Err: "Permission denied",
  1059. })
  1060. // test that root user can drop default capability CAP_NET_BIND_SERVICE
  1061. icmd.RunCommand(dockerBinary, "run", "--cap-drop", "net_bind_service", "syscall-test", "socket-test").Assert(c, icmd.Expected{
  1062. ExitCode: 1,
  1063. Err: "Permission denied",
  1064. })
  1065. }
  1066. func (s *DockerSuite) TestUserNoEffectiveCapabilitiesNetRaw(c *check.C) {
  1067. testRequires(c, DaemonIsLinux)
  1068. ensureSyscallTest(c)
  1069. // test that a root user has default capability CAP_NET_RAW
  1070. dockerCmd(c, "run", "syscall-test", "raw-test")
  1071. // test that non root user does not have default capability CAP_NET_RAW
  1072. icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "raw-test").Assert(c, icmd.Expected{
  1073. ExitCode: 1,
  1074. Err: "Operation not permitted",
  1075. })
  1076. // test that root user can drop default capability CAP_NET_RAW
  1077. icmd.RunCommand(dockerBinary, "run", "--cap-drop", "net_raw", "syscall-test", "raw-test").Assert(c, icmd.Expected{
  1078. ExitCode: 1,
  1079. Err: "Operation not permitted",
  1080. })
  1081. }
  1082. func (s *DockerSuite) TestUserNoEffectiveCapabilitiesChroot(c *check.C) {
  1083. testRequires(c, DaemonIsLinux)
  1084. ensureSyscallTest(c)
  1085. // test that a root user has default capability CAP_SYS_CHROOT
  1086. dockerCmd(c, "run", "busybox", "chroot", "/", "/bin/true")
  1087. // test that non root user does not have default capability CAP_SYS_CHROOT
  1088. icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "chroot", "/", "/bin/true").Assert(c, icmd.Expected{
  1089. ExitCode: 1,
  1090. Err: "Operation not permitted",
  1091. })
  1092. // test that root user can drop default capability CAP_SYS_CHROOT
  1093. icmd.RunCommand(dockerBinary, "run", "--cap-drop", "sys_chroot", "busybox", "chroot", "/", "/bin/true").Assert(c, icmd.Expected{
  1094. ExitCode: 1,
  1095. Err: "Operation not permitted",
  1096. })
  1097. }
  1098. func (s *DockerSuite) TestUserNoEffectiveCapabilitiesMknod(c *check.C) {
  1099. testRequires(c, DaemonIsLinux, NotUserNamespace)
  1100. ensureSyscallTest(c)
  1101. // test that a root user has default capability CAP_MKNOD
  1102. dockerCmd(c, "run", "busybox", "mknod", "/tmp/node", "b", "1", "2")
  1103. // test that non root user does not have default capability CAP_MKNOD
  1104. // test that root user can drop default capability CAP_SYS_CHROOT
  1105. icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "mknod", "/tmp/node", "b", "1", "2").Assert(c, icmd.Expected{
  1106. ExitCode: 1,
  1107. Err: "Operation not permitted",
  1108. })
  1109. // test that root user can drop default capability CAP_MKNOD
  1110. icmd.RunCommand(dockerBinary, "run", "--cap-drop", "mknod", "busybox", "mknod", "/tmp/node", "b", "1", "2").Assert(c, icmd.Expected{
  1111. ExitCode: 1,
  1112. Err: "Operation not permitted",
  1113. })
  1114. }
  1115. // TODO CAP_AUDIT_WRITE
  1116. // TODO CAP_SETFCAP
  1117. func (s *DockerSuite) TestRunApparmorProcDirectory(c *check.C) {
  1118. testRequires(c, SameHostDaemon, Apparmor)
  1119. // running w seccomp unconfined tests the apparmor profile
  1120. result := icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/cgroup")
  1121. result.Assert(c, icmd.Expected{ExitCode: 1})
  1122. if !(strings.Contains(result.Combined(), "Permission denied") || strings.Contains(result.Combined(), "Operation not permitted")) {
  1123. c.Fatalf("expected chmod 777 /proc/1/cgroup to fail, got %s: %v", result.Combined(), result.Error)
  1124. }
  1125. result = icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/attr/current")
  1126. result.Assert(c, icmd.Expected{ExitCode: 1})
  1127. if !(strings.Contains(result.Combined(), "Permission denied") || strings.Contains(result.Combined(), "Operation not permitted")) {
  1128. c.Fatalf("expected chmod 777 /proc/1/attr/current to fail, got %s: %v", result.Combined(), result.Error)
  1129. }
  1130. }
  1131. // make sure the default profile can be successfully parsed (using unshare as it is
  1132. // something which we know is blocked in the default profile)
  1133. func (s *DockerSuite) TestRunSeccompWithDefaultProfile(c *check.C) {
  1134. testRequires(c, SameHostDaemon, seccompEnabled)
  1135. out, _, err := dockerCmdWithError("run", "--security-opt", "seccomp=../profiles/seccomp/default.json", "debian:jessie", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami")
  1136. c.Assert(err, checker.NotNil, check.Commentf(out))
  1137. c.Assert(strings.TrimSpace(out), checker.Equals, "unshare: unshare failed: Operation not permitted")
  1138. }
  1139. // TestRunDeviceSymlink checks run with device that follows symlink (#13840 and #22271)
  1140. func (s *DockerSuite) TestRunDeviceSymlink(c *check.C) {
  1141. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm, SameHostDaemon)
  1142. if _, err := os.Stat("/dev/zero"); err != nil {
  1143. c.Skip("Host does not have /dev/zero")
  1144. }
  1145. // Create a temporary directory to create symlink
  1146. tmpDir, err := ioutil.TempDir("", "docker_device_follow_symlink_tests")
  1147. c.Assert(err, checker.IsNil)
  1148. defer os.RemoveAll(tmpDir)
  1149. // Create a symbolic link to /dev/zero
  1150. symZero := filepath.Join(tmpDir, "zero")
  1151. err = os.Symlink("/dev/zero", symZero)
  1152. c.Assert(err, checker.IsNil)
  1153. // Create a temporary file "temp" inside tmpDir, write some data to "tmpDir/temp",
  1154. // then create a symlink "tmpDir/file" to the temporary file "tmpDir/temp".
  1155. tmpFile := filepath.Join(tmpDir, "temp")
  1156. err = ioutil.WriteFile(tmpFile, []byte("temp"), 0666)
  1157. c.Assert(err, checker.IsNil)
  1158. symFile := filepath.Join(tmpDir, "file")
  1159. err = os.Symlink(tmpFile, symFile)
  1160. c.Assert(err, checker.IsNil)
  1161. // Create a symbolic link to /dev/zero, this time with a relative path (#22271)
  1162. err = os.Symlink("zero", "/dev/symzero")
  1163. if err != nil {
  1164. c.Fatal("/dev/symzero creation failed")
  1165. }
  1166. // We need to remove this symbolic link here as it is created in /dev/, not temporary directory as above
  1167. defer os.Remove("/dev/symzero")
  1168. // md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23
  1169. out, _ := dockerCmd(c, "run", "--device", symZero+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  1170. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "bb7df04e1b0a2570657527a7e108ae23", check.Commentf("expected output bb7df04e1b0a2570657527a7e108ae23"))
  1171. // symlink "tmpDir/file" to a file "tmpDir/temp" will result in an error as it is not a device.
  1172. out, _, err = dockerCmdWithError("run", "--device", symFile+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  1173. c.Assert(err, check.NotNil)
  1174. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "not a device node", check.Commentf("expected output 'not a device node'"))
  1175. // md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23 (this time check with relative path backed, see #22271)
  1176. out, _ = dockerCmd(c, "run", "--device", "/dev/symzero:/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  1177. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "bb7df04e1b0a2570657527a7e108ae23", check.Commentf("expected output bb7df04e1b0a2570657527a7e108ae23"))
  1178. }
  1179. // TestRunPIDsLimit makes sure the pids cgroup is set with --pids-limit
  1180. func (s *DockerSuite) TestRunPIDsLimit(c *check.C) {
  1181. testRequires(c, pidsLimit)
  1182. file := "/sys/fs/cgroup/pids/pids.max"
  1183. out, _ := dockerCmd(c, "run", "--name", "skittles", "--pids-limit", "4", "busybox", "cat", file)
  1184. c.Assert(strings.TrimSpace(out), checker.Equals, "4")
  1185. out = inspectField(c, "skittles", "HostConfig.PidsLimit")
  1186. c.Assert(out, checker.Equals, "4", check.Commentf("setting the pids limit failed"))
  1187. }
  1188. func (s *DockerSuite) TestRunPrivilegedAllowedDevices(c *check.C) {
  1189. testRequires(c, DaemonIsLinux, NotUserNamespace)
  1190. file := "/sys/fs/cgroup/devices/devices.list"
  1191. out, _ := dockerCmd(c, "run", "--privileged", "busybox", "cat", file)
  1192. c.Logf("out: %q", out)
  1193. c.Assert(strings.TrimSpace(out), checker.Equals, "a *:* rwm")
  1194. }
  1195. func (s *DockerSuite) TestRunUserDeviceAllowed(c *check.C) {
  1196. testRequires(c, DaemonIsLinux)
  1197. fi, err := os.Stat("/dev/snd/timer")
  1198. if err != nil {
  1199. c.Skip("Host does not have /dev/snd/timer")
  1200. }
  1201. stat, ok := fi.Sys().(*syscall.Stat_t)
  1202. if !ok {
  1203. c.Skip("Could not stat /dev/snd/timer")
  1204. }
  1205. file := "/sys/fs/cgroup/devices/devices.list"
  1206. out, _ := dockerCmd(c, "run", "--device", "/dev/snd/timer:w", "busybox", "cat", file)
  1207. c.Assert(out, checker.Contains, fmt.Sprintf("c %d:%d w", stat.Rdev/256, stat.Rdev%256))
  1208. }
  1209. func (s *DockerDaemonSuite) TestRunSeccompJSONNewFormat(c *check.C) {
  1210. testRequires(c, SameHostDaemon, seccompEnabled)
  1211. s.d.StartWithBusybox(c)
  1212. jsonData := `{
  1213. "defaultAction": "SCMP_ACT_ALLOW",
  1214. "syscalls": [
  1215. {
  1216. "names": ["chmod", "fchmod", "fchmodat"],
  1217. "action": "SCMP_ACT_ERRNO"
  1218. }
  1219. ]
  1220. }`
  1221. tmpFile, err := ioutil.TempFile("", "profile.json")
  1222. c.Assert(err, check.IsNil)
  1223. defer tmpFile.Close()
  1224. _, err = tmpFile.Write([]byte(jsonData))
  1225. c.Assert(err, check.IsNil)
  1226. out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".")
  1227. c.Assert(err, check.NotNil)
  1228. c.Assert(out, checker.Contains, "Operation not permitted")
  1229. }
  1230. func (s *DockerDaemonSuite) TestRunSeccompJSONNoNameAndNames(c *check.C) {
  1231. testRequires(c, SameHostDaemon, seccompEnabled)
  1232. s.d.StartWithBusybox(c)
  1233. jsonData := `{
  1234. "defaultAction": "SCMP_ACT_ALLOW",
  1235. "syscalls": [
  1236. {
  1237. "name": "chmod",
  1238. "names": ["fchmod", "fchmodat"],
  1239. "action": "SCMP_ACT_ERRNO"
  1240. }
  1241. ]
  1242. }`
  1243. tmpFile, err := ioutil.TempFile("", "profile.json")
  1244. c.Assert(err, check.IsNil)
  1245. defer tmpFile.Close()
  1246. _, err = tmpFile.Write([]byte(jsonData))
  1247. c.Assert(err, check.IsNil)
  1248. out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".")
  1249. c.Assert(err, check.NotNil)
  1250. c.Assert(out, checker.Contains, "'name' and 'names' were specified in the seccomp profile, use either 'name' or 'names'")
  1251. }
  1252. func (s *DockerDaemonSuite) TestRunSeccompJSONNoArchAndArchMap(c *check.C) {
  1253. testRequires(c, SameHostDaemon, seccompEnabled)
  1254. s.d.StartWithBusybox(c)
  1255. jsonData := `{
  1256. "archMap": [
  1257. {
  1258. "architecture": "SCMP_ARCH_X86_64",
  1259. "subArchitectures": [
  1260. "SCMP_ARCH_X86",
  1261. "SCMP_ARCH_X32"
  1262. ]
  1263. }
  1264. ],
  1265. "architectures": [
  1266. "SCMP_ARCH_X32"
  1267. ],
  1268. "defaultAction": "SCMP_ACT_ALLOW",
  1269. "syscalls": [
  1270. {
  1271. "names": ["chmod", "fchmod", "fchmodat"],
  1272. "action": "SCMP_ACT_ERRNO"
  1273. }
  1274. ]
  1275. }`
  1276. tmpFile, err := ioutil.TempFile("", "profile.json")
  1277. c.Assert(err, check.IsNil)
  1278. defer tmpFile.Close()
  1279. _, err = tmpFile.Write([]byte(jsonData))
  1280. c.Assert(err, check.IsNil)
  1281. out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".")
  1282. c.Assert(err, check.NotNil)
  1283. c.Assert(out, checker.Contains, "'architectures' and 'archMap' were specified in the seccomp profile, use either 'architectures' or 'archMap'")
  1284. }
  1285. func (s *DockerDaemonSuite) TestRunWithDaemonDefaultSeccompProfile(c *check.C) {
  1286. testRequires(c, SameHostDaemon, seccompEnabled)
  1287. s.d.StartWithBusybox(c)
  1288. // 1) verify I can run containers with the Docker default shipped profile which allows chmod
  1289. _, err := s.d.Cmd("run", "busybox", "chmod", "777", ".")
  1290. c.Assert(err, check.IsNil)
  1291. jsonData := `{
  1292. "defaultAction": "SCMP_ACT_ALLOW",
  1293. "syscalls": [
  1294. {
  1295. "name": "chmod",
  1296. "action": "SCMP_ACT_ERRNO"
  1297. }
  1298. ]
  1299. }`
  1300. tmpFile, err := ioutil.TempFile("", "profile.json")
  1301. c.Assert(err, check.IsNil)
  1302. defer tmpFile.Close()
  1303. _, err = tmpFile.Write([]byte(jsonData))
  1304. c.Assert(err, check.IsNil)
  1305. // 2) restart the daemon and add a custom seccomp profile in which we deny chmod
  1306. s.d.Restart(c, "--seccomp-profile="+tmpFile.Name())
  1307. out, err := s.d.Cmd("run", "busybox", "chmod", "777", ".")
  1308. c.Assert(err, check.NotNil)
  1309. c.Assert(out, checker.Contains, "Operation not permitted")
  1310. }
  1311. func (s *DockerSuite) TestRunWithNanoCPUs(c *check.C) {
  1312. testRequires(c, cpuCfsQuota, cpuCfsPeriod)
  1313. file1 := "/sys/fs/cgroup/cpu/cpu.cfs_quota_us"
  1314. file2 := "/sys/fs/cgroup/cpu/cpu.cfs_period_us"
  1315. out, _ := dockerCmd(c, "run", "--cpus", "0.5", "--name", "test", "busybox", "sh", "-c", fmt.Sprintf("cat %s && cat %s", file1, file2))
  1316. c.Assert(strings.TrimSpace(out), checker.Equals, "50000\n100000")
  1317. out = inspectField(c, "test", "HostConfig.NanoCpus")
  1318. c.Assert(out, checker.Equals, "5e+08", check.Commentf("setting the Nano CPUs failed"))
  1319. out = inspectField(c, "test", "HostConfig.CpuQuota")
  1320. c.Assert(out, checker.Equals, "0", check.Commentf("CPU CFS quota should be 0"))
  1321. out = inspectField(c, "test", "HostConfig.CpuPeriod")
  1322. c.Assert(out, checker.Equals, "0", check.Commentf("CPU CFS period should be 0"))
  1323. out, _, err := dockerCmdWithError("run", "--cpus", "0.5", "--cpu-quota", "50000", "--cpu-period", "100000", "busybox", "sh")
  1324. c.Assert(err, check.NotNil)
  1325. c.Assert(out, checker.Contains, "Conflicting options: Nano CPUs and CPU Period cannot both be set")
  1326. }