docker_cli_run_unix_test.go 56 KB

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