docker_cli_run_unix_test.go 58 KB

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