docker_cli_run_unix_test.go 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582
  1. // +build !windows
  2. package main
  3. import (
  4. "bufio"
  5. "context"
  6. "encoding/json"
  7. "fmt"
  8. "io/ioutil"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "syscall"
  16. "time"
  17. "github.com/docker/docker/client"
  18. "github.com/docker/docker/integration-cli/checker"
  19. "github.com/docker/docker/integration-cli/cli"
  20. "github.com/docker/docker/integration-cli/cli/build"
  21. "github.com/docker/docker/pkg/homedir"
  22. "github.com/docker/docker/pkg/mount"
  23. "github.com/docker/docker/pkg/parsers"
  24. "github.com/docker/docker/pkg/sysinfo"
  25. "github.com/go-check/check"
  26. "github.com/gotestyourself/gotestyourself/icmd"
  27. "github.com/kr/pty"
  28. )
  29. // #6509
  30. func (s *DockerSuite) TestRunRedirectStdout(c *check.C) {
  31. checkRedirect := func(command string) {
  32. _, tty, err := pty.Open()
  33. c.Assert(err, checker.IsNil, check.Commentf("Could not open pty"))
  34. cmd := exec.Command("sh", "-c", command)
  35. cmd.Stdin = tty
  36. cmd.Stdout = tty
  37. cmd.Stderr = tty
  38. c.Assert(cmd.Start(), checker.IsNil)
  39. ch := make(chan error)
  40. go func() {
  41. ch <- cmd.Wait()
  42. close(ch)
  43. }()
  44. select {
  45. case <-time.After(10 * time.Second):
  46. c.Fatal("command timeout")
  47. case err := <-ch:
  48. c.Assert(err, checker.IsNil, check.Commentf("wait err"))
  49. }
  50. }
  51. checkRedirect(dockerBinary + " run -i busybox cat /etc/passwd | grep -q root")
  52. checkRedirect(dockerBinary + " run busybox cat /etc/passwd | grep -q root")
  53. }
  54. // Test recursive bind mount works by default
  55. func (s *DockerSuite) TestRunWithVolumesIsRecursive(c *check.C) {
  56. // /tmp gets permission denied
  57. testRequires(c, NotUserNamespace, SameHostDaemon)
  58. tmpDir, err := ioutil.TempDir("", "docker_recursive_mount_test")
  59. c.Assert(err, checker.IsNil)
  60. defer os.RemoveAll(tmpDir)
  61. // Create a temporary tmpfs mount.
  62. tmpfsDir := filepath.Join(tmpDir, "tmpfs")
  63. c.Assert(os.MkdirAll(tmpfsDir, 0777), checker.IsNil, check.Commentf("failed to mkdir at %s", tmpfsDir))
  64. c.Assert(mount.Mount("tmpfs", tmpfsDir, "tmpfs", ""), checker.IsNil, check.Commentf("failed to create a tmpfs mount at %s", tmpfsDir))
  65. f, err := ioutil.TempFile(tmpfsDir, "touch-me")
  66. c.Assert(err, checker.IsNil)
  67. defer f.Close()
  68. out, _ := dockerCmd(c, "run", "--name", "test-data", "--volume", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox:latest", "ls", "/tmp/tmpfs")
  69. c.Assert(out, checker.Contains, filepath.Base(f.Name()), check.Commentf("Recursive bind mount test failed. Expected file not found"))
  70. }
  71. func (s *DockerSuite) TestRunDeviceDirectory(c *check.C) {
  72. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  73. if _, err := os.Stat("/dev/snd"); err != nil {
  74. c.Skip("Host does not have /dev/snd")
  75. }
  76. out, _ := dockerCmd(c, "run", "--device", "/dev/snd:/dev/snd", "busybox", "sh", "-c", "ls /dev/snd/")
  77. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "timer", check.Commentf("expected output /dev/snd/timer"))
  78. out, _ = dockerCmd(c, "run", "--device", "/dev/snd:/dev/othersnd", "busybox", "sh", "-c", "ls /dev/othersnd/")
  79. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "seq", check.Commentf("expected output /dev/othersnd/seq"))
  80. }
  81. // TestRunAttachDetach checks attaching and detaching with the default escape sequence.
  82. func (s *DockerSuite) TestRunAttachDetach(c *check.C) {
  83. name := "attach-detach"
  84. dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
  85. cmd := exec.Command(dockerBinary, "attach", name)
  86. stdout, err := cmd.StdoutPipe()
  87. c.Assert(err, checker.IsNil)
  88. cpty, tty, err := pty.Open()
  89. c.Assert(err, checker.IsNil)
  90. defer cpty.Close()
  91. cmd.Stdin = tty
  92. c.Assert(cmd.Start(), checker.IsNil)
  93. c.Assert(waitRun(name), check.IsNil)
  94. _, err = cpty.Write([]byte("hello\n"))
  95. c.Assert(err, checker.IsNil)
  96. out, err := bufio.NewReader(stdout).ReadString('\n')
  97. c.Assert(err, checker.IsNil)
  98. c.Assert(strings.TrimSpace(out), checker.Equals, "hello")
  99. // escape sequence
  100. _, err = cpty.Write([]byte{16})
  101. c.Assert(err, checker.IsNil)
  102. time.Sleep(100 * time.Millisecond)
  103. _, err = cpty.Write([]byte{17})
  104. c.Assert(err, checker.IsNil)
  105. ch := make(chan struct{})
  106. go func() {
  107. cmd.Wait()
  108. ch <- struct{}{}
  109. }()
  110. select {
  111. case <-ch:
  112. case <-time.After(10 * time.Second):
  113. c.Fatal("timed out waiting for container to exit")
  114. }
  115. running := inspectField(c, name, "State.Running")
  116. c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running"))
  117. out, _ = dockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c), "-f", "container="+name)
  118. // attach and detach event should be monitored
  119. c.Assert(out, checker.Contains, "attach")
  120. c.Assert(out, checker.Contains, "detach")
  121. }
  122. // TestRunAttachDetachFromFlag checks attaching and detaching with the escape sequence specified via flags.
  123. func (s *DockerSuite) TestRunAttachDetachFromFlag(c *check.C) {
  124. name := "attach-detach"
  125. keyCtrlA := []byte{1}
  126. keyA := []byte{97}
  127. dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
  128. cmd := exec.Command(dockerBinary, "attach", "--detach-keys=ctrl-a,a", name)
  129. stdout, err := cmd.StdoutPipe()
  130. if err != nil {
  131. c.Fatal(err)
  132. }
  133. cpty, tty, err := pty.Open()
  134. if err != nil {
  135. c.Fatal(err)
  136. }
  137. defer cpty.Close()
  138. cmd.Stdin = tty
  139. if err := cmd.Start(); err != nil {
  140. c.Fatal(err)
  141. }
  142. c.Assert(waitRun(name), check.IsNil)
  143. if _, err := cpty.Write([]byte("hello\n")); err != nil {
  144. c.Fatal(err)
  145. }
  146. out, err := bufio.NewReader(stdout).ReadString('\n')
  147. if err != nil {
  148. c.Fatal(err)
  149. }
  150. if strings.TrimSpace(out) != "hello" {
  151. c.Fatalf("expected 'hello', got %q", out)
  152. }
  153. // escape sequence
  154. if _, err := cpty.Write(keyCtrlA); err != nil {
  155. c.Fatal(err)
  156. }
  157. time.Sleep(100 * time.Millisecond)
  158. if _, err := cpty.Write(keyA); err != nil {
  159. c.Fatal(err)
  160. }
  161. ch := make(chan struct{})
  162. go func() {
  163. cmd.Wait()
  164. ch <- struct{}{}
  165. }()
  166. select {
  167. case <-ch:
  168. case <-time.After(10 * time.Second):
  169. c.Fatal("timed out waiting for container to exit")
  170. }
  171. running := inspectField(c, name, "State.Running")
  172. c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running"))
  173. }
  174. // TestRunAttachDetachFromInvalidFlag checks attaching and detaching with the escape sequence specified via flags.
  175. func (s *DockerSuite) TestRunAttachDetachFromInvalidFlag(c *check.C) {
  176. name := "attach-detach"
  177. dockerCmd(c, "run", "--name", name, "-itd", "busybox", "top")
  178. c.Assert(waitRun(name), check.IsNil)
  179. // specify an invalid detach key, container will ignore it and use default
  180. cmd := exec.Command(dockerBinary, "attach", "--detach-keys=ctrl-A,a", name)
  181. stdout, err := cmd.StdoutPipe()
  182. if err != nil {
  183. c.Fatal(err)
  184. }
  185. cpty, tty, err := pty.Open()
  186. if err != nil {
  187. c.Fatal(err)
  188. }
  189. defer cpty.Close()
  190. cmd.Stdin = tty
  191. if err := cmd.Start(); err != nil {
  192. c.Fatal(err)
  193. }
  194. bufReader := bufio.NewReader(stdout)
  195. out, err := bufReader.ReadString('\n')
  196. if err != nil {
  197. c.Fatal(err)
  198. }
  199. // it should print a warning to indicate the detach key flag is invalid
  200. errStr := "Invalid detach keys (ctrl-A,a) provided"
  201. c.Assert(strings.TrimSpace(out), checker.Equals, errStr)
  202. }
  203. // TestRunAttachDetachFromConfig checks attaching and detaching with the escape sequence specified via config file.
  204. func (s *DockerSuite) TestRunAttachDetachFromConfig(c *check.C) {
  205. keyCtrlA := []byte{1}
  206. keyA := []byte{97}
  207. // Setup config
  208. homeKey := homedir.Key()
  209. homeVal := homedir.Get()
  210. tmpDir, err := ioutil.TempDir("", "fake-home")
  211. c.Assert(err, checker.IsNil)
  212. defer os.RemoveAll(tmpDir)
  213. dotDocker := filepath.Join(tmpDir, ".docker")
  214. os.Mkdir(dotDocker, 0600)
  215. tmpCfg := filepath.Join(dotDocker, "config.json")
  216. defer func() { os.Setenv(homeKey, homeVal) }()
  217. os.Setenv(homeKey, tmpDir)
  218. data := `{
  219. "detachKeys": "ctrl-a,a"
  220. }`
  221. err = ioutil.WriteFile(tmpCfg, []byte(data), 0600)
  222. c.Assert(err, checker.IsNil)
  223. // Then do the work
  224. name := "attach-detach"
  225. dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
  226. cmd := exec.Command(dockerBinary, "attach", name)
  227. stdout, err := cmd.StdoutPipe()
  228. if err != nil {
  229. c.Fatal(err)
  230. }
  231. cpty, tty, err := pty.Open()
  232. if err != nil {
  233. c.Fatal(err)
  234. }
  235. defer cpty.Close()
  236. cmd.Stdin = tty
  237. if err := cmd.Start(); err != nil {
  238. c.Fatal(err)
  239. }
  240. c.Assert(waitRun(name), check.IsNil)
  241. if _, err := cpty.Write([]byte("hello\n")); err != nil {
  242. c.Fatal(err)
  243. }
  244. out, err := bufio.NewReader(stdout).ReadString('\n')
  245. if err != nil {
  246. c.Fatal(err)
  247. }
  248. if strings.TrimSpace(out) != "hello" {
  249. c.Fatalf("expected 'hello', got %q", out)
  250. }
  251. // escape sequence
  252. if _, err := cpty.Write(keyCtrlA); err != nil {
  253. c.Fatal(err)
  254. }
  255. time.Sleep(100 * time.Millisecond)
  256. if _, err := cpty.Write(keyA); err != nil {
  257. c.Fatal(err)
  258. }
  259. ch := make(chan struct{})
  260. go func() {
  261. cmd.Wait()
  262. ch <- struct{}{}
  263. }()
  264. select {
  265. case <-ch:
  266. case <-time.After(10 * time.Second):
  267. c.Fatal("timed out waiting for container to exit")
  268. }
  269. running := inspectField(c, name, "State.Running")
  270. c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running"))
  271. }
  272. // TestRunAttachDetachKeysOverrideConfig checks attaching and detaching with the detach flags, making sure it overrides config file
  273. func (s *DockerSuite) TestRunAttachDetachKeysOverrideConfig(c *check.C) {
  274. keyCtrlA := []byte{1}
  275. keyA := []byte{97}
  276. // Setup config
  277. homeKey := homedir.Key()
  278. homeVal := homedir.Get()
  279. tmpDir, err := ioutil.TempDir("", "fake-home")
  280. c.Assert(err, checker.IsNil)
  281. defer os.RemoveAll(tmpDir)
  282. dotDocker := filepath.Join(tmpDir, ".docker")
  283. os.Mkdir(dotDocker, 0600)
  284. tmpCfg := filepath.Join(dotDocker, "config.json")
  285. defer func() { os.Setenv(homeKey, homeVal) }()
  286. os.Setenv(homeKey, tmpDir)
  287. data := `{
  288. "detachKeys": "ctrl-e,e"
  289. }`
  290. err = ioutil.WriteFile(tmpCfg, []byte(data), 0600)
  291. c.Assert(err, checker.IsNil)
  292. // Then do the work
  293. name := "attach-detach"
  294. dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
  295. cmd := exec.Command(dockerBinary, "attach", "--detach-keys=ctrl-a,a", name)
  296. stdout, err := cmd.StdoutPipe()
  297. if err != nil {
  298. c.Fatal(err)
  299. }
  300. cpty, tty, err := pty.Open()
  301. if err != nil {
  302. c.Fatal(err)
  303. }
  304. defer cpty.Close()
  305. cmd.Stdin = tty
  306. if err := cmd.Start(); err != nil {
  307. c.Fatal(err)
  308. }
  309. c.Assert(waitRun(name), check.IsNil)
  310. if _, err := cpty.Write([]byte("hello\n")); err != nil {
  311. c.Fatal(err)
  312. }
  313. out, err := bufio.NewReader(stdout).ReadString('\n')
  314. if err != nil {
  315. c.Fatal(err)
  316. }
  317. if strings.TrimSpace(out) != "hello" {
  318. c.Fatalf("expected 'hello', got %q", out)
  319. }
  320. // escape sequence
  321. if _, err := cpty.Write(keyCtrlA); err != nil {
  322. c.Fatal(err)
  323. }
  324. time.Sleep(100 * time.Millisecond)
  325. if _, err := cpty.Write(keyA); err != nil {
  326. c.Fatal(err)
  327. }
  328. ch := make(chan struct{})
  329. go func() {
  330. cmd.Wait()
  331. ch <- struct{}{}
  332. }()
  333. select {
  334. case <-ch:
  335. case <-time.After(10 * time.Second):
  336. c.Fatal("timed out waiting for container to exit")
  337. }
  338. running := inspectField(c, name, "State.Running")
  339. c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running"))
  340. }
  341. func (s *DockerSuite) TestRunAttachInvalidDetachKeySequencePreserved(c *check.C) {
  342. name := "attach-detach"
  343. keyA := []byte{97}
  344. keyB := []byte{98}
  345. dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
  346. cmd := exec.Command(dockerBinary, "attach", "--detach-keys=a,b,c", name)
  347. stdout, err := cmd.StdoutPipe()
  348. if err != nil {
  349. c.Fatal(err)
  350. }
  351. cpty, tty, err := pty.Open()
  352. if err != nil {
  353. c.Fatal(err)
  354. }
  355. defer cpty.Close()
  356. cmd.Stdin = tty
  357. if err := cmd.Start(); err != nil {
  358. c.Fatal(err)
  359. }
  360. c.Assert(waitRun(name), check.IsNil)
  361. // Invalid escape sequence aba, should print aba in output
  362. if _, err := cpty.Write(keyA); err != nil {
  363. c.Fatal(err)
  364. }
  365. time.Sleep(100 * time.Millisecond)
  366. if _, err := cpty.Write(keyB); err != nil {
  367. c.Fatal(err)
  368. }
  369. time.Sleep(100 * time.Millisecond)
  370. if _, err := cpty.Write(keyA); err != nil {
  371. c.Fatal(err)
  372. }
  373. time.Sleep(100 * time.Millisecond)
  374. if _, err := cpty.Write([]byte("\n")); err != nil {
  375. c.Fatal(err)
  376. }
  377. out, err := bufio.NewReader(stdout).ReadString('\n')
  378. if err != nil {
  379. c.Fatal(err)
  380. }
  381. if strings.TrimSpace(out) != "aba" {
  382. c.Fatalf("expected 'aba', got %q", out)
  383. }
  384. }
  385. // "test" should be printed
  386. func (s *DockerSuite) TestRunWithCPUQuota(c *check.C) {
  387. testRequires(c, cpuCfsQuota)
  388. file := "/sys/fs/cgroup/cpu/cpu.cfs_quota_us"
  389. out, _ := dockerCmd(c, "run", "--cpu-quota", "8000", "--name", "test", "busybox", "cat", file)
  390. c.Assert(strings.TrimSpace(out), checker.Equals, "8000")
  391. out = inspectField(c, "test", "HostConfig.CpuQuota")
  392. c.Assert(out, checker.Equals, "8000", check.Commentf("setting the CPU CFS quota failed"))
  393. }
  394. func (s *DockerSuite) TestRunWithCpuPeriod(c *check.C) {
  395. testRequires(c, cpuCfsPeriod)
  396. file := "/sys/fs/cgroup/cpu/cpu.cfs_period_us"
  397. out, _ := dockerCmd(c, "run", "--cpu-period", "50000", "--name", "test", "busybox", "cat", file)
  398. c.Assert(strings.TrimSpace(out), checker.Equals, "50000")
  399. out, _ = dockerCmd(c, "run", "--cpu-period", "0", "busybox", "cat", file)
  400. c.Assert(strings.TrimSpace(out), checker.Equals, "100000")
  401. out = inspectField(c, "test", "HostConfig.CpuPeriod")
  402. c.Assert(out, checker.Equals, "50000", check.Commentf("setting the CPU CFS period failed"))
  403. }
  404. func (s *DockerSuite) TestRunWithInvalidCpuPeriod(c *check.C) {
  405. testRequires(c, cpuCfsPeriod)
  406. out, _, err := dockerCmdWithError("run", "--cpu-period", "900", "busybox", "true")
  407. c.Assert(err, check.NotNil)
  408. expected := "CPU cfs period can not be less than 1ms (i.e. 1000) or larger than 1s (i.e. 1000000)"
  409. c.Assert(out, checker.Contains, expected)
  410. out, _, err = dockerCmdWithError("run", "--cpu-period", "2000000", "busybox", "true")
  411. c.Assert(err, check.NotNil)
  412. c.Assert(out, checker.Contains, expected)
  413. out, _, err = dockerCmdWithError("run", "--cpu-period", "-3", "busybox", "true")
  414. c.Assert(err, check.NotNil)
  415. c.Assert(out, checker.Contains, expected)
  416. }
  417. func (s *DockerSuite) TestRunWithKernelMemory(c *check.C) {
  418. testRequires(c, kernelMemorySupport)
  419. file := "/sys/fs/cgroup/memory/memory.kmem.limit_in_bytes"
  420. cli.DockerCmd(c, "run", "--kernel-memory", "50M", "--name", "test1", "busybox", "cat", file).Assert(c, icmd.Expected{
  421. Out: "52428800",
  422. })
  423. cli.InspectCmd(c, "test1", cli.Format(".HostConfig.KernelMemory")).Assert(c, icmd.Expected{
  424. Out: "52428800",
  425. })
  426. }
  427. func (s *DockerSuite) TestRunWithInvalidKernelMemory(c *check.C) {
  428. testRequires(c, kernelMemorySupport)
  429. out, _, err := dockerCmdWithError("run", "--kernel-memory", "2M", "busybox", "true")
  430. c.Assert(err, check.NotNil)
  431. expected := "Minimum kernel memory limit allowed is 4MB"
  432. c.Assert(out, checker.Contains, expected)
  433. out, _, err = dockerCmdWithError("run", "--kernel-memory", "-16m", "--name", "test2", "busybox", "echo", "test")
  434. c.Assert(err, check.NotNil)
  435. expected = "invalid size"
  436. c.Assert(out, checker.Contains, expected)
  437. }
  438. func (s *DockerSuite) TestRunWithCPUShares(c *check.C) {
  439. testRequires(c, cpuShare)
  440. file := "/sys/fs/cgroup/cpu/cpu.shares"
  441. out, _ := dockerCmd(c, "run", "--cpu-shares", "1000", "--name", "test", "busybox", "cat", file)
  442. c.Assert(strings.TrimSpace(out), checker.Equals, "1000")
  443. out = inspectField(c, "test", "HostConfig.CPUShares")
  444. c.Assert(out, check.Equals, "1000")
  445. }
  446. // "test" should be printed
  447. func (s *DockerSuite) TestRunEchoStdoutWithCPUSharesAndMemoryLimit(c *check.C) {
  448. testRequires(c, cpuShare)
  449. testRequires(c, memoryLimitSupport)
  450. cli.DockerCmd(c, "run", "--cpu-shares", "1000", "-m", "32m", "busybox", "echo", "test").Assert(c, icmd.Expected{
  451. Out: "test\n",
  452. })
  453. }
  454. func (s *DockerSuite) TestRunWithCpusetCpus(c *check.C) {
  455. testRequires(c, cgroupCpuset)
  456. file := "/sys/fs/cgroup/cpuset/cpuset.cpus"
  457. out, _ := dockerCmd(c, "run", "--cpuset-cpus", "0", "--name", "test", "busybox", "cat", file)
  458. c.Assert(strings.TrimSpace(out), checker.Equals, "0")
  459. out = inspectField(c, "test", "HostConfig.CpusetCpus")
  460. c.Assert(out, check.Equals, "0")
  461. }
  462. func (s *DockerSuite) TestRunWithCpusetMems(c *check.C) {
  463. testRequires(c, cgroupCpuset)
  464. file := "/sys/fs/cgroup/cpuset/cpuset.mems"
  465. out, _ := dockerCmd(c, "run", "--cpuset-mems", "0", "--name", "test", "busybox", "cat", file)
  466. c.Assert(strings.TrimSpace(out), checker.Equals, "0")
  467. out = inspectField(c, "test", "HostConfig.CpusetMems")
  468. c.Assert(out, check.Equals, "0")
  469. }
  470. func (s *DockerSuite) TestRunWithBlkioWeight(c *check.C) {
  471. testRequires(c, blkioWeight)
  472. file := "/sys/fs/cgroup/blkio/blkio.weight"
  473. out, _ := dockerCmd(c, "run", "--blkio-weight", "300", "--name", "test", "busybox", "cat", file)
  474. c.Assert(strings.TrimSpace(out), checker.Equals, "300")
  475. out = inspectField(c, "test", "HostConfig.BlkioWeight")
  476. c.Assert(out, check.Equals, "300")
  477. }
  478. func (s *DockerSuite) TestRunWithInvalidBlkioWeight(c *check.C) {
  479. testRequires(c, blkioWeight)
  480. out, _, err := dockerCmdWithError("run", "--blkio-weight", "5", "busybox", "true")
  481. c.Assert(err, check.NotNil, check.Commentf(out))
  482. expected := "Range of blkio weight is from 10 to 1000"
  483. c.Assert(out, checker.Contains, expected)
  484. }
  485. func (s *DockerSuite) TestRunWithInvalidPathforBlkioWeightDevice(c *check.C) {
  486. testRequires(c, blkioWeight)
  487. out, _, err := dockerCmdWithError("run", "--blkio-weight-device", "/dev/sdX:100", "busybox", "true")
  488. c.Assert(err, check.NotNil, check.Commentf(out))
  489. }
  490. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceReadBps(c *check.C) {
  491. testRequires(c, blkioWeight)
  492. out, _, err := dockerCmdWithError("run", "--device-read-bps", "/dev/sdX:500", "busybox", "true")
  493. c.Assert(err, check.NotNil, check.Commentf(out))
  494. }
  495. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceWriteBps(c *check.C) {
  496. testRequires(c, blkioWeight)
  497. out, _, err := dockerCmdWithError("run", "--device-write-bps", "/dev/sdX:500", "busybox", "true")
  498. c.Assert(err, check.NotNil, check.Commentf(out))
  499. }
  500. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceReadIOps(c *check.C) {
  501. testRequires(c, blkioWeight)
  502. out, _, err := dockerCmdWithError("run", "--device-read-iops", "/dev/sdX:500", "busybox", "true")
  503. c.Assert(err, check.NotNil, check.Commentf(out))
  504. }
  505. func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceWriteIOps(c *check.C) {
  506. testRequires(c, blkioWeight)
  507. out, _, err := dockerCmdWithError("run", "--device-write-iops", "/dev/sdX:500", "busybox", "true")
  508. c.Assert(err, check.NotNil, check.Commentf(out))
  509. }
  510. func (s *DockerSuite) TestRunOOMExitCode(c *check.C) {
  511. testRequires(c, memoryLimitSupport, swapMemorySupport)
  512. errChan := make(chan error)
  513. go func() {
  514. defer close(errChan)
  515. out, exitCode, _ := dockerCmdWithError("run", "-m", "4MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done")
  516. if expected := 137; exitCode != expected {
  517. errChan <- fmt.Errorf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out)
  518. }
  519. }()
  520. select {
  521. case err := <-errChan:
  522. c.Assert(err, check.IsNil)
  523. case <-time.After(600 * time.Second):
  524. c.Fatal("Timeout waiting for container to die on OOM")
  525. }
  526. }
  527. func (s *DockerSuite) TestRunWithMemoryLimit(c *check.C) {
  528. testRequires(c, memoryLimitSupport)
  529. file := "/sys/fs/cgroup/memory/memory.limit_in_bytes"
  530. cli.DockerCmd(c, "run", "-m", "32M", "--name", "test", "busybox", "cat", file).Assert(c, icmd.Expected{
  531. Out: "33554432",
  532. })
  533. cli.InspectCmd(c, "test", cli.Format(".HostConfig.Memory")).Assert(c, icmd.Expected{
  534. Out: "33554432",
  535. })
  536. }
  537. // TestRunWithoutMemoryswapLimit sets memory limit and disables swap
  538. // memory limit, this means the processes in the container can use
  539. // 16M memory and as much swap memory as they need (if the host
  540. // supports swap memory).
  541. func (s *DockerSuite) TestRunWithoutMemoryswapLimit(c *check.C) {
  542. testRequires(c, DaemonIsLinux)
  543. testRequires(c, memoryLimitSupport)
  544. testRequires(c, swapMemorySupport)
  545. dockerCmd(c, "run", "-m", "32m", "--memory-swap", "-1", "busybox", "true")
  546. }
  547. func (s *DockerSuite) TestRunWithSwappiness(c *check.C) {
  548. testRequires(c, memorySwappinessSupport)
  549. file := "/sys/fs/cgroup/memory/memory.swappiness"
  550. out, _ := dockerCmd(c, "run", "--memory-swappiness", "0", "--name", "test", "busybox", "cat", file)
  551. c.Assert(strings.TrimSpace(out), checker.Equals, "0")
  552. out = inspectField(c, "test", "HostConfig.MemorySwappiness")
  553. c.Assert(out, check.Equals, "0")
  554. }
  555. func (s *DockerSuite) TestRunWithSwappinessInvalid(c *check.C) {
  556. testRequires(c, memorySwappinessSupport)
  557. out, _, err := dockerCmdWithError("run", "--memory-swappiness", "101", "busybox", "true")
  558. c.Assert(err, check.NotNil)
  559. expected := "Valid memory swappiness range is 0-100"
  560. c.Assert(out, checker.Contains, expected, check.Commentf("Expected output to contain %q, not %q", out, expected))
  561. out, _, err = dockerCmdWithError("run", "--memory-swappiness", "-10", "busybox", "true")
  562. c.Assert(err, check.NotNil)
  563. c.Assert(out, checker.Contains, expected, check.Commentf("Expected output to contain %q, not %q", out, expected))
  564. }
  565. func (s *DockerSuite) TestRunWithMemoryReservation(c *check.C) {
  566. testRequires(c, SameHostDaemon, memoryReservationSupport)
  567. file := "/sys/fs/cgroup/memory/memory.soft_limit_in_bytes"
  568. out, _ := dockerCmd(c, "run", "--memory-reservation", "200M", "--name", "test", "busybox", "cat", file)
  569. c.Assert(strings.TrimSpace(out), checker.Equals, "209715200")
  570. out = inspectField(c, "test", "HostConfig.MemoryReservation")
  571. c.Assert(out, check.Equals, "209715200")
  572. }
  573. func (s *DockerSuite) TestRunWithMemoryReservationInvalid(c *check.C) {
  574. testRequires(c, memoryLimitSupport)
  575. testRequires(c, SameHostDaemon, memoryReservationSupport)
  576. out, _, err := dockerCmdWithError("run", "-m", "500M", "--memory-reservation", "800M", "busybox", "true")
  577. c.Assert(err, check.NotNil)
  578. expected := "Minimum memory limit can not be less than memory reservation limit"
  579. c.Assert(strings.TrimSpace(out), checker.Contains, expected, check.Commentf("run container should fail with invalid memory reservation"))
  580. out, _, err = dockerCmdWithError("run", "--memory-reservation", "1k", "busybox", "true")
  581. c.Assert(err, check.NotNil)
  582. expected = "Minimum memory reservation allowed is 4MB"
  583. c.Assert(strings.TrimSpace(out), checker.Contains, expected, check.Commentf("run container should fail with invalid memory reservation"))
  584. }
  585. func (s *DockerSuite) TestStopContainerSignal(c *check.C) {
  586. 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`)
  587. containerID := strings.TrimSpace(out)
  588. c.Assert(waitRun(containerID), checker.IsNil)
  589. dockerCmd(c, "stop", containerID)
  590. out, _ = dockerCmd(c, "logs", containerID)
  591. c.Assert(out, checker.Contains, "exit trapped", check.Commentf("Expected `exit trapped` in the log"))
  592. }
  593. func (s *DockerSuite) TestRunSwapLessThanMemoryLimit(c *check.C) {
  594. testRequires(c, memoryLimitSupport)
  595. testRequires(c, swapMemorySupport)
  596. out, _, err := dockerCmdWithError("run", "-m", "16m", "--memory-swap", "15m", "busybox", "echo", "test")
  597. expected := "Minimum memoryswap limit should be larger than memory limit"
  598. c.Assert(err, check.NotNil)
  599. c.Assert(out, checker.Contains, expected)
  600. }
  601. func (s *DockerSuite) TestRunInvalidCpusetCpusFlagValue(c *check.C) {
  602. testRequires(c, cgroupCpuset, SameHostDaemon)
  603. sysInfo := sysinfo.New(true)
  604. cpus, err := parsers.ParseUintList(sysInfo.Cpus)
  605. c.Assert(err, check.IsNil)
  606. var invalid int
  607. for i := 0; i <= len(cpus)+1; i++ {
  608. if !cpus[i] {
  609. invalid = i
  610. break
  611. }
  612. }
  613. out, _, err := dockerCmdWithError("run", "--cpuset-cpus", strconv.Itoa(invalid), "busybox", "true")
  614. c.Assert(err, check.NotNil)
  615. expected := fmt.Sprintf("Error response from daemon: Requested CPUs are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Cpus)
  616. c.Assert(out, checker.Contains, expected)
  617. }
  618. func (s *DockerSuite) TestRunInvalidCpusetMemsFlagValue(c *check.C) {
  619. testRequires(c, cgroupCpuset)
  620. sysInfo := sysinfo.New(true)
  621. mems, err := parsers.ParseUintList(sysInfo.Mems)
  622. c.Assert(err, check.IsNil)
  623. var invalid int
  624. for i := 0; i <= len(mems)+1; i++ {
  625. if !mems[i] {
  626. invalid = i
  627. break
  628. }
  629. }
  630. out, _, err := dockerCmdWithError("run", "--cpuset-mems", strconv.Itoa(invalid), "busybox", "true")
  631. c.Assert(err, check.NotNil)
  632. expected := fmt.Sprintf("Error response from daemon: Requested memory nodes are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Mems)
  633. c.Assert(out, checker.Contains, expected)
  634. }
  635. func (s *DockerSuite) TestRunInvalidCPUShares(c *check.C) {
  636. testRequires(c, cpuShare, DaemonIsLinux)
  637. out, _, err := dockerCmdWithError("run", "--cpu-shares", "1", "busybox", "echo", "test")
  638. c.Assert(err, check.NotNil, check.Commentf(out))
  639. expected := "The minimum allowed cpu-shares is 2"
  640. c.Assert(out, checker.Contains, expected)
  641. out, _, err = dockerCmdWithError("run", "--cpu-shares", "-1", "busybox", "echo", "test")
  642. c.Assert(err, check.NotNil, check.Commentf(out))
  643. expected = "shares: invalid argument"
  644. c.Assert(out, checker.Contains, expected)
  645. out, _, err = dockerCmdWithError("run", "--cpu-shares", "99999999", "busybox", "echo", "test")
  646. c.Assert(err, check.NotNil, check.Commentf(out))
  647. expected = "The maximum allowed cpu-shares is"
  648. c.Assert(out, checker.Contains, expected)
  649. }
  650. func (s *DockerSuite) TestRunWithDefaultShmSize(c *check.C) {
  651. testRequires(c, DaemonIsLinux)
  652. name := "shm-default"
  653. out, _ := dockerCmd(c, "run", "--name", name, "busybox", "mount")
  654. shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
  655. if !shmRegex.MatchString(out) {
  656. c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
  657. }
  658. shmSize := inspectField(c, name, "HostConfig.ShmSize")
  659. c.Assert(shmSize, check.Equals, "67108864")
  660. }
  661. func (s *DockerSuite) TestRunWithShmSize(c *check.C) {
  662. testRequires(c, DaemonIsLinux)
  663. name := "shm"
  664. out, _ := dockerCmd(c, "run", "--name", name, "--shm-size=1G", "busybox", "mount")
  665. shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=1048576k`)
  666. if !shmRegex.MatchString(out) {
  667. c.Fatalf("Expected shm of 1GB in mount command, got %v", out)
  668. }
  669. shmSize := inspectField(c, name, "HostConfig.ShmSize")
  670. c.Assert(shmSize, check.Equals, "1073741824")
  671. }
  672. func (s *DockerSuite) TestRunTmpfsMountsEnsureOrdered(c *check.C) {
  673. tmpFile, err := ioutil.TempFile("", "test")
  674. c.Assert(err, check.IsNil)
  675. defer tmpFile.Close()
  676. out, _ := dockerCmd(c, "run", "--tmpfs", "/run", "-v", tmpFile.Name()+":/run/test", "busybox", "ls", "/run")
  677. c.Assert(out, checker.Contains, "test")
  678. }
  679. func (s *DockerSuite) TestRunTmpfsMounts(c *check.C) {
  680. // TODO Windows (Post TP5): This test cannot run on a Windows daemon as
  681. // Windows does not support tmpfs mounts.
  682. testRequires(c, DaemonIsLinux)
  683. if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run", "busybox", "touch", "/run/somefile"); err != nil {
  684. c.Fatalf("/run directory not mounted on tmpfs %q %s", err, out)
  685. }
  686. if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run:noexec", "busybox", "touch", "/run/somefile"); err != nil {
  687. c.Fatalf("/run directory not mounted on tmpfs %q %s", err, out)
  688. }
  689. if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run:noexec,nosuid,rw,size=5k,mode=700", "busybox", "touch", "/run/somefile"); err != nil {
  690. c.Fatalf("/run failed to mount on tmpfs with valid options %q %s", err, out)
  691. }
  692. if _, _, err := dockerCmdWithError("run", "--tmpfs", "/run:foobar", "busybox", "touch", "/run/somefile"); err == nil {
  693. c.Fatalf("/run mounted on tmpfs when it should have vailed within invalid mount option")
  694. }
  695. if _, _, err := dockerCmdWithError("run", "--tmpfs", "/run", "-v", "/run:/run", "busybox", "touch", "/run/somefile"); err == nil {
  696. c.Fatalf("Should have generated an error saying Duplicate mount points")
  697. }
  698. }
  699. func (s *DockerSuite) TestRunTmpfsMountsOverrideImageVolumes(c *check.C) {
  700. name := "img-with-volumes"
  701. buildImageSuccessfully(c, name, build.WithDockerfile(`
  702. FROM busybox
  703. VOLUME /run
  704. RUN touch /run/stuff
  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. icmd.RunCommand(dockerBinary, "run", "--sysctl", "kernel.foobar=1", "--name", "test2",
  761. "busybox", "cat", "/proc/sys/kernel/foobar").Assert(c, icmd.Expected{
  762. ExitCode: 125,
  763. Err: "invalid argument",
  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. if err != nil {
  780. c.Fatal(err)
  781. }
  782. defer tmpFile.Close()
  783. if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
  784. c.Fatal(err)
  785. }
  786. icmd.RunCommand(dockerBinary, "run", "--security-opt", "apparmor=unconfined",
  787. "--security-opt", "seccomp="+tmpFile.Name(),
  788. "debian:jessie", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc").Assert(c, icmd.Expected{
  789. ExitCode: 1,
  790. Err: "Operation not permitted",
  791. })
  792. }
  793. // TestRunSeccompProfileDenyChmod checks that 'docker run --security-opt seccomp=/tmp/profile.json busybox chmod 400 /etc/hostname' exits with operation not permitted.
  794. func (s *DockerSuite) TestRunSeccompProfileDenyChmod(c *check.C) {
  795. testRequires(c, SameHostDaemon, seccompEnabled)
  796. jsonData := `{
  797. "defaultAction": "SCMP_ACT_ALLOW",
  798. "syscalls": [
  799. {
  800. "name": "chmod",
  801. "action": "SCMP_ACT_ERRNO"
  802. },
  803. {
  804. "name":"fchmod",
  805. "action": "SCMP_ACT_ERRNO"
  806. },
  807. {
  808. "name": "fchmodat",
  809. "action":"SCMP_ACT_ERRNO"
  810. }
  811. ]
  812. }`
  813. tmpFile, err := ioutil.TempFile("", "profile.json")
  814. c.Assert(err, check.IsNil)
  815. defer tmpFile.Close()
  816. if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
  817. c.Fatal(err)
  818. }
  819. icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp="+tmpFile.Name(),
  820. "busybox", "chmod", "400", "/etc/hostname").Assert(c, icmd.Expected{
  821. ExitCode: 1,
  822. Err: "Operation not permitted",
  823. })
  824. }
  825. // TestRunSeccompProfileDenyUnshareUserns checks that 'docker run debian:jessie unshare --map-root-user --user sh -c whoami' with a specific profile to
  826. // deny unshare of a userns exits with operation not permitted.
  827. func (s *DockerSuite) TestRunSeccompProfileDenyUnshareUserns(c *check.C) {
  828. testRequires(c, SameHostDaemon, seccompEnabled, NotArm, Apparmor)
  829. // from sched.h
  830. jsonData := fmt.Sprintf(`{
  831. "defaultAction": "SCMP_ACT_ALLOW",
  832. "syscalls": [
  833. {
  834. "name": "unshare",
  835. "action": "SCMP_ACT_ERRNO",
  836. "args": [
  837. {
  838. "index": 0,
  839. "value": %d,
  840. "op": "SCMP_CMP_EQ"
  841. }
  842. ]
  843. }
  844. ]
  845. }`, uint64(0x10000000))
  846. tmpFile, err := ioutil.TempFile("", "profile.json")
  847. if err != nil {
  848. c.Fatal(err)
  849. }
  850. defer tmpFile.Close()
  851. if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
  852. c.Fatal(err)
  853. }
  854. icmd.RunCommand(dockerBinary, "run",
  855. "--security-opt", "apparmor=unconfined", "--security-opt", "seccomp="+tmpFile.Name(),
  856. "debian:jessie", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami").Assert(c, icmd.Expected{
  857. ExitCode: 1,
  858. Err: "Operation not permitted",
  859. })
  860. }
  861. // TestRunSeccompProfileDenyCloneUserns checks that 'docker run syscall-test'
  862. // with a the default seccomp profile exits with operation not permitted.
  863. func (s *DockerSuite) TestRunSeccompProfileDenyCloneUserns(c *check.C) {
  864. testRequires(c, SameHostDaemon, seccompEnabled)
  865. ensureSyscallTest(c)
  866. icmd.RunCommand(dockerBinary, "run", "syscall-test", "userns-test", "id").Assert(c, icmd.Expected{
  867. ExitCode: 1,
  868. Err: "clone failed: Operation not permitted",
  869. })
  870. }
  871. // TestRunSeccompUnconfinedCloneUserns checks that
  872. // 'docker run --security-opt seccomp=unconfined syscall-test' allows creating a userns.
  873. func (s *DockerSuite) TestRunSeccompUnconfinedCloneUserns(c *check.C) {
  874. testRequires(c, SameHostDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace, unprivilegedUsernsClone)
  875. ensureSyscallTest(c)
  876. // make sure running w privileged is ok
  877. icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp=unconfined",
  878. "syscall-test", "userns-test", "id").Assert(c, icmd.Expected{
  879. Out: "nobody",
  880. })
  881. }
  882. // TestRunSeccompAllowPrivCloneUserns checks that 'docker run --privileged syscall-test'
  883. // allows creating a userns.
  884. func (s *DockerSuite) TestRunSeccompAllowPrivCloneUserns(c *check.C) {
  885. testRequires(c, SameHostDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace)
  886. ensureSyscallTest(c)
  887. // make sure running w privileged is ok
  888. icmd.RunCommand(dockerBinary, "run", "--privileged", "syscall-test", "userns-test", "id").Assert(c, icmd.Expected{
  889. Out: "nobody",
  890. })
  891. }
  892. // TestRunSeccompProfileAllow32Bit checks that 32 bit code can run on x86_64
  893. // with the default seccomp profile.
  894. func (s *DockerSuite) TestRunSeccompProfileAllow32Bit(c *check.C) {
  895. testRequires(c, SameHostDaemon, seccompEnabled, IsAmd64)
  896. ensureSyscallTest(c)
  897. icmd.RunCommand(dockerBinary, "run", "syscall-test", "exit32-test", "id").Assert(c, icmd.Success)
  898. }
  899. // TestRunSeccompAllowSetrlimit checks that 'docker run debian:jessie ulimit -v 1048510' succeeds.
  900. func (s *DockerSuite) TestRunSeccompAllowSetrlimit(c *check.C) {
  901. testRequires(c, SameHostDaemon, seccompEnabled)
  902. // ulimit uses setrlimit, so we want to make sure we don't break it
  903. icmd.RunCommand(dockerBinary, "run", "debian:jessie", "bash", "-c", "ulimit -v 1048510").Assert(c, icmd.Success)
  904. }
  905. func (s *DockerSuite) TestRunSeccompDefaultProfileAcct(c *check.C) {
  906. testRequires(c, SameHostDaemon, seccompEnabled, NotUserNamespace)
  907. ensureSyscallTest(c)
  908. out, _, err := dockerCmdWithError("run", "syscall-test", "acct-test")
  909. if err == nil || !strings.Contains(out, "Operation not permitted") {
  910. c.Fatalf("test 0: expected Operation not permitted, got: %s", out)
  911. }
  912. out, _, err = dockerCmdWithError("run", "--cap-add", "sys_admin", "syscall-test", "acct-test")
  913. if err == nil || !strings.Contains(out, "Operation not permitted") {
  914. c.Fatalf("test 1: expected Operation not permitted, got: %s", out)
  915. }
  916. out, _, err = dockerCmdWithError("run", "--cap-add", "sys_pacct", "syscall-test", "acct-test")
  917. if err == nil || !strings.Contains(out, "No such file or directory") {
  918. c.Fatalf("test 2: expected No such file or directory, got: %s", out)
  919. }
  920. out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "syscall-test", "acct-test")
  921. if err == nil || !strings.Contains(out, "No such file or directory") {
  922. c.Fatalf("test 3: expected No such file or directory, got: %s", out)
  923. }
  924. out, _, err = dockerCmdWithError("run", "--cap-drop", "ALL", "--cap-add", "sys_pacct", "syscall-test", "acct-test")
  925. if err == nil || !strings.Contains(out, "No such file or directory") {
  926. c.Fatalf("test 4: expected No such file or directory, got: %s", out)
  927. }
  928. }
  929. func (s *DockerSuite) TestRunSeccompDefaultProfileNS(c *check.C) {
  930. testRequires(c, SameHostDaemon, seccompEnabled, NotUserNamespace)
  931. ensureSyscallTest(c)
  932. out, _, err := dockerCmdWithError("run", "syscall-test", "ns-test", "echo", "hello0")
  933. if err == nil || !strings.Contains(out, "Operation not permitted") {
  934. c.Fatalf("test 0: expected Operation not permitted, got: %s", out)
  935. }
  936. out, _, err = dockerCmdWithError("run", "--cap-add", "sys_admin", "syscall-test", "ns-test", "echo", "hello1")
  937. if err != nil || !strings.Contains(out, "hello1") {
  938. c.Fatalf("test 1: expected hello1, got: %s, %v", out, err)
  939. }
  940. out, _, err = dockerCmdWithError("run", "--cap-drop", "all", "--cap-add", "sys_admin", "syscall-test", "ns-test", "echo", "hello2")
  941. if err != nil || !strings.Contains(out, "hello2") {
  942. c.Fatalf("test 2: expected hello2, got: %s, %v", out, err)
  943. }
  944. out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "syscall-test", "ns-test", "echo", "hello3")
  945. if err != nil || !strings.Contains(out, "hello3") {
  946. c.Fatalf("test 3: expected hello3, got: %s, %v", out, err)
  947. }
  948. out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "--security-opt", "seccomp=unconfined", "syscall-test", "acct-test")
  949. if err == nil || !strings.Contains(out, "No such file or directory") {
  950. c.Fatalf("test 4: expected No such file or directory, got: %s", out)
  951. }
  952. out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "--security-opt", "seccomp=unconfined", "syscall-test", "ns-test", "echo", "hello4")
  953. if err != nil || !strings.Contains(out, "hello4") {
  954. c.Fatalf("test 5: expected hello4, got: %s, %v", out, err)
  955. }
  956. }
  957. // TestRunNoNewPrivSetuid checks that --security-opt='no-new-privileges=true' prevents
  958. // effective uid transtions on executing setuid binaries.
  959. func (s *DockerSuite) TestRunNoNewPrivSetuid(c *check.C) {
  960. testRequires(c, DaemonIsLinux, NotUserNamespace, SameHostDaemon)
  961. ensureNNPTest(c)
  962. // test that running a setuid binary results in no effective uid transition
  963. icmd.RunCommand(dockerBinary, "run", "--security-opt", "no-new-privileges=true", "--user", "1000",
  964. "nnp-test", "/usr/bin/nnp-test").Assert(c, icmd.Expected{
  965. Out: "EUID=1000",
  966. })
  967. }
  968. // TestLegacyRunNoNewPrivSetuid checks that --security-opt=no-new-privileges prevents
  969. // effective uid transtions on executing setuid binaries.
  970. func (s *DockerSuite) TestLegacyRunNoNewPrivSetuid(c *check.C) {
  971. testRequires(c, DaemonIsLinux, NotUserNamespace, SameHostDaemon)
  972. ensureNNPTest(c)
  973. // test that running a setuid binary results in no effective uid transition
  974. icmd.RunCommand(dockerBinary, "run", "--security-opt", "no-new-privileges", "--user", "1000",
  975. "nnp-test", "/usr/bin/nnp-test").Assert(c, icmd.Expected{
  976. Out: "EUID=1000",
  977. })
  978. }
  979. func (s *DockerSuite) TestUserNoEffectiveCapabilitiesChown(c *check.C) {
  980. testRequires(c, DaemonIsLinux)
  981. ensureSyscallTest(c)
  982. // test that a root user has default capability CAP_CHOWN
  983. dockerCmd(c, "run", "busybox", "chown", "100", "/tmp")
  984. // test that non root user does not have default capability CAP_CHOWN
  985. icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "chown", "100", "/tmp").Assert(c, icmd.Expected{
  986. ExitCode: 1,
  987. Err: "Operation not permitted",
  988. })
  989. // test that root user can drop default capability CAP_CHOWN
  990. icmd.RunCommand(dockerBinary, "run", "--cap-drop", "chown", "busybox", "chown", "100", "/tmp").Assert(c, icmd.Expected{
  991. ExitCode: 1,
  992. Err: "Operation not permitted",
  993. })
  994. }
  995. func (s *DockerSuite) TestUserNoEffectiveCapabilitiesDacOverride(c *check.C) {
  996. testRequires(c, DaemonIsLinux)
  997. ensureSyscallTest(c)
  998. // test that a root user has default capability CAP_DAC_OVERRIDE
  999. dockerCmd(c, "run", "busybox", "sh", "-c", "echo test > /etc/passwd")
  1000. // test that non root user does not have default capability CAP_DAC_OVERRIDE
  1001. icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "sh", "-c", "echo test > /etc/passwd").Assert(c, icmd.Expected{
  1002. ExitCode: 1,
  1003. Err: "Permission denied",
  1004. })
  1005. }
  1006. func (s *DockerSuite) TestUserNoEffectiveCapabilitiesFowner(c *check.C) {
  1007. testRequires(c, DaemonIsLinux)
  1008. ensureSyscallTest(c)
  1009. // test that a root user has default capability CAP_FOWNER
  1010. dockerCmd(c, "run", "busybox", "chmod", "777", "/etc/passwd")
  1011. // test that non root user does not have default capability CAP_FOWNER
  1012. icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "chmod", "777", "/etc/passwd").Assert(c, icmd.Expected{
  1013. ExitCode: 1,
  1014. Err: "Operation not permitted",
  1015. })
  1016. // TODO test that root user can drop default capability CAP_FOWNER
  1017. }
  1018. // TODO CAP_KILL
  1019. func (s *DockerSuite) TestUserNoEffectiveCapabilitiesSetuid(c *check.C) {
  1020. testRequires(c, DaemonIsLinux)
  1021. ensureSyscallTest(c)
  1022. // test that a root user has default capability CAP_SETUID
  1023. dockerCmd(c, "run", "syscall-test", "setuid-test")
  1024. // test that non root user does not have default capability CAP_SETUID
  1025. icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "setuid-test").Assert(c, icmd.Expected{
  1026. ExitCode: 1,
  1027. Err: "Operation not permitted",
  1028. })
  1029. // test that root user can drop default capability CAP_SETUID
  1030. icmd.RunCommand(dockerBinary, "run", "--cap-drop", "setuid", "syscall-test", "setuid-test").Assert(c, icmd.Expected{
  1031. ExitCode: 1,
  1032. Err: "Operation not permitted",
  1033. })
  1034. }
  1035. func (s *DockerSuite) TestUserNoEffectiveCapabilitiesSetgid(c *check.C) {
  1036. testRequires(c, DaemonIsLinux)
  1037. ensureSyscallTest(c)
  1038. // test that a root user has default capability CAP_SETGID
  1039. dockerCmd(c, "run", "syscall-test", "setgid-test")
  1040. // test that non root user does not have default capability CAP_SETGID
  1041. icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "setgid-test").Assert(c, icmd.Expected{
  1042. ExitCode: 1,
  1043. Err: "Operation not permitted",
  1044. })
  1045. // test that root user can drop default capability CAP_SETGID
  1046. icmd.RunCommand(dockerBinary, "run", "--cap-drop", "setgid", "syscall-test", "setgid-test").Assert(c, icmd.Expected{
  1047. ExitCode: 1,
  1048. Err: "Operation not permitted",
  1049. })
  1050. }
  1051. // TODO CAP_SETPCAP
  1052. func (s *DockerSuite) TestUserNoEffectiveCapabilitiesNetBindService(c *check.C) {
  1053. testRequires(c, DaemonIsLinux)
  1054. ensureSyscallTest(c)
  1055. // test that a root user has default capability CAP_NET_BIND_SERVICE
  1056. dockerCmd(c, "run", "syscall-test", "socket-test")
  1057. // test that non root user does not have default capability CAP_NET_BIND_SERVICE
  1058. icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "socket-test").Assert(c, icmd.Expected{
  1059. ExitCode: 1,
  1060. Err: "Permission denied",
  1061. })
  1062. // test that root user can drop default capability CAP_NET_BIND_SERVICE
  1063. icmd.RunCommand(dockerBinary, "run", "--cap-drop", "net_bind_service", "syscall-test", "socket-test").Assert(c, icmd.Expected{
  1064. ExitCode: 1,
  1065. Err: "Permission denied",
  1066. })
  1067. }
  1068. func (s *DockerSuite) TestUserNoEffectiveCapabilitiesNetRaw(c *check.C) {
  1069. testRequires(c, DaemonIsLinux)
  1070. ensureSyscallTest(c)
  1071. // test that a root user has default capability CAP_NET_RAW
  1072. dockerCmd(c, "run", "syscall-test", "raw-test")
  1073. // test that non root user does not have default capability CAP_NET_RAW
  1074. icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "raw-test").Assert(c, icmd.Expected{
  1075. ExitCode: 1,
  1076. Err: "Operation not permitted",
  1077. })
  1078. // test that root user can drop default capability CAP_NET_RAW
  1079. icmd.RunCommand(dockerBinary, "run", "--cap-drop", "net_raw", "syscall-test", "raw-test").Assert(c, icmd.Expected{
  1080. ExitCode: 1,
  1081. Err: "Operation not permitted",
  1082. })
  1083. }
  1084. func (s *DockerSuite) TestUserNoEffectiveCapabilitiesChroot(c *check.C) {
  1085. testRequires(c, DaemonIsLinux)
  1086. ensureSyscallTest(c)
  1087. // test that a root user has default capability CAP_SYS_CHROOT
  1088. dockerCmd(c, "run", "busybox", "chroot", "/", "/bin/true")
  1089. // test that non root user does not have default capability CAP_SYS_CHROOT
  1090. icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "chroot", "/", "/bin/true").Assert(c, icmd.Expected{
  1091. ExitCode: 1,
  1092. Err: "Operation not permitted",
  1093. })
  1094. // test that root user can drop default capability CAP_SYS_CHROOT
  1095. icmd.RunCommand(dockerBinary, "run", "--cap-drop", "sys_chroot", "busybox", "chroot", "/", "/bin/true").Assert(c, icmd.Expected{
  1096. ExitCode: 1,
  1097. Err: "Operation not permitted",
  1098. })
  1099. }
  1100. func (s *DockerSuite) TestUserNoEffectiveCapabilitiesMknod(c *check.C) {
  1101. testRequires(c, DaemonIsLinux, NotUserNamespace)
  1102. ensureSyscallTest(c)
  1103. // test that a root user has default capability CAP_MKNOD
  1104. dockerCmd(c, "run", "busybox", "mknod", "/tmp/node", "b", "1", "2")
  1105. // test that non root user does not have default capability CAP_MKNOD
  1106. // test that root user can drop default capability CAP_SYS_CHROOT
  1107. icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "mknod", "/tmp/node", "b", "1", "2").Assert(c, icmd.Expected{
  1108. ExitCode: 1,
  1109. Err: "Operation not permitted",
  1110. })
  1111. // test that root user can drop default capability CAP_MKNOD
  1112. icmd.RunCommand(dockerBinary, "run", "--cap-drop", "mknod", "busybox", "mknod", "/tmp/node", "b", "1", "2").Assert(c, icmd.Expected{
  1113. ExitCode: 1,
  1114. Err: "Operation not permitted",
  1115. })
  1116. }
  1117. // TODO CAP_AUDIT_WRITE
  1118. // TODO CAP_SETFCAP
  1119. func (s *DockerSuite) TestRunApparmorProcDirectory(c *check.C) {
  1120. testRequires(c, SameHostDaemon, Apparmor)
  1121. // running w seccomp unconfined tests the apparmor profile
  1122. result := icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/cgroup")
  1123. result.Assert(c, icmd.Expected{ExitCode: 1})
  1124. if !(strings.Contains(result.Combined(), "Permission denied") || strings.Contains(result.Combined(), "Operation not permitted")) {
  1125. c.Fatalf("expected chmod 777 /proc/1/cgroup to fail, got %s: %v", result.Combined(), result.Error)
  1126. }
  1127. result = icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/attr/current")
  1128. result.Assert(c, icmd.Expected{ExitCode: 1})
  1129. if !(strings.Contains(result.Combined(), "Permission denied") || strings.Contains(result.Combined(), "Operation not permitted")) {
  1130. c.Fatalf("expected chmod 777 /proc/1/attr/current to fail, got %s: %v", result.Combined(), result.Error)
  1131. }
  1132. }
  1133. // make sure the default profile can be successfully parsed (using unshare as it is
  1134. // something which we know is blocked in the default profile)
  1135. func (s *DockerSuite) TestRunSeccompWithDefaultProfile(c *check.C) {
  1136. testRequires(c, SameHostDaemon, seccompEnabled)
  1137. out, _, err := dockerCmdWithError("run", "--security-opt", "seccomp=../profiles/seccomp/default.json", "debian:jessie", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami")
  1138. c.Assert(err, checker.NotNil, check.Commentf(out))
  1139. c.Assert(strings.TrimSpace(out), checker.Equals, "unshare: unshare failed: Operation not permitted")
  1140. }
  1141. // TestRunDeviceSymlink checks run with device that follows symlink (#13840 and #22271)
  1142. func (s *DockerSuite) TestRunDeviceSymlink(c *check.C) {
  1143. testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm, SameHostDaemon)
  1144. if _, err := os.Stat("/dev/zero"); err != nil {
  1145. c.Skip("Host does not have /dev/zero")
  1146. }
  1147. // Create a temporary directory to create symlink
  1148. tmpDir, err := ioutil.TempDir("", "docker_device_follow_symlink_tests")
  1149. c.Assert(err, checker.IsNil)
  1150. defer os.RemoveAll(tmpDir)
  1151. // Create a symbolic link to /dev/zero
  1152. symZero := filepath.Join(tmpDir, "zero")
  1153. err = os.Symlink("/dev/zero", symZero)
  1154. c.Assert(err, checker.IsNil)
  1155. // Create a temporary file "temp" inside tmpDir, write some data to "tmpDir/temp",
  1156. // then create a symlink "tmpDir/file" to the temporary file "tmpDir/temp".
  1157. tmpFile := filepath.Join(tmpDir, "temp")
  1158. err = ioutil.WriteFile(tmpFile, []byte("temp"), 0666)
  1159. c.Assert(err, checker.IsNil)
  1160. symFile := filepath.Join(tmpDir, "file")
  1161. err = os.Symlink(tmpFile, symFile)
  1162. c.Assert(err, checker.IsNil)
  1163. // Create a symbolic link to /dev/zero, this time with a relative path (#22271)
  1164. err = os.Symlink("zero", "/dev/symzero")
  1165. if err != nil {
  1166. c.Fatal("/dev/symzero creation failed")
  1167. }
  1168. // We need to remove this symbolic link here as it is created in /dev/, not temporary directory as above
  1169. defer os.Remove("/dev/symzero")
  1170. // md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23
  1171. out, _ := dockerCmd(c, "run", "--device", symZero+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  1172. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "bb7df04e1b0a2570657527a7e108ae23", check.Commentf("expected output bb7df04e1b0a2570657527a7e108ae23"))
  1173. // symlink "tmpDir/file" to a file "tmpDir/temp" will result in an error as it is not a device.
  1174. out, _, err = dockerCmdWithError("run", "--device", symFile+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  1175. c.Assert(err, check.NotNil)
  1176. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "not a device node", check.Commentf("expected output 'not a device node'"))
  1177. // md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23 (this time check with relative path backed, see #22271)
  1178. out, _ = dockerCmd(c, "run", "--device", "/dev/symzero:/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  1179. c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "bb7df04e1b0a2570657527a7e108ae23", check.Commentf("expected output bb7df04e1b0a2570657527a7e108ae23"))
  1180. }
  1181. // TestRunPIDsLimit makes sure the pids cgroup is set with --pids-limit
  1182. func (s *DockerSuite) TestRunPIDsLimit(c *check.C) {
  1183. testRequires(c, SameHostDaemon, pidsLimit)
  1184. file := "/sys/fs/cgroup/pids/pids.max"
  1185. out, _ := dockerCmd(c, "run", "--name", "skittles", "--pids-limit", "4", "busybox", "cat", file)
  1186. c.Assert(strings.TrimSpace(out), checker.Equals, "4")
  1187. out = inspectField(c, "skittles", "HostConfig.PidsLimit")
  1188. c.Assert(out, checker.Equals, "4", check.Commentf("setting the pids limit failed"))
  1189. }
  1190. func (s *DockerSuite) TestRunPrivilegedAllowedDevices(c *check.C) {
  1191. testRequires(c, DaemonIsLinux, NotUserNamespace)
  1192. file := "/sys/fs/cgroup/devices/devices.list"
  1193. out, _ := dockerCmd(c, "run", "--privileged", "busybox", "cat", file)
  1194. c.Logf("out: %q", out)
  1195. c.Assert(strings.TrimSpace(out), checker.Equals, "a *:* rwm")
  1196. }
  1197. func (s *DockerSuite) TestRunUserDeviceAllowed(c *check.C) {
  1198. testRequires(c, DaemonIsLinux)
  1199. fi, err := os.Stat("/dev/snd/timer")
  1200. if err != nil {
  1201. c.Skip("Host does not have /dev/snd/timer")
  1202. }
  1203. stat, ok := fi.Sys().(*syscall.Stat_t)
  1204. if !ok {
  1205. c.Skip("Could not stat /dev/snd/timer")
  1206. }
  1207. file := "/sys/fs/cgroup/devices/devices.list"
  1208. out, _ := dockerCmd(c, "run", "--device", "/dev/snd/timer:w", "busybox", "cat", file)
  1209. c.Assert(out, checker.Contains, fmt.Sprintf("c %d:%d w", stat.Rdev/256, stat.Rdev%256))
  1210. }
  1211. func (s *DockerDaemonSuite) TestRunSeccompJSONNewFormat(c *check.C) {
  1212. testRequires(c, SameHostDaemon, seccompEnabled)
  1213. s.d.StartWithBusybox(c)
  1214. jsonData := `{
  1215. "defaultAction": "SCMP_ACT_ALLOW",
  1216. "syscalls": [
  1217. {
  1218. "names": ["chmod", "fchmod", "fchmodat"],
  1219. "action": "SCMP_ACT_ERRNO"
  1220. }
  1221. ]
  1222. }`
  1223. tmpFile, err := ioutil.TempFile("", "profile.json")
  1224. c.Assert(err, check.IsNil)
  1225. defer tmpFile.Close()
  1226. _, err = tmpFile.Write([]byte(jsonData))
  1227. c.Assert(err, check.IsNil)
  1228. out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".")
  1229. c.Assert(err, check.NotNil)
  1230. c.Assert(out, checker.Contains, "Operation not permitted")
  1231. }
  1232. func (s *DockerDaemonSuite) TestRunSeccompJSONNoNameAndNames(c *check.C) {
  1233. testRequires(c, SameHostDaemon, seccompEnabled)
  1234. s.d.StartWithBusybox(c)
  1235. jsonData := `{
  1236. "defaultAction": "SCMP_ACT_ALLOW",
  1237. "syscalls": [
  1238. {
  1239. "name": "chmod",
  1240. "names": ["fchmod", "fchmodat"],
  1241. "action": "SCMP_ACT_ERRNO"
  1242. }
  1243. ]
  1244. }`
  1245. tmpFile, err := ioutil.TempFile("", "profile.json")
  1246. c.Assert(err, check.IsNil)
  1247. defer tmpFile.Close()
  1248. _, err = tmpFile.Write([]byte(jsonData))
  1249. c.Assert(err, check.IsNil)
  1250. out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".")
  1251. c.Assert(err, check.NotNil)
  1252. c.Assert(out, checker.Contains, "'name' and 'names' were specified in the seccomp profile, use either 'name' or 'names'")
  1253. }
  1254. func (s *DockerDaemonSuite) TestRunSeccompJSONNoArchAndArchMap(c *check.C) {
  1255. testRequires(c, SameHostDaemon, seccompEnabled)
  1256. s.d.StartWithBusybox(c)
  1257. jsonData := `{
  1258. "archMap": [
  1259. {
  1260. "architecture": "SCMP_ARCH_X86_64",
  1261. "subArchitectures": [
  1262. "SCMP_ARCH_X86",
  1263. "SCMP_ARCH_X32"
  1264. ]
  1265. }
  1266. ],
  1267. "architectures": [
  1268. "SCMP_ARCH_X32"
  1269. ],
  1270. "defaultAction": "SCMP_ACT_ALLOW",
  1271. "syscalls": [
  1272. {
  1273. "names": ["chmod", "fchmod", "fchmodat"],
  1274. "action": "SCMP_ACT_ERRNO"
  1275. }
  1276. ]
  1277. }`
  1278. tmpFile, err := ioutil.TempFile("", "profile.json")
  1279. c.Assert(err, check.IsNil)
  1280. defer tmpFile.Close()
  1281. _, err = tmpFile.Write([]byte(jsonData))
  1282. c.Assert(err, check.IsNil)
  1283. out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".")
  1284. c.Assert(err, check.NotNil)
  1285. c.Assert(out, checker.Contains, "'architectures' and 'archMap' were specified in the seccomp profile, use either 'architectures' or 'archMap'")
  1286. }
  1287. func (s *DockerDaemonSuite) TestRunWithDaemonDefaultSeccompProfile(c *check.C) {
  1288. testRequires(c, SameHostDaemon, seccompEnabled)
  1289. s.d.StartWithBusybox(c)
  1290. // 1) verify I can run containers with the Docker default shipped profile which allows chmod
  1291. _, err := s.d.Cmd("run", "busybox", "chmod", "777", ".")
  1292. c.Assert(err, check.IsNil)
  1293. jsonData := `{
  1294. "defaultAction": "SCMP_ACT_ALLOW",
  1295. "syscalls": [
  1296. {
  1297. "name": "chmod",
  1298. "action": "SCMP_ACT_ERRNO"
  1299. }
  1300. ]
  1301. }`
  1302. tmpFile, err := ioutil.TempFile("", "profile.json")
  1303. c.Assert(err, check.IsNil)
  1304. defer tmpFile.Close()
  1305. _, err = tmpFile.Write([]byte(jsonData))
  1306. c.Assert(err, check.IsNil)
  1307. // 2) restart the daemon and add a custom seccomp profile in which we deny chmod
  1308. s.d.Restart(c, "--seccomp-profile="+tmpFile.Name())
  1309. out, err := s.d.Cmd("run", "busybox", "chmod", "777", ".")
  1310. c.Assert(err, check.NotNil)
  1311. c.Assert(out, checker.Contains, "Operation not permitted")
  1312. }
  1313. func (s *DockerSuite) TestRunWithNanoCPUs(c *check.C) {
  1314. testRequires(c, cpuCfsQuota, cpuCfsPeriod)
  1315. file1 := "/sys/fs/cgroup/cpu/cpu.cfs_quota_us"
  1316. file2 := "/sys/fs/cgroup/cpu/cpu.cfs_period_us"
  1317. out, _ := dockerCmd(c, "run", "--cpus", "0.5", "--name", "test", "busybox", "sh", "-c", fmt.Sprintf("cat %s && cat %s", file1, file2))
  1318. c.Assert(strings.TrimSpace(out), checker.Equals, "50000\n100000")
  1319. clt, err := client.NewEnvClient()
  1320. c.Assert(err, checker.IsNil)
  1321. inspect, err := clt.ContainerInspect(context.Background(), "test")
  1322. c.Assert(err, checker.IsNil)
  1323. c.Assert(inspect.HostConfig.NanoCPUs, checker.Equals, int64(500000000))
  1324. out = inspectField(c, "test", "HostConfig.CpuQuota")
  1325. c.Assert(out, checker.Equals, "0", check.Commentf("CPU CFS quota should be 0"))
  1326. out = inspectField(c, "test", "HostConfig.CpuPeriod")
  1327. c.Assert(out, checker.Equals, "0", check.Commentf("CPU CFS period should be 0"))
  1328. out, _, err = dockerCmdWithError("run", "--cpus", "0.5", "--cpu-quota", "50000", "--cpu-period", "100000", "busybox", "sh")
  1329. c.Assert(err, check.NotNil)
  1330. c.Assert(out, checker.Contains, "Conflicting options: Nano CPUs and CPU Period cannot both be set")
  1331. }