docker_cli_run_unix_test.go 56 KB

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