docker_cli_run_unix_test.go 58 KB

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