docker_cli_run_unix_test.go 56 KB

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