docker_cli_run_unix_test.go 56 KB

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