docker_cli_run_test.go 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839
  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "os"
  9. "os/exec"
  10. "path"
  11. "path/filepath"
  12. "reflect"
  13. "regexp"
  14. "sort"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "time"
  19. "github.com/docker/docker/pkg/nat"
  20. "github.com/docker/libnetwork/resolvconf"
  21. "github.com/go-check/check"
  22. )
  23. // "test123" should be printed by docker run
  24. func (s *DockerSuite) TestRunEchoStdout(c *check.C) {
  25. out, _ := dockerCmd(c, "run", "busybox", "echo", "test123")
  26. if out != "test123\n" {
  27. c.Fatalf("container should've printed 'test123'")
  28. }
  29. }
  30. // "test" should be printed
  31. func (s *DockerSuite) TestRunEchoStdoutWithMemoryLimit(c *check.C) {
  32. out, _, _ := dockerCmdWithStdoutStderr(c, "run", "-m", "16m", "busybox", "echo", "test")
  33. out = strings.Trim(out, "\r\n")
  34. if expected := "test"; out != expected {
  35. c.Fatalf("container should've printed %q but printed %q", expected, out)
  36. }
  37. }
  38. // should run without memory swap
  39. func (s *DockerSuite) TestRunWithoutMemoryswapLimit(c *check.C) {
  40. testRequires(c, NativeExecDriver)
  41. dockerCmd(c, "run", "-m", "16m", "--memory-swap", "-1", "busybox", "true")
  42. }
  43. func (s *DockerSuite) TestRunWithSwappiness(c *check.C) {
  44. dockerCmd(c, "run", "--memory-swappiness", "0", "busybox", "true")
  45. }
  46. func (s *DockerSuite) TestRunWithSwappinessInvalid(c *check.C) {
  47. out, _, err := dockerCmdWithError("run", "--memory-swappiness", "101", "busybox", "true")
  48. if err == nil {
  49. c.Fatalf("failed. test was able to set invalid value, output: %q", out)
  50. }
  51. }
  52. // "test" should be printed
  53. func (s *DockerSuite) TestRunEchoStdoutWitCPULimit(c *check.C) {
  54. out, _ := dockerCmd(c, "run", "-c", "1000", "busybox", "echo", "test")
  55. if out != "test\n" {
  56. c.Errorf("container should've printed 'test'")
  57. }
  58. }
  59. // "test" should be printed
  60. func (s *DockerSuite) TestRunEchoStdoutWithCPUAndMemoryLimit(c *check.C) {
  61. out, _, _ := dockerCmdWithStdoutStderr(c, "run", "-c", "1000", "-m", "16m", "busybox", "echo", "test")
  62. if out != "test\n" {
  63. c.Errorf("container should've printed 'test', got %q instead", out)
  64. }
  65. }
  66. // "test" should be printed
  67. func (s *DockerSuite) TestRunEchoNamedContainer(c *check.C) {
  68. out, _ := dockerCmd(c, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test")
  69. if out != "test\n" {
  70. c.Errorf("container should've printed 'test'")
  71. }
  72. }
  73. // docker run should not leak file descriptors
  74. func (s *DockerSuite) TestRunLeakyFileDescriptors(c *check.C) {
  75. out, _ := dockerCmd(c, "run", "busybox", "ls", "-C", "/proc/self/fd")
  76. // normally, we should only get 0, 1, and 2, but 3 gets created by "ls" when it does "opendir" on the "fd" directory
  77. if out != "0 1 2 3\n" {
  78. c.Errorf("container should've printed '0 1 2 3', not: %s", out)
  79. }
  80. }
  81. // it should be possible to lookup Google DNS
  82. // this will fail when Internet access is unavailable
  83. func (s *DockerSuite) TestRunLookupGoogleDns(c *check.C) {
  84. testRequires(c, Network)
  85. dockerCmd(c, "run", "busybox", "nslookup", "google.com")
  86. }
  87. // the exit code should be 0
  88. // some versions of lxc might make this test fail
  89. func (s *DockerSuite) TestRunExitCodeZero(c *check.C) {
  90. dockerCmd(c, "run", "busybox", "true")
  91. }
  92. // the exit code should be 1
  93. // some versions of lxc might make this test fail
  94. func (s *DockerSuite) TestRunExitCodeOne(c *check.C) {
  95. _, exitCode, err := dockerCmdWithError("run", "busybox", "false")
  96. if err != nil && !strings.Contains("exit status 1", fmt.Sprintf("%s", err)) {
  97. c.Fatal(err)
  98. }
  99. if exitCode != 1 {
  100. c.Errorf("container should've exited with exit code 1")
  101. }
  102. }
  103. // it should be possible to pipe in data via stdin to a process running in a container
  104. // some versions of lxc might make this test fail
  105. func (s *DockerSuite) TestRunStdinPipe(c *check.C) {
  106. runCmd := exec.Command(dockerBinary, "run", "-i", "-a", "stdin", "busybox", "cat")
  107. runCmd.Stdin = strings.NewReader("blahblah")
  108. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  109. if err != nil {
  110. c.Fatalf("failed to run container: %v, output: %q", err, out)
  111. }
  112. out = strings.TrimSpace(out)
  113. dockerCmd(c, "wait", out)
  114. logsOut, _ := dockerCmd(c, "logs", out)
  115. containerLogs := strings.TrimSpace(logsOut)
  116. if containerLogs != "blahblah" {
  117. c.Errorf("logs didn't print the container's logs %s", containerLogs)
  118. }
  119. dockerCmd(c, "rm", out)
  120. }
  121. // the container's ID should be printed when starting a container in detached mode
  122. func (s *DockerSuite) TestRunDetachedContainerIDPrinting(c *check.C) {
  123. out, _ := dockerCmd(c, "run", "-d", "busybox", "true")
  124. out = strings.TrimSpace(out)
  125. dockerCmd(c, "wait", out)
  126. rmOut, _ := dockerCmd(c, "rm", out)
  127. rmOut = strings.TrimSpace(rmOut)
  128. if rmOut != out {
  129. c.Errorf("rm didn't print the container ID %s %s", out, rmOut)
  130. }
  131. }
  132. // the working directory should be set correctly
  133. func (s *DockerSuite) TestRunWorkingDirectory(c *check.C) {
  134. out, _ := dockerCmd(c, "run", "-w", "/root", "busybox", "pwd")
  135. out = strings.TrimSpace(out)
  136. if out != "/root" {
  137. c.Errorf("-w failed to set working directory")
  138. }
  139. out, _ = dockerCmd(c, "run", "--workdir", "/root", "busybox", "pwd")
  140. out = strings.TrimSpace(out)
  141. if out != "/root" {
  142. c.Errorf("--workdir failed to set working directory")
  143. }
  144. }
  145. // pinging Google's DNS resolver should fail when we disable the networking
  146. func (s *DockerSuite) TestRunWithoutNetworking(c *check.C) {
  147. out, exitCode, err := dockerCmdWithError("run", "--net=none", "busybox", "ping", "-c", "1", "8.8.8.8")
  148. if err != nil && exitCode != 1 {
  149. c.Fatal(out, err)
  150. }
  151. if exitCode != 1 {
  152. c.Errorf("--net=none should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
  153. }
  154. out, exitCode, err = dockerCmdWithError("run", "-n=false", "busybox", "ping", "-c", "1", "8.8.8.8")
  155. if err != nil && exitCode != 1 {
  156. c.Fatal(out, err)
  157. }
  158. if exitCode != 1 {
  159. c.Errorf("-n=false should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
  160. }
  161. }
  162. //test --link use container name to link target
  163. func (s *DockerSuite) TestRunLinksContainerWithContainerName(c *check.C) {
  164. dockerCmd(c, "run", "-i", "-t", "-d", "--name", "parent", "busybox")
  165. ip, err := inspectField("parent", "NetworkSettings.IPAddress")
  166. c.Assert(err, check.IsNil)
  167. out, _ := dockerCmd(c, "run", "--link", "parent:test", "busybox", "/bin/cat", "/etc/hosts")
  168. if !strings.Contains(out, ip+" test") {
  169. c.Fatalf("use a container name to link target failed")
  170. }
  171. }
  172. //test --link use container id to link target
  173. func (s *DockerSuite) TestRunLinksContainerWithContainerId(c *check.C) {
  174. cID, _ := dockerCmd(c, "run", "-i", "-t", "-d", "busybox")
  175. cID = strings.TrimSpace(cID)
  176. ip, err := inspectField(cID, "NetworkSettings.IPAddress")
  177. c.Assert(err, check.IsNil)
  178. out, _ := dockerCmd(c, "run", "--link", cID+":test", "busybox", "/bin/cat", "/etc/hosts")
  179. if !strings.Contains(out, ip+" test") {
  180. c.Fatalf("use a container id to link target failed")
  181. }
  182. }
  183. // Issue 9677.
  184. func (s *DockerSuite) TestRunWithDaemonFlags(c *check.C) {
  185. out, _, err := dockerCmdWithError("--selinux-enabled", "run", "-i", "-t", "busybox", "true")
  186. if err != nil {
  187. if !strings.Contains(out, "must follow the 'docker daemon' command") && // daemon
  188. !strings.Contains(out, "flag provided but not defined: --selinux-enabled") { // no daemon (client-only)
  189. c.Fatal(err, out)
  190. }
  191. }
  192. }
  193. // Regression test for #4979
  194. func (s *DockerSuite) TestRunWithVolumesFromExited(c *check.C) {
  195. out, exitCode := dockerCmd(c, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file")
  196. if exitCode != 0 {
  197. c.Fatal("1", out, exitCode)
  198. }
  199. out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file")
  200. if exitCode != 0 {
  201. c.Fatal("2", out, exitCode)
  202. }
  203. }
  204. // Volume path is a symlink which also exists on the host, and the host side is a file not a dir
  205. // But the volume call is just a normal volume, not a bind mount
  206. func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir(c *check.C) {
  207. testRequires(c, SameHostDaemon)
  208. testRequires(c, NativeExecDriver)
  209. name := "test-volume-symlink"
  210. dir, err := ioutil.TempDir("", name)
  211. if err != nil {
  212. c.Fatal(err)
  213. }
  214. defer os.RemoveAll(dir)
  215. f, err := os.OpenFile(filepath.Join(dir, "test"), os.O_CREATE, 0700)
  216. if err != nil {
  217. c.Fatal(err)
  218. }
  219. f.Close()
  220. dockerFile := fmt.Sprintf("FROM busybox\nRUN mkdir -p %s\nRUN ln -s %s /test", dir, dir)
  221. if _, err := buildImage(name, dockerFile, false); err != nil {
  222. c.Fatal(err)
  223. }
  224. dockerCmd(c, "run", "-v", "/test/test", name)
  225. }
  226. func (s *DockerSuite) TestRunVolumesMountedAsReadonly(c *check.C) {
  227. if _, code, err := dockerCmdWithError("run", "-v", "/test:/test:ro", "busybox", "touch", "/test/somefile"); err == nil || code == 0 {
  228. c.Fatalf("run should fail because volume is ro: exit code %d", code)
  229. }
  230. }
  231. func (s *DockerSuite) TestRunVolumesFromInReadonlyMode(c *check.C) {
  232. dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true")
  233. if _, code, err := dockerCmdWithError("run", "--volumes-from", "parent:ro", "busybox", "touch", "/test/file"); err == nil || code == 0 {
  234. c.Fatalf("run should fail because volume is ro: exit code %d", code)
  235. }
  236. }
  237. // Regression test for #1201
  238. func (s *DockerSuite) TestRunVolumesFromInReadWriteMode(c *check.C) {
  239. dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true")
  240. dockerCmd(c, "run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file")
  241. if out, _, err := dockerCmdWithError("run", "--volumes-from", "parent:bar", "busybox", "touch", "/test/file"); err == nil || !strings.Contains(out, "invalid mode for volumes-from: bar") {
  242. c.Fatalf("running --volumes-from foo:bar should have failed with invalid mount mode: %q", out)
  243. }
  244. dockerCmd(c, "run", "--volumes-from", "parent", "busybox", "touch", "/test/file")
  245. }
  246. func (s *DockerSuite) TestVolumesFromGetsProperMode(c *check.C) {
  247. dockerCmd(c, "run", "--name", "parent", "-v", "/test:/test:ro", "busybox", "true")
  248. // Expect this "rw" mode to be be ignored since the inherited volume is "ro"
  249. if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file"); err == nil {
  250. c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `rw`")
  251. }
  252. dockerCmd(c, "run", "--name", "parent2", "-v", "/test:/test:ro", "busybox", "true")
  253. // Expect this to be read-only since both are "ro"
  254. if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent2:ro", "busybox", "touch", "/test/file"); err == nil {
  255. c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `ro`")
  256. }
  257. }
  258. // Test for GH#10618
  259. func (s *DockerSuite) TestRunNoDupVolumes(c *check.C) {
  260. mountstr1 := randomUnixTmpDirPath("test1") + ":/someplace"
  261. mountstr2 := randomUnixTmpDirPath("test2") + ":/someplace"
  262. if out, _, err := dockerCmdWithError("run", "-v", mountstr1, "-v", mountstr2, "busybox", "true"); err == nil {
  263. c.Fatal("Expected error about duplicate volume definitions")
  264. } else {
  265. if !strings.Contains(out, "Duplicate bind mount") {
  266. c.Fatalf("Expected 'duplicate volume' error, got %v", err)
  267. }
  268. }
  269. }
  270. // Test for #1351
  271. func (s *DockerSuite) TestRunApplyVolumesFromBeforeVolumes(c *check.C) {
  272. dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "touch", "/test/foo")
  273. dockerCmd(c, "run", "--volumes-from", "parent", "-v", "/test", "busybox", "cat", "/test/foo")
  274. }
  275. func (s *DockerSuite) TestRunMultipleVolumesFrom(c *check.C) {
  276. dockerCmd(c, "run", "--name", "parent1", "-v", "/test", "busybox", "touch", "/test/foo")
  277. dockerCmd(c, "run", "--name", "parent2", "-v", "/other", "busybox", "touch", "/other/bar")
  278. dockerCmd(c, "run", "--volumes-from", "parent1", "--volumes-from", "parent2", "busybox", "sh", "-c", "cat /test/foo && cat /other/bar")
  279. }
  280. // this tests verifies the ID format for the container
  281. func (s *DockerSuite) TestRunVerifyContainerID(c *check.C) {
  282. out, exit, err := dockerCmdWithError("run", "-d", "busybox", "true")
  283. if err != nil {
  284. c.Fatal(err)
  285. }
  286. if exit != 0 {
  287. c.Fatalf("expected exit code 0 received %d", exit)
  288. }
  289. match, err := regexp.MatchString("^[0-9a-f]{64}$", strings.TrimSuffix(out, "\n"))
  290. if err != nil {
  291. c.Fatal(err)
  292. }
  293. if !match {
  294. c.Fatalf("Invalid container ID: %s", out)
  295. }
  296. }
  297. // Test that creating a container with a volume doesn't crash. Regression test for #995.
  298. func (s *DockerSuite) TestRunCreateVolume(c *check.C) {
  299. dockerCmd(c, "run", "-v", "/var/lib/data", "busybox", "true")
  300. }
  301. // Test that creating a volume with a symlink in its path works correctly. Test for #5152.
  302. // Note that this bug happens only with symlinks with a target that starts with '/'.
  303. func (s *DockerSuite) TestRunCreateVolumeWithSymlink(c *check.C) {
  304. image := "docker-test-createvolumewithsymlink"
  305. buildCmd := exec.Command(dockerBinary, "build", "-t", image, "-")
  306. buildCmd.Stdin = strings.NewReader(`FROM busybox
  307. RUN ln -s home /bar`)
  308. buildCmd.Dir = workingDirectory
  309. err := buildCmd.Run()
  310. if err != nil {
  311. c.Fatalf("could not build '%s': %v", image, err)
  312. }
  313. _, exitCode, err := dockerCmdWithError("run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", image, "sh", "-c", "mount | grep -q /home/foo")
  314. if err != nil || exitCode != 0 {
  315. c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
  316. }
  317. volPath, err := inspectMountSourceField("test-createvolumewithsymlink", "/bar/foo")
  318. if err != nil {
  319. c.Fatalf("[inspect] err: %v", err)
  320. }
  321. _, exitCode, err = dockerCmdWithError("rm", "-v", "test-createvolumewithsymlink")
  322. if err != nil || exitCode != 0 {
  323. c.Fatalf("[rm] err: %v, exitcode: %d", err, exitCode)
  324. }
  325. _, err = os.Stat(volPath)
  326. if !os.IsNotExist(err) {
  327. c.Fatalf("[open] (expecting 'file does not exist' error) err: %v, volPath: %s", err, volPath)
  328. }
  329. }
  330. // Tests that a volume path that has a symlink exists in a container mounting it with `--volumes-from`.
  331. func (s *DockerSuite) TestRunVolumesFromSymlinkPath(c *check.C) {
  332. name := "docker-test-volumesfromsymlinkpath"
  333. buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-")
  334. buildCmd.Stdin = strings.NewReader(`FROM busybox
  335. RUN ln -s home /foo
  336. VOLUME ["/foo/bar"]`)
  337. buildCmd.Dir = workingDirectory
  338. err := buildCmd.Run()
  339. if err != nil {
  340. c.Fatalf("could not build 'docker-test-volumesfromsymlinkpath': %v", err)
  341. }
  342. _, exitCode, err := dockerCmdWithError("run", "--name", "test-volumesfromsymlinkpath", name)
  343. if err != nil || exitCode != 0 {
  344. c.Fatalf("[run] (volume) err: %v, exitcode: %d", err, exitCode)
  345. }
  346. _, exitCode, err = dockerCmdWithError("run", "--volumes-from", "test-volumesfromsymlinkpath", "busybox", "sh", "-c", "ls /foo | grep -q bar")
  347. if err != nil || exitCode != 0 {
  348. c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
  349. }
  350. }
  351. func (s *DockerSuite) TestRunExitCode(c *check.C) {
  352. _, exit, err := dockerCmdWithError("run", "busybox", "/bin/sh", "-c", "exit 72")
  353. if err == nil {
  354. c.Fatal("should not have a non nil error")
  355. }
  356. if exit != 72 {
  357. c.Fatalf("expected exit code 72 received %d", exit)
  358. }
  359. }
  360. func (s *DockerSuite) TestRunUserDefaultsToRoot(c *check.C) {
  361. out, _ := dockerCmd(c, "run", "busybox", "id")
  362. if !strings.Contains(out, "uid=0(root) gid=0(root)") {
  363. c.Fatalf("expected root user got %s", out)
  364. }
  365. }
  366. func (s *DockerSuite) TestRunUserByName(c *check.C) {
  367. out, _ := dockerCmd(c, "run", "-u", "root", "busybox", "id")
  368. if !strings.Contains(out, "uid=0(root) gid=0(root)") {
  369. c.Fatalf("expected root user got %s", out)
  370. }
  371. }
  372. func (s *DockerSuite) TestRunUserByID(c *check.C) {
  373. out, _ := dockerCmd(c, "run", "-u", "1", "busybox", "id")
  374. if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") {
  375. c.Fatalf("expected daemon user got %s", out)
  376. }
  377. }
  378. func (s *DockerSuite) TestRunUserByIDBig(c *check.C) {
  379. out, _, err := dockerCmdWithError("run", "-u", "2147483648", "busybox", "id")
  380. if err == nil {
  381. c.Fatal("No error, but must be.", out)
  382. }
  383. if !strings.Contains(out, "Uids and gids must be in range") {
  384. c.Fatalf("expected error about uids range, got %s", out)
  385. }
  386. }
  387. func (s *DockerSuite) TestRunUserByIDNegative(c *check.C) {
  388. out, _, err := dockerCmdWithError("run", "-u", "-1", "busybox", "id")
  389. if err == nil {
  390. c.Fatal("No error, but must be.", out)
  391. }
  392. if !strings.Contains(out, "Uids and gids must be in range") {
  393. c.Fatalf("expected error about uids range, got %s", out)
  394. }
  395. }
  396. func (s *DockerSuite) TestRunUserByIDZero(c *check.C) {
  397. out, _, err := dockerCmdWithError("run", "-u", "0", "busybox", "id")
  398. if err != nil {
  399. c.Fatal(err, out)
  400. }
  401. if !strings.Contains(out, "uid=0(root) gid=0(root) groups=10(wheel)") {
  402. c.Fatalf("expected daemon user got %s", out)
  403. }
  404. }
  405. func (s *DockerSuite) TestRunUserNotFound(c *check.C) {
  406. _, _, err := dockerCmdWithError("run", "-u", "notme", "busybox", "id")
  407. if err == nil {
  408. c.Fatal("unknown user should cause container to fail")
  409. }
  410. }
  411. func (s *DockerSuite) TestRunTwoConcurrentContainers(c *check.C) {
  412. group := sync.WaitGroup{}
  413. group.Add(2)
  414. errChan := make(chan error, 2)
  415. for i := 0; i < 2; i++ {
  416. go func() {
  417. defer group.Done()
  418. _, _, err := dockerCmdWithError("run", "busybox", "sleep", "2")
  419. errChan <- err
  420. }()
  421. }
  422. group.Wait()
  423. close(errChan)
  424. for err := range errChan {
  425. c.Assert(err, check.IsNil)
  426. }
  427. }
  428. func (s *DockerSuite) TestRunEnvironment(c *check.C) {
  429. cmd := exec.Command(dockerBinary, "run", "-h", "testing", "-e=FALSE=true", "-e=TRUE", "-e=TRICKY", "-e=HOME=", "busybox", "env")
  430. cmd.Env = append(os.Environ(),
  431. "TRUE=false",
  432. "TRICKY=tri\ncky\n",
  433. )
  434. out, _, err := runCommandWithOutput(cmd)
  435. if err != nil {
  436. c.Fatal(err, out)
  437. }
  438. actualEnvLxc := strings.Split(strings.TrimSpace(out), "\n")
  439. actualEnv := []string{}
  440. for i := range actualEnvLxc {
  441. if actualEnvLxc[i] != "container=lxc" {
  442. actualEnv = append(actualEnv, actualEnvLxc[i])
  443. }
  444. }
  445. sort.Strings(actualEnv)
  446. goodEnv := []string{
  447. "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  448. "HOSTNAME=testing",
  449. "FALSE=true",
  450. "TRUE=false",
  451. "TRICKY=tri",
  452. "cky",
  453. "",
  454. "HOME=/root",
  455. }
  456. sort.Strings(goodEnv)
  457. if len(goodEnv) != len(actualEnv) {
  458. c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", "))
  459. }
  460. for i := range goodEnv {
  461. if actualEnv[i] != goodEnv[i] {
  462. c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
  463. }
  464. }
  465. }
  466. func (s *DockerSuite) TestRunEnvironmentErase(c *check.C) {
  467. // Test to make sure that when we use -e on env vars that are
  468. // not set in our local env that they're removed (if present) in
  469. // the container
  470. cmd := exec.Command(dockerBinary, "run", "-e", "FOO", "-e", "HOSTNAME", "busybox", "env")
  471. cmd.Env = appendBaseEnv([]string{})
  472. out, _, err := runCommandWithOutput(cmd)
  473. if err != nil {
  474. c.Fatal(err, out)
  475. }
  476. actualEnvLxc := strings.Split(strings.TrimSpace(out), "\n")
  477. actualEnv := []string{}
  478. for i := range actualEnvLxc {
  479. if actualEnvLxc[i] != "container=lxc" {
  480. actualEnv = append(actualEnv, actualEnvLxc[i])
  481. }
  482. }
  483. sort.Strings(actualEnv)
  484. goodEnv := []string{
  485. "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  486. "HOME=/root",
  487. }
  488. sort.Strings(goodEnv)
  489. if len(goodEnv) != len(actualEnv) {
  490. c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", "))
  491. }
  492. for i := range goodEnv {
  493. if actualEnv[i] != goodEnv[i] {
  494. c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
  495. }
  496. }
  497. }
  498. func (s *DockerSuite) TestRunEnvironmentOverride(c *check.C) {
  499. // Test to make sure that when we use -e on env vars that are
  500. // already in the env that we're overriding them
  501. cmd := exec.Command(dockerBinary, "run", "-e", "HOSTNAME", "-e", "HOME=/root2", "busybox", "env")
  502. cmd.Env = appendBaseEnv([]string{"HOSTNAME=bar"})
  503. out, _, err := runCommandWithOutput(cmd)
  504. if err != nil {
  505. c.Fatal(err, out)
  506. }
  507. actualEnvLxc := strings.Split(strings.TrimSpace(out), "\n")
  508. actualEnv := []string{}
  509. for i := range actualEnvLxc {
  510. if actualEnvLxc[i] != "container=lxc" {
  511. actualEnv = append(actualEnv, actualEnvLxc[i])
  512. }
  513. }
  514. sort.Strings(actualEnv)
  515. goodEnv := []string{
  516. "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  517. "HOME=/root2",
  518. "HOSTNAME=bar",
  519. }
  520. sort.Strings(goodEnv)
  521. if len(goodEnv) != len(actualEnv) {
  522. c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", "))
  523. }
  524. for i := range goodEnv {
  525. if actualEnv[i] != goodEnv[i] {
  526. c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
  527. }
  528. }
  529. }
  530. func (s *DockerSuite) TestRunContainerNetwork(c *check.C) {
  531. dockerCmd(c, "run", "busybox", "ping", "-c", "1", "127.0.0.1")
  532. }
  533. func (s *DockerSuite) TestRunNetHostNotAllowedWithLinks(c *check.C) {
  534. dockerCmd(c, "run", "--name", "linked", "busybox", "true")
  535. _, _, err := dockerCmdWithError("run", "--net=host", "--link", "linked:linked", "busybox", "true")
  536. if err == nil {
  537. c.Fatal("Expected error")
  538. }
  539. }
  540. // #7851 hostname outside container shows FQDN, inside only shortname
  541. // For testing purposes it is not required to set host's hostname directly
  542. // and use "--net=host" (as the original issue submitter did), as the same
  543. // codepath is executed with "docker run -h <hostname>". Both were manually
  544. // tested, but this testcase takes the simpler path of using "run -h .."
  545. func (s *DockerSuite) TestRunFullHostnameSet(c *check.C) {
  546. out, _ := dockerCmd(c, "run", "-h", "foo.bar.baz", "busybox", "hostname")
  547. if actual := strings.Trim(out, "\r\n"); actual != "foo.bar.baz" {
  548. c.Fatalf("expected hostname 'foo.bar.baz', received %s", actual)
  549. }
  550. }
  551. func (s *DockerSuite) TestRunPrivilegedCanMknod(c *check.C) {
  552. out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  553. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  554. c.Fatalf("expected output ok received %s", actual)
  555. }
  556. }
  557. func (s *DockerSuite) TestRunUnprivilegedCanMknod(c *check.C) {
  558. out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  559. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  560. c.Fatalf("expected output ok received %s", actual)
  561. }
  562. }
  563. func (s *DockerSuite) TestRunCapDropInvalid(c *check.C) {
  564. out, _, err := dockerCmdWithError("run", "--cap-drop=CHPASS", "busybox", "ls")
  565. if err == nil {
  566. c.Fatal(err, out)
  567. }
  568. }
  569. func (s *DockerSuite) TestRunCapDropCannotMknod(c *check.C) {
  570. out, _, err := dockerCmdWithError("run", "--cap-drop=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  571. if err == nil {
  572. c.Fatal(err, out)
  573. }
  574. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  575. c.Fatalf("expected output not ok received %s", actual)
  576. }
  577. }
  578. func (s *DockerSuite) TestRunCapDropCannotMknodLowerCase(c *check.C) {
  579. out, _, err := dockerCmdWithError("run", "--cap-drop=mknod", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  580. if err == nil {
  581. c.Fatal(err, out)
  582. }
  583. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  584. c.Fatalf("expected output not ok received %s", actual)
  585. }
  586. }
  587. func (s *DockerSuite) TestRunCapDropALLCannotMknod(c *check.C) {
  588. out, _, err := dockerCmdWithError("run", "--cap-drop=ALL", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  589. if err == nil {
  590. c.Fatal(err, out)
  591. }
  592. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  593. c.Fatalf("expected output not ok received %s", actual)
  594. }
  595. }
  596. func (s *DockerSuite) TestRunCapDropALLAddMknodCanMknod(c *check.C) {
  597. out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  598. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  599. c.Fatalf("expected output ok received %s", actual)
  600. }
  601. }
  602. func (s *DockerSuite) TestRunCapAddInvalid(c *check.C) {
  603. out, _, err := dockerCmdWithError("run", "--cap-add=CHPASS", "busybox", "ls")
  604. if err == nil {
  605. c.Fatal(err, out)
  606. }
  607. }
  608. func (s *DockerSuite) TestRunCapAddCanDownInterface(c *check.C) {
  609. out, _ := dockerCmd(c, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  610. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  611. c.Fatalf("expected output ok received %s", actual)
  612. }
  613. }
  614. func (s *DockerSuite) TestRunCapAddALLCanDownInterface(c *check.C) {
  615. out, _ := dockerCmd(c, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  616. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  617. c.Fatalf("expected output ok received %s", actual)
  618. }
  619. }
  620. func (s *DockerSuite) TestRunCapAddALLDropNetAdminCanDownInterface(c *check.C) {
  621. out, _, err := dockerCmdWithError("run", "--cap-add=ALL", "--cap-drop=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  622. if err == nil {
  623. c.Fatal(err, out)
  624. }
  625. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  626. c.Fatalf("expected output not ok received %s", actual)
  627. }
  628. }
  629. func (s *DockerSuite) TestRunGroupAdd(c *check.C) {
  630. testRequires(c, NativeExecDriver)
  631. out, _ := dockerCmd(c, "run", "--group-add=audio", "--group-add=dbus", "--group-add=777", "busybox", "sh", "-c", "id")
  632. groupsList := "uid=0(root) gid=0(root) groups=10(wheel),29(audio),81(dbus),777"
  633. if actual := strings.Trim(out, "\r\n"); actual != groupsList {
  634. c.Fatalf("expected output %s received %s", groupsList, actual)
  635. }
  636. }
  637. func (s *DockerSuite) TestRunPrivilegedCanMount(c *check.C) {
  638. out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
  639. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  640. c.Fatalf("expected output ok received %s", actual)
  641. }
  642. }
  643. func (s *DockerSuite) TestRunUnprivilegedCannotMount(c *check.C) {
  644. out, _, err := dockerCmdWithError("run", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
  645. if err == nil {
  646. c.Fatal(err, out)
  647. }
  648. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  649. c.Fatalf("expected output not ok received %s", actual)
  650. }
  651. }
  652. func (s *DockerSuite) TestRunSysNotWritableInNonPrivilegedContainers(c *check.C) {
  653. if _, code, err := dockerCmdWithError("run", "busybox", "touch", "/sys/kernel/profiling"); err == nil || code == 0 {
  654. c.Fatal("sys should not be writable in a non privileged container")
  655. }
  656. }
  657. func (s *DockerSuite) TestRunSysWritableInPrivilegedContainers(c *check.C) {
  658. if _, code, err := dockerCmdWithError("run", "--privileged", "busybox", "touch", "/sys/kernel/profiling"); err != nil || code != 0 {
  659. c.Fatalf("sys should be writable in privileged container")
  660. }
  661. }
  662. func (s *DockerSuite) TestRunProcNotWritableInNonPrivilegedContainers(c *check.C) {
  663. if _, code, err := dockerCmdWithError("run", "busybox", "touch", "/proc/sysrq-trigger"); err == nil || code == 0 {
  664. c.Fatal("proc should not be writable in a non privileged container")
  665. }
  666. }
  667. func (s *DockerSuite) TestRunProcWritableInPrivilegedContainers(c *check.C) {
  668. if _, code := dockerCmd(c, "run", "--privileged", "busybox", "touch", "/proc/sysrq-trigger"); code != 0 {
  669. c.Fatalf("proc should be writable in privileged container")
  670. }
  671. }
  672. func (s *DockerSuite) TestRunWithCpuset(c *check.C) {
  673. if _, code := dockerCmd(c, "run", "--cpuset", "0", "busybox", "true"); code != 0 {
  674. c.Fatalf("container should run successfully with cpuset of 0")
  675. }
  676. }
  677. func (s *DockerSuite) TestRunWithCpusetCpus(c *check.C) {
  678. if _, code := dockerCmd(c, "run", "--cpuset-cpus", "0", "busybox", "true"); code != 0 {
  679. c.Fatalf("container should run successfully with cpuset-cpus of 0")
  680. }
  681. }
  682. func (s *DockerSuite) TestRunWithCpusetMems(c *check.C) {
  683. if _, code := dockerCmd(c, "run", "--cpuset-mems", "0", "busybox", "true"); code != 0 {
  684. c.Fatalf("container should run successfully with cpuset-mems of 0")
  685. }
  686. }
  687. func (s *DockerSuite) TestRunWithBlkioWeight(c *check.C) {
  688. if _, code := dockerCmd(c, "run", "--blkio-weight", "300", "busybox", "true"); code != 0 {
  689. c.Fatalf("container should run successfully with blkio-weight of 300")
  690. }
  691. }
  692. func (s *DockerSuite) TestRunWithBlkioInvalidWeight(c *check.C) {
  693. if _, _, err := dockerCmdWithError("run", "--blkio-weight", "5", "busybox", "true"); err == nil {
  694. c.Fatalf("run with invalid blkio-weight should failed")
  695. }
  696. }
  697. func (s *DockerSuite) TestRunDeviceNumbers(c *check.C) {
  698. out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "ls -l /dev/null")
  699. deviceLineFields := strings.Fields(out)
  700. deviceLineFields[6] = ""
  701. deviceLineFields[7] = ""
  702. deviceLineFields[8] = ""
  703. expected := []string{"crw-rw-rw-", "1", "root", "root", "1,", "3", "", "", "", "/dev/null"}
  704. if !(reflect.DeepEqual(deviceLineFields, expected)) {
  705. c.Fatalf("expected output\ncrw-rw-rw- 1 root root 1, 3 May 24 13:29 /dev/null\n received\n %s\n", out)
  706. }
  707. }
  708. func (s *DockerSuite) TestRunThatCharacterDevicesActLikeCharacterDevices(c *check.C) {
  709. out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero")
  710. if actual := strings.Trim(out, "\r\n"); actual[0] == '0' {
  711. c.Fatalf("expected a new file called /zero to be create that is greater than 0 bytes long, but du says: %s", actual)
  712. }
  713. }
  714. func (s *DockerSuite) TestRunUnprivilegedWithChroot(c *check.C) {
  715. dockerCmd(c, "run", "busybox", "chroot", "/", "true")
  716. }
  717. func (s *DockerSuite) TestRunAddingOptionalDevices(c *check.C) {
  718. out, _ := dockerCmd(c, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo")
  719. if actual := strings.Trim(out, "\r\n"); actual != "/dev/nulo" {
  720. c.Fatalf("expected output /dev/nulo, received %s", actual)
  721. }
  722. }
  723. func (s *DockerSuite) TestRunAddingOptionalDevicesNoSrc(c *check.C) {
  724. out, _ := dockerCmd(c, "run", "--device", "/dev/zero:rw", "busybox", "sh", "-c", "ls /dev/zero")
  725. if actual := strings.Trim(out, "\r\n"); actual != "/dev/zero" {
  726. c.Fatalf("expected output /dev/zero, received %s", actual)
  727. }
  728. }
  729. func (s *DockerSuite) TestRunAddingOptionalDevicesInvalideMode(c *check.C) {
  730. _, _, err := dockerCmdWithError("run", "--device", "/dev/zero:ro", "busybox", "sh", "-c", "ls /dev/zero")
  731. if err == nil {
  732. c.Fatalf("run container with device mode ro should fail")
  733. }
  734. }
  735. func (s *DockerSuite) TestRunModeHostname(c *check.C) {
  736. testRequires(c, SameHostDaemon)
  737. out, _ := dockerCmd(c, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname")
  738. if actual := strings.Trim(out, "\r\n"); actual != "testhostname" {
  739. c.Fatalf("expected 'testhostname', but says: %q", actual)
  740. }
  741. out, _ = dockerCmd(c, "run", "--net=host", "busybox", "cat", "/etc/hostname")
  742. hostname, err := os.Hostname()
  743. if err != nil {
  744. c.Fatal(err)
  745. }
  746. if actual := strings.Trim(out, "\r\n"); actual != hostname {
  747. c.Fatalf("expected %q, but says: %q", hostname, actual)
  748. }
  749. }
  750. func (s *DockerSuite) TestRunRootWorkdir(c *check.C) {
  751. out, _ := dockerCmd(c, "run", "--workdir", "/", "busybox", "pwd")
  752. if out != "/\n" {
  753. c.Fatalf("pwd returned %q (expected /\\n)", s)
  754. }
  755. }
  756. func (s *DockerSuite) TestRunAllowBindMountingRoot(c *check.C) {
  757. dockerCmd(c, "run", "-v", "/:/host", "busybox", "ls", "/host")
  758. }
  759. func (s *DockerSuite) TestRunDisallowBindMountingRootToRoot(c *check.C) {
  760. out, _, err := dockerCmdWithError("run", "-v", "/:/", "busybox", "ls", "/host")
  761. if err == nil {
  762. c.Fatal(out, err)
  763. }
  764. }
  765. // Verify that a container gets default DNS when only localhost resolvers exist
  766. func (s *DockerSuite) TestRunDnsDefaultOptions(c *check.C) {
  767. testRequires(c, SameHostDaemon)
  768. // preserve original resolv.conf for restoring after test
  769. origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  770. if os.IsNotExist(err) {
  771. c.Fatalf("/etc/resolv.conf does not exist")
  772. }
  773. // defer restored original conf
  774. defer func() {
  775. if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil {
  776. c.Fatal(err)
  777. }
  778. }()
  779. // test 3 cases: standard IPv4 localhost, commented out localhost, and IPv6 localhost
  780. // 2 are removed from the file at container start, and the 3rd (commented out) one is ignored by
  781. // GetNameservers(), leading to a replacement of nameservers with the default set
  782. tmpResolvConf := []byte("nameserver 127.0.0.1\n#nameserver 127.0.2.1\nnameserver ::1")
  783. if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
  784. c.Fatal(err)
  785. }
  786. actual, _ := dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf")
  787. // check that the actual defaults are appended to the commented out
  788. // localhost resolver (which should be preserved)
  789. // NOTE: if we ever change the defaults from google dns, this will break
  790. expected := "#nameserver 127.0.2.1\n\nnameserver 8.8.8.8\nnameserver 8.8.4.4"
  791. if actual != expected {
  792. c.Fatalf("expected resolv.conf be: %q, but was: %q", expected, actual)
  793. }
  794. }
  795. func (s *DockerSuite) TestRunDnsOptions(c *check.C) {
  796. out, stderr, _ := dockerCmdWithStdoutStderr(c, "run", "--dns=127.0.0.1", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
  797. // The client will get a warning on stderr when setting DNS to a localhost address; verify this:
  798. if !strings.Contains(stderr, "Localhost DNS setting") {
  799. c.Fatalf("Expected warning on stderr about localhost resolver, but got %q", stderr)
  800. }
  801. actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1)
  802. if actual != "nameserver 127.0.0.1 search mydomain" {
  803. c.Fatalf("expected 'nameserver 127.0.0.1 search mydomain', but says: %q", actual)
  804. }
  805. out, stderr, _ = dockerCmdWithStdoutStderr(c, "run", "--dns=127.0.0.1", "--dns-search=.", "busybox", "cat", "/etc/resolv.conf")
  806. actual = strings.Replace(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ", -1)
  807. if actual != "nameserver 127.0.0.1" {
  808. c.Fatalf("expected 'nameserver 127.0.0.1', but says: %q", actual)
  809. }
  810. }
  811. func (s *DockerSuite) TestRunDnsOptionsBasedOnHostResolvConf(c *check.C) {
  812. testRequires(c, SameHostDaemon)
  813. origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  814. if os.IsNotExist(err) {
  815. c.Fatalf("/etc/resolv.conf does not exist")
  816. }
  817. hostNamservers := resolvconf.GetNameservers(origResolvConf)
  818. hostSearch := resolvconf.GetSearchDomains(origResolvConf)
  819. var out string
  820. out, _ = dockerCmd(c, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf")
  821. if actualNameservers := resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "127.0.0.1" {
  822. c.Fatalf("expected '127.0.0.1', but says: %q", string(actualNameservers[0]))
  823. }
  824. actualSearch := resolvconf.GetSearchDomains([]byte(out))
  825. if len(actualSearch) != len(hostSearch) {
  826. c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch))
  827. }
  828. for i := range actualSearch {
  829. if actualSearch[i] != hostSearch[i] {
  830. c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i])
  831. }
  832. }
  833. out, _ = dockerCmd(c, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
  834. actualNameservers := resolvconf.GetNameservers([]byte(out))
  835. if len(actualNameservers) != len(hostNamservers) {
  836. c.Fatalf("expected %q nameserver(s), but it has: %q", len(hostNamservers), len(actualNameservers))
  837. }
  838. for i := range actualNameservers {
  839. if actualNameservers[i] != hostNamservers[i] {
  840. c.Fatalf("expected %q nameserver, but says: %q", actualNameservers[i], hostNamservers[i])
  841. }
  842. }
  843. if actualSearch = resolvconf.GetSearchDomains([]byte(out)); string(actualSearch[0]) != "mydomain" {
  844. c.Fatalf("expected 'mydomain', but says: %q", string(actualSearch[0]))
  845. }
  846. // test with file
  847. tmpResolvConf := []byte("search example.com\nnameserver 12.34.56.78\nnameserver 127.0.0.1")
  848. if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
  849. c.Fatal(err)
  850. }
  851. // put the old resolvconf back
  852. defer func() {
  853. if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil {
  854. c.Fatal(err)
  855. }
  856. }()
  857. resolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  858. if os.IsNotExist(err) {
  859. c.Fatalf("/etc/resolv.conf does not exist")
  860. }
  861. hostNamservers = resolvconf.GetNameservers(resolvConf)
  862. hostSearch = resolvconf.GetSearchDomains(resolvConf)
  863. out, _ = dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf")
  864. if actualNameservers = resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "12.34.56.78" || len(actualNameservers) != 1 {
  865. c.Fatalf("expected '12.34.56.78', but has: %v", actualNameservers)
  866. }
  867. actualSearch = resolvconf.GetSearchDomains([]byte(out))
  868. if len(actualSearch) != len(hostSearch) {
  869. c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch))
  870. }
  871. for i := range actualSearch {
  872. if actualSearch[i] != hostSearch[i] {
  873. c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i])
  874. }
  875. }
  876. }
  877. // Test to see if a non-root user can resolve a DNS name and reach out to it. Also
  878. // check if the container resolv.conf file has at least 0644 perm.
  879. func (s *DockerSuite) TestRunNonRootUserResolvName(c *check.C) {
  880. testRequires(c, SameHostDaemon, Network)
  881. dockerCmd(c, "run", "--name=testperm", "--user=default", "busybox", "ping", "-c", "1", "apt.dockerproject.org")
  882. cID, err := getIDByName("testperm")
  883. if err != nil {
  884. c.Fatal(err)
  885. }
  886. fmode := (os.FileMode)(0644)
  887. finfo, err := os.Stat(containerStorageFile(cID, "resolv.conf"))
  888. if err != nil {
  889. c.Fatal(err)
  890. }
  891. if (finfo.Mode() & fmode) != fmode {
  892. c.Fatalf("Expected container resolv.conf mode to be at least %s, instead got %s", fmode.String(), finfo.Mode().String())
  893. }
  894. }
  895. // Test if container resolv.conf gets updated the next time it restarts
  896. // if host /etc/resolv.conf has changed. This only applies if the container
  897. // uses the host's /etc/resolv.conf and does not have any dns options provided.
  898. func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) {
  899. testRequires(c, SameHostDaemon)
  900. tmpResolvConf := []byte("search pommesfrites.fr\nnameserver 12.34.56.78")
  901. tmpLocalhostResolvConf := []byte("nameserver 127.0.0.1")
  902. //take a copy of resolv.conf for restoring after test completes
  903. resolvConfSystem, err := ioutil.ReadFile("/etc/resolv.conf")
  904. if err != nil {
  905. c.Fatal(err)
  906. }
  907. // This test case is meant to test monitoring resolv.conf when it is
  908. // a regular file not a bind mounc. So we unmount resolv.conf and replace
  909. // it with a file containing the original settings.
  910. cmd := exec.Command("umount", "/etc/resolv.conf")
  911. if _, err = runCommand(cmd); err != nil {
  912. c.Fatal(err)
  913. }
  914. //cleanup
  915. defer func() {
  916. if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  917. c.Fatal(err)
  918. }
  919. }()
  920. //1. test that a restarting container gets an updated resolv.conf
  921. dockerCmd(c, "run", "--name='first'", "busybox", "true")
  922. containerID1, err := getIDByName("first")
  923. if err != nil {
  924. c.Fatal(err)
  925. }
  926. // replace resolv.conf with our temporary copy
  927. bytesResolvConf := []byte(tmpResolvConf)
  928. if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  929. c.Fatal(err)
  930. }
  931. // start the container again to pickup changes
  932. dockerCmd(c, "start", "first")
  933. // check for update in container
  934. containerResolv, err := readContainerFile(containerID1, "resolv.conf")
  935. if err != nil {
  936. c.Fatal(err)
  937. }
  938. if !bytes.Equal(containerResolv, bytesResolvConf) {
  939. c.Fatalf("Restarted container does not have updated resolv.conf; expected %q, got %q", tmpResolvConf, string(containerResolv))
  940. }
  941. /* //make a change to resolv.conf (in this case replacing our tmp copy with orig copy)
  942. if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  943. c.Fatal(err)
  944. } */
  945. //2. test that a restarting container does not receive resolv.conf updates
  946. // if it modified the container copy of the starting point resolv.conf
  947. dockerCmd(c, "run", "--name='second'", "busybox", "sh", "-c", "echo 'search mylittlepony.com' >>/etc/resolv.conf")
  948. containerID2, err := getIDByName("second")
  949. if err != nil {
  950. c.Fatal(err)
  951. }
  952. //make a change to resolv.conf (in this case replacing our tmp copy with orig copy)
  953. if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  954. c.Fatal(err)
  955. }
  956. // start the container again
  957. dockerCmd(c, "start", "second")
  958. // check for update in container
  959. containerResolv, err = readContainerFile(containerID2, "resolv.conf")
  960. if err != nil {
  961. c.Fatal(err)
  962. }
  963. if bytes.Equal(containerResolv, resolvConfSystem) {
  964. c.Fatalf("Restarting a container after container updated resolv.conf should not pick up host changes; expected %q, got %q", string(containerResolv), string(resolvConfSystem))
  965. }
  966. //3. test that a running container's resolv.conf is not modified while running
  967. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  968. runningContainerID := strings.TrimSpace(out)
  969. // replace resolv.conf
  970. if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  971. c.Fatal(err)
  972. }
  973. // check for update in container
  974. containerResolv, err = readContainerFile(runningContainerID, "resolv.conf")
  975. if err != nil {
  976. c.Fatal(err)
  977. }
  978. if bytes.Equal(containerResolv, bytesResolvConf) {
  979. c.Fatalf("Running container should not have updated resolv.conf; expected %q, got %q", string(resolvConfSystem), string(containerResolv))
  980. }
  981. //4. test that a running container's resolv.conf is updated upon restart
  982. // (the above container is still running..)
  983. dockerCmd(c, "restart", runningContainerID)
  984. // check for update in container
  985. containerResolv, err = readContainerFile(runningContainerID, "resolv.conf")
  986. if err != nil {
  987. c.Fatal(err)
  988. }
  989. if !bytes.Equal(containerResolv, bytesResolvConf) {
  990. c.Fatalf("Restarted container should have updated resolv.conf; expected %q, got %q", string(bytesResolvConf), string(containerResolv))
  991. }
  992. //5. test that additions of a localhost resolver are cleaned from
  993. // host resolv.conf before updating container's resolv.conf copies
  994. // replace resolv.conf with a localhost-only nameserver copy
  995. bytesResolvConf = []byte(tmpLocalhostResolvConf)
  996. if err = ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  997. c.Fatal(err)
  998. }
  999. // start the container again to pickup changes
  1000. dockerCmd(c, "start", "first")
  1001. // our first exited container ID should have been updated, but with default DNS
  1002. // after the cleanup of resolv.conf found only a localhost nameserver:
  1003. containerResolv, err = readContainerFile(containerID1, "resolv.conf")
  1004. if err != nil {
  1005. c.Fatal(err)
  1006. }
  1007. expected := "\nnameserver 8.8.8.8\nnameserver 8.8.4.4"
  1008. if !bytes.Equal(containerResolv, []byte(expected)) {
  1009. c.Fatalf("Container does not have cleaned/replaced DNS in resolv.conf; expected %q, got %q", expected, string(containerResolv))
  1010. }
  1011. //6. Test that replacing (as opposed to modifying) resolv.conf triggers an update
  1012. // of containers' resolv.conf.
  1013. // Restore the original resolv.conf
  1014. if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1015. c.Fatal(err)
  1016. }
  1017. // Run the container so it picks up the old settings
  1018. dockerCmd(c, "run", "--name='third'", "busybox", "true")
  1019. containerID3, err := getIDByName("third")
  1020. if err != nil {
  1021. c.Fatal(err)
  1022. }
  1023. // Create a modified resolv.conf.aside and override resolv.conf with it
  1024. bytesResolvConf = []byte(tmpResolvConf)
  1025. if err := ioutil.WriteFile("/etc/resolv.conf.aside", bytesResolvConf, 0644); err != nil {
  1026. c.Fatal(err)
  1027. }
  1028. err = os.Rename("/etc/resolv.conf.aside", "/etc/resolv.conf")
  1029. if err != nil {
  1030. c.Fatal(err)
  1031. }
  1032. // start the container again to pickup changes
  1033. dockerCmd(c, "start", "third")
  1034. // check for update in container
  1035. containerResolv, err = readContainerFile(containerID3, "resolv.conf")
  1036. if err != nil {
  1037. c.Fatal(err)
  1038. }
  1039. if !bytes.Equal(containerResolv, bytesResolvConf) {
  1040. c.Fatalf("Stopped container does not have updated resolv.conf; expected\n%q\n got\n%q", tmpResolvConf, string(containerResolv))
  1041. }
  1042. //cleanup, restore original resolv.conf happens in defer func()
  1043. }
  1044. func (s *DockerSuite) TestRunAddHost(c *check.C) {
  1045. out, _ := dockerCmd(c, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts")
  1046. actual := strings.Trim(out, "\r\n")
  1047. if actual != "86.75.30.9\textra" {
  1048. c.Fatalf("expected '86.75.30.9\textra', but says: %q", actual)
  1049. }
  1050. }
  1051. // Regression test for #6983
  1052. func (s *DockerSuite) TestRunAttachStdErrOnlyTTYMode(c *check.C) {
  1053. _, exitCode := dockerCmd(c, "run", "-t", "-a", "stderr", "busybox", "true")
  1054. if exitCode != 0 {
  1055. c.Fatalf("Container should have exited with error code 0")
  1056. }
  1057. }
  1058. // Regression test for #6983
  1059. func (s *DockerSuite) TestRunAttachStdOutOnlyTTYMode(c *check.C) {
  1060. _, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "busybox", "true")
  1061. if exitCode != 0 {
  1062. c.Fatalf("Container should have exited with error code 0")
  1063. }
  1064. }
  1065. // Regression test for #6983
  1066. func (s *DockerSuite) TestRunAttachStdOutAndErrTTYMode(c *check.C) {
  1067. _, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true")
  1068. if exitCode != 0 {
  1069. c.Fatalf("Container should have exited with error code 0")
  1070. }
  1071. }
  1072. // Test for #10388 - this will run the same test as TestRunAttachStdOutAndErrTTYMode
  1073. // but using --attach instead of -a to make sure we read the flag correctly
  1074. func (s *DockerSuite) TestRunAttachWithDetach(c *check.C) {
  1075. cmd := exec.Command(dockerBinary, "run", "-d", "--attach", "stdout", "busybox", "true")
  1076. _, stderr, _, err := runCommandWithStdoutStderr(cmd)
  1077. if err == nil {
  1078. c.Fatal("Container should have exited with error code different than 0")
  1079. } else if !strings.Contains(stderr, "Conflicting options: -a and -d") {
  1080. c.Fatal("Should have been returned an error with conflicting options -a and -d")
  1081. }
  1082. }
  1083. func (s *DockerSuite) TestRunState(c *check.C) {
  1084. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1085. id := strings.TrimSpace(out)
  1086. state, err := inspectField(id, "State.Running")
  1087. c.Assert(err, check.IsNil)
  1088. if state != "true" {
  1089. c.Fatal("Container state is 'not running'")
  1090. }
  1091. pid1, err := inspectField(id, "State.Pid")
  1092. c.Assert(err, check.IsNil)
  1093. if pid1 == "0" {
  1094. c.Fatal("Container state Pid 0")
  1095. }
  1096. dockerCmd(c, "stop", id)
  1097. state, err = inspectField(id, "State.Running")
  1098. c.Assert(err, check.IsNil)
  1099. if state != "false" {
  1100. c.Fatal("Container state is 'running'")
  1101. }
  1102. pid2, err := inspectField(id, "State.Pid")
  1103. c.Assert(err, check.IsNil)
  1104. if pid2 == pid1 {
  1105. c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1106. }
  1107. dockerCmd(c, "start", id)
  1108. state, err = inspectField(id, "State.Running")
  1109. c.Assert(err, check.IsNil)
  1110. if state != "true" {
  1111. c.Fatal("Container state is 'not running'")
  1112. }
  1113. pid3, err := inspectField(id, "State.Pid")
  1114. c.Assert(err, check.IsNil)
  1115. if pid3 == pid1 {
  1116. c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1117. }
  1118. }
  1119. // Test for #1737
  1120. func (s *DockerSuite) TestRunCopyVolumeUidGid(c *check.C) {
  1121. name := "testrunvolumesuidgid"
  1122. _, err := buildImage(name,
  1123. `FROM busybox
  1124. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1125. RUN echo 'dockerio:x:1001:' >> /etc/group
  1126. RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`,
  1127. true)
  1128. if err != nil {
  1129. c.Fatal(err)
  1130. }
  1131. // Test that the uid and gid is copied from the image to the volume
  1132. out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'")
  1133. out = strings.TrimSpace(out)
  1134. if out != "dockerio:dockerio" {
  1135. c.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out)
  1136. }
  1137. }
  1138. // Test for #1582
  1139. func (s *DockerSuite) TestRunCopyVolumeContent(c *check.C) {
  1140. name := "testruncopyvolumecontent"
  1141. _, err := buildImage(name,
  1142. `FROM busybox
  1143. RUN mkdir -p /hello/local && echo hello > /hello/local/world`,
  1144. true)
  1145. if err != nil {
  1146. c.Fatal(err)
  1147. }
  1148. // Test that the content is copied from the image to the volume
  1149. out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "find", "/hello")
  1150. if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) {
  1151. c.Fatal("Container failed to transfer content to volume")
  1152. }
  1153. }
  1154. func (s *DockerSuite) TestRunCleanupCmdOnEntrypoint(c *check.C) {
  1155. name := "testrunmdcleanuponentrypoint"
  1156. if _, err := buildImage(name,
  1157. `FROM busybox
  1158. ENTRYPOINT ["echo"]
  1159. CMD ["testingpoint"]`,
  1160. true); err != nil {
  1161. c.Fatal(err)
  1162. }
  1163. out, exit := dockerCmd(c, "run", "--entrypoint", "whoami", name)
  1164. if exit != 0 {
  1165. c.Fatalf("expected exit code 0 received %d, out: %q", exit, out)
  1166. }
  1167. out = strings.TrimSpace(out)
  1168. if out != "root" {
  1169. c.Fatalf("Expected output root, got %q", out)
  1170. }
  1171. }
  1172. // TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected
  1173. func (s *DockerSuite) TestRunWorkdirExistsAndIsFile(c *check.C) {
  1174. out, exit, err := dockerCmdWithError("run", "-w", "/bin/cat", "busybox")
  1175. if !(err != nil && exit == 1 && strings.Contains(out, "Cannot mkdir: /bin/cat is not a directory")) {
  1176. c.Fatalf("Docker must complains about making dir, but we got out: %s, exit: %d, err: %s", out, exit, err)
  1177. }
  1178. }
  1179. func (s *DockerSuite) TestRunExitOnStdinClose(c *check.C) {
  1180. name := "testrunexitonstdinclose"
  1181. runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", "/bin/cat")
  1182. stdin, err := runCmd.StdinPipe()
  1183. if err != nil {
  1184. c.Fatal(err)
  1185. }
  1186. stdout, err := runCmd.StdoutPipe()
  1187. if err != nil {
  1188. c.Fatal(err)
  1189. }
  1190. if err := runCmd.Start(); err != nil {
  1191. c.Fatal(err)
  1192. }
  1193. if _, err := stdin.Write([]byte("hello\n")); err != nil {
  1194. c.Fatal(err)
  1195. }
  1196. r := bufio.NewReader(stdout)
  1197. line, err := r.ReadString('\n')
  1198. if err != nil {
  1199. c.Fatal(err)
  1200. }
  1201. line = strings.TrimSpace(line)
  1202. if line != "hello" {
  1203. c.Fatalf("Output should be 'hello', got '%q'", line)
  1204. }
  1205. if err := stdin.Close(); err != nil {
  1206. c.Fatal(err)
  1207. }
  1208. finish := make(chan error)
  1209. go func() {
  1210. finish <- runCmd.Wait()
  1211. close(finish)
  1212. }()
  1213. select {
  1214. case err := <-finish:
  1215. c.Assert(err, check.IsNil)
  1216. case <-time.After(1 * time.Second):
  1217. c.Fatal("docker run failed to exit on stdin close")
  1218. }
  1219. state, err := inspectField(name, "State.Running")
  1220. c.Assert(err, check.IsNil)
  1221. if state != "false" {
  1222. c.Fatal("Container must be stopped after stdin closing")
  1223. }
  1224. }
  1225. // Test for #2267
  1226. func (s *DockerSuite) TestRunWriteHostsFileAndNotCommit(c *check.C) {
  1227. name := "writehosts"
  1228. out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hosts && cat /etc/hosts")
  1229. if !strings.Contains(out, "test2267") {
  1230. c.Fatal("/etc/hosts should contain 'test2267'")
  1231. }
  1232. out, _ = dockerCmd(c, "diff", name)
  1233. if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1234. c.Fatal("diff should be empty")
  1235. }
  1236. }
  1237. func eqToBaseDiff(out string, c *check.C) bool {
  1238. out1, _ := dockerCmd(c, "run", "-d", "busybox", "echo", "hello")
  1239. cID := strings.TrimSpace(out1)
  1240. baseDiff, _ := dockerCmd(c, "diff", cID)
  1241. baseArr := strings.Split(baseDiff, "\n")
  1242. sort.Strings(baseArr)
  1243. outArr := strings.Split(out, "\n")
  1244. sort.Strings(outArr)
  1245. return sliceEq(baseArr, outArr)
  1246. }
  1247. func sliceEq(a, b []string) bool {
  1248. if len(a) != len(b) {
  1249. return false
  1250. }
  1251. for i := range a {
  1252. if a[i] != b[i] {
  1253. return false
  1254. }
  1255. }
  1256. return true
  1257. }
  1258. // Test for #2267
  1259. func (s *DockerSuite) TestRunWriteHostnameFileAndNotCommit(c *check.C) {
  1260. name := "writehostname"
  1261. out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hostname && cat /etc/hostname")
  1262. if !strings.Contains(out, "test2267") {
  1263. c.Fatal("/etc/hostname should contain 'test2267'")
  1264. }
  1265. out, _ = dockerCmd(c, "diff", name)
  1266. if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1267. c.Fatal("diff should be empty")
  1268. }
  1269. }
  1270. // Test for #2267
  1271. func (s *DockerSuite) TestRunWriteResolvFileAndNotCommit(c *check.C) {
  1272. name := "writeresolv"
  1273. out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/resolv.conf && cat /etc/resolv.conf")
  1274. if !strings.Contains(out, "test2267") {
  1275. c.Fatal("/etc/resolv.conf should contain 'test2267'")
  1276. }
  1277. out, _ = dockerCmd(c, "diff", name)
  1278. if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1279. c.Fatal("diff should be empty")
  1280. }
  1281. }
  1282. func (s *DockerSuite) TestRunWithBadDevice(c *check.C) {
  1283. name := "baddevice"
  1284. out, _, err := dockerCmdWithError("run", "--name", name, "--device", "/etc", "busybox", "true")
  1285. if err == nil {
  1286. c.Fatal("Run should fail with bad device")
  1287. }
  1288. expected := `"/etc": not a device node`
  1289. if !strings.Contains(out, expected) {
  1290. c.Fatalf("Output should contain %q, actual out: %q", expected, out)
  1291. }
  1292. }
  1293. func (s *DockerSuite) TestRunEntrypoint(c *check.C) {
  1294. name := "entrypoint"
  1295. out, _ := dockerCmd(c, "run", "--name", name, "--entrypoint", "/bin/echo", "busybox", "-n", "foobar")
  1296. expected := "foobar"
  1297. if out != expected {
  1298. c.Fatalf("Output should be %q, actual out: %q", expected, out)
  1299. }
  1300. }
  1301. func (s *DockerSuite) TestRunBindMounts(c *check.C) {
  1302. testRequires(c, SameHostDaemon)
  1303. tmpDir, err := ioutil.TempDir("", "docker-test-container")
  1304. if err != nil {
  1305. c.Fatal(err)
  1306. }
  1307. defer os.RemoveAll(tmpDir)
  1308. writeFile(path.Join(tmpDir, "touch-me"), "", c)
  1309. // Test reading from a read-only bind mount
  1310. out, _ := dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox", "ls", "/tmp")
  1311. if !strings.Contains(out, "touch-me") {
  1312. c.Fatal("Container failed to read from bind mount")
  1313. }
  1314. // test writing to bind mount
  1315. dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla")
  1316. readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist
  1317. // test mounting to an illegal destination directory
  1318. _, _, err = dockerCmdWithError("run", "-v", fmt.Sprintf("%s:.", tmpDir), "busybox", "ls", ".")
  1319. if err == nil {
  1320. c.Fatal("Container bind mounted illegal directory")
  1321. }
  1322. // test mount a file
  1323. dockerCmd(c, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla")
  1324. content := readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist
  1325. expected := "yotta"
  1326. if content != expected {
  1327. c.Fatalf("Output should be %q, actual out: %q", expected, content)
  1328. }
  1329. }
  1330. // Ensure that CIDFile gets deleted if it's empty
  1331. // Perform this test by making `docker run` fail
  1332. func (s *DockerSuite) TestRunCidFileCleanupIfEmpty(c *check.C) {
  1333. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1334. if err != nil {
  1335. c.Fatal(err)
  1336. }
  1337. defer os.RemoveAll(tmpDir)
  1338. tmpCidFile := path.Join(tmpDir, "cid")
  1339. out, _, err := dockerCmdWithError("run", "--cidfile", tmpCidFile, "emptyfs")
  1340. if err == nil {
  1341. c.Fatalf("Run without command must fail. out=%s", out)
  1342. } else if !strings.Contains(out, "No command specified") {
  1343. c.Fatalf("Run without command failed with wrong output. out=%s\nerr=%v", out, err)
  1344. }
  1345. if _, err := os.Stat(tmpCidFile); err == nil {
  1346. c.Fatalf("empty CIDFile %q should've been deleted", tmpCidFile)
  1347. }
  1348. }
  1349. // #2098 - Docker cidFiles only contain short version of the containerId
  1350. //sudo docker run --cidfile /tmp/docker_tesc.cid ubuntu echo "test"
  1351. // TestRunCidFile tests that run --cidfile returns the longid
  1352. func (s *DockerSuite) TestRunCidFileCheckIDLength(c *check.C) {
  1353. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1354. if err != nil {
  1355. c.Fatal(err)
  1356. }
  1357. tmpCidFile := path.Join(tmpDir, "cid")
  1358. defer os.RemoveAll(tmpDir)
  1359. out, _ := dockerCmd(c, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true")
  1360. id := strings.TrimSpace(out)
  1361. buffer, err := ioutil.ReadFile(tmpCidFile)
  1362. if err != nil {
  1363. c.Fatal(err)
  1364. }
  1365. cid := string(buffer)
  1366. if len(cid) != 64 {
  1367. c.Fatalf("--cidfile should be a long id, not %q", id)
  1368. }
  1369. if cid != id {
  1370. c.Fatalf("cid must be equal to %s, got %s", id, cid)
  1371. }
  1372. }
  1373. func (s *DockerSuite) TestRunSetMacAddress(c *check.C) {
  1374. mac := "12:34:56:78:9a:bc"
  1375. out, _ := dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "/bin/sh", "-c", "ip link show eth0 | tail -1 | awk '{print $2}'")
  1376. actualMac := strings.TrimSpace(out)
  1377. if actualMac != mac {
  1378. c.Fatalf("Set MAC address with --mac-address failed. The container has an incorrect MAC address: %q, expected: %q", actualMac, mac)
  1379. }
  1380. }
  1381. func (s *DockerSuite) TestRunInspectMacAddress(c *check.C) {
  1382. mac := "12:34:56:78:9a:bc"
  1383. out, _ := dockerCmd(c, "run", "-d", "--mac-address="+mac, "busybox", "top")
  1384. id := strings.TrimSpace(out)
  1385. inspectedMac, err := inspectField(id, "NetworkSettings.MacAddress")
  1386. c.Assert(err, check.IsNil)
  1387. if inspectedMac != mac {
  1388. c.Fatalf("docker inspect outputs wrong MAC address: %q, should be: %q", inspectedMac, mac)
  1389. }
  1390. }
  1391. // test docker run use a invalid mac address
  1392. func (s *DockerSuite) TestRunWithInvalidMacAddress(c *check.C) {
  1393. out, _, err := dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29", "busybox")
  1394. //use a invalid mac address should with a error out
  1395. if err == nil || !strings.Contains(out, "is not a valid mac address") {
  1396. c.Fatalf("run with an invalid --mac-address should with error out")
  1397. }
  1398. }
  1399. func (s *DockerSuite) TestRunDeallocatePortOnMissingIptablesRule(c *check.C) {
  1400. testRequires(c, SameHostDaemon)
  1401. out, _ := dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top")
  1402. id := strings.TrimSpace(out)
  1403. ip, err := inspectField(id, "NetworkSettings.IPAddress")
  1404. c.Assert(err, check.IsNil)
  1405. iptCmd := exec.Command("iptables", "-D", "DOCKER", "-d", fmt.Sprintf("%s/32", ip),
  1406. "!", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-m", "tcp", "--dport", "23", "-j", "ACCEPT")
  1407. out, _, err = runCommandWithOutput(iptCmd)
  1408. if err != nil {
  1409. c.Fatal(err, out)
  1410. }
  1411. if err := deleteContainer(id); err != nil {
  1412. c.Fatal(err)
  1413. }
  1414. dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top")
  1415. }
  1416. func (s *DockerSuite) TestRunPortInUse(c *check.C) {
  1417. testRequires(c, SameHostDaemon)
  1418. port := "1234"
  1419. dockerCmd(c, "run", "-d", "-p", port+":80", "busybox", "top")
  1420. out, _, err := dockerCmdWithError("run", "-d", "-p", port+":80", "busybox", "top")
  1421. if err == nil {
  1422. c.Fatalf("Binding on used port must fail")
  1423. }
  1424. if !strings.Contains(out, "port is already allocated") {
  1425. c.Fatalf("Out must be about \"port is already allocated\", got %s", out)
  1426. }
  1427. }
  1428. // https://github.com/docker/docker/issues/12148
  1429. func (s *DockerSuite) TestRunAllocatePortInReservedRange(c *check.C) {
  1430. // allocate a dynamic port to get the most recent
  1431. out, _ := dockerCmd(c, "run", "-d", "-P", "-p", "80", "busybox", "top")
  1432. id := strings.TrimSpace(out)
  1433. out, _ = dockerCmd(c, "port", id, "80")
  1434. strPort := strings.Split(strings.TrimSpace(out), ":")[1]
  1435. port, err := strconv.ParseInt(strPort, 10, 64)
  1436. if err != nil {
  1437. c.Fatalf("invalid port, got: %s, error: %s", strPort, err)
  1438. }
  1439. // allocate a static port and a dynamic port together, with static port
  1440. // takes the next recent port in dynamic port range.
  1441. dockerCmd(c, "run", "-d", "-P", "-p", "80", "-p", fmt.Sprintf("%d:8080", port+1), "busybox", "top")
  1442. }
  1443. // Regression test for #7792
  1444. func (s *DockerSuite) TestRunMountOrdering(c *check.C) {
  1445. testRequires(c, SameHostDaemon)
  1446. tmpDir, err := ioutil.TempDir("", "docker_nested_mount_test")
  1447. if err != nil {
  1448. c.Fatal(err)
  1449. }
  1450. defer os.RemoveAll(tmpDir)
  1451. tmpDir2, err := ioutil.TempDir("", "docker_nested_mount_test2")
  1452. if err != nil {
  1453. c.Fatal(err)
  1454. }
  1455. defer os.RemoveAll(tmpDir2)
  1456. // Create a temporary tmpfs mounc.
  1457. fooDir := filepath.Join(tmpDir, "foo")
  1458. if err := os.MkdirAll(filepath.Join(tmpDir, "foo"), 0755); err != nil {
  1459. c.Fatalf("failed to mkdir at %s - %s", fooDir, err)
  1460. }
  1461. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", fooDir), []byte{}, 0644); err != nil {
  1462. c.Fatal(err)
  1463. }
  1464. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir), []byte{}, 0644); err != nil {
  1465. c.Fatal(err)
  1466. }
  1467. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir2), []byte{}, 0644); err != nil {
  1468. c.Fatal(err)
  1469. }
  1470. dockerCmd(c, "run",
  1471. "-v", fmt.Sprintf("%s:/tmp", tmpDir),
  1472. "-v", fmt.Sprintf("%s:/tmp/foo", fooDir),
  1473. "-v", fmt.Sprintf("%s:/tmp/tmp2", tmpDir2),
  1474. "-v", fmt.Sprintf("%s:/tmp/tmp2/foo", fooDir),
  1475. "busybox:latest", "sh", "-c",
  1476. "ls /tmp/touch-me && ls /tmp/foo/touch-me && ls /tmp/tmp2/touch-me && ls /tmp/tmp2/foo/touch-me")
  1477. }
  1478. // Regression test for https://github.com/docker/docker/issues/8259
  1479. func (s *DockerSuite) TestRunReuseBindVolumeThatIsSymlink(c *check.C) {
  1480. testRequires(c, SameHostDaemon)
  1481. tmpDir, err := ioutil.TempDir(os.TempDir(), "testlink")
  1482. if err != nil {
  1483. c.Fatal(err)
  1484. }
  1485. defer os.RemoveAll(tmpDir)
  1486. linkPath := os.TempDir() + "/testlink2"
  1487. if err := os.Symlink(tmpDir, linkPath); err != nil {
  1488. c.Fatal(err)
  1489. }
  1490. defer os.RemoveAll(linkPath)
  1491. // Create first container
  1492. dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
  1493. // Create second container with same symlinked path
  1494. // This will fail if the referenced issue is hit with a "Volume exists" error
  1495. dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
  1496. }
  1497. //GH#10604: Test an "/etc" volume doesn't overlay special bind mounts in container
  1498. func (s *DockerSuite) TestRunCreateVolumeEtc(c *check.C) {
  1499. out, _ := dockerCmd(c, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf")
  1500. if !strings.Contains(out, "nameserver 127.0.0.1") {
  1501. c.Fatal("/etc volume mount hides /etc/resolv.conf")
  1502. }
  1503. out, _ = dockerCmd(c, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname")
  1504. if !strings.Contains(out, "test123") {
  1505. c.Fatal("/etc volume mount hides /etc/hostname")
  1506. }
  1507. out, _ = dockerCmd(c, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts")
  1508. out = strings.Replace(out, "\n", " ", -1)
  1509. if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") {
  1510. c.Fatal("/etc volume mount hides /etc/hosts")
  1511. }
  1512. }
  1513. func (s *DockerSuite) TestVolumesNoCopyData(c *check.C) {
  1514. if _, err := buildImage("dataimage",
  1515. `FROM busybox
  1516. RUN mkdir -p /foo
  1517. RUN touch /foo/bar`,
  1518. true); err != nil {
  1519. c.Fatal(err)
  1520. }
  1521. dockerCmd(c, "run", "--name", "test", "-v", "/foo", "busybox")
  1522. if out, _, err := dockerCmdWithError("run", "--volumes-from", "test", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") {
  1523. c.Fatalf("Data was copied on volumes-from but shouldn't be:\n%q", out)
  1524. }
  1525. tmpDir := randomUnixTmpDirPath("docker_test_bind_mount_copy_data")
  1526. if out, _, err := dockerCmdWithError("run", "-v", tmpDir+":/foo", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") {
  1527. c.Fatalf("Data was copied on bind-mount but shouldn't be:\n%q", out)
  1528. }
  1529. }
  1530. func (s *DockerSuite) TestRunNoOutputFromPullInStdout(c *check.C) {
  1531. // just run with unknown image
  1532. cmd := exec.Command(dockerBinary, "run", "asdfsg")
  1533. stdout := bytes.NewBuffer(nil)
  1534. cmd.Stdout = stdout
  1535. if err := cmd.Run(); err == nil {
  1536. c.Fatal("Run with unknown image should fail")
  1537. }
  1538. if stdout.Len() != 0 {
  1539. c.Fatalf("Stdout contains output from pull: %s", stdout)
  1540. }
  1541. }
  1542. func (s *DockerSuite) TestRunVolumesCleanPaths(c *check.C) {
  1543. if _, err := buildImage("run_volumes_clean_paths",
  1544. `FROM busybox
  1545. VOLUME /foo/`,
  1546. true); err != nil {
  1547. c.Fatal(err)
  1548. }
  1549. dockerCmd(c, "run", "-v", "/foo", "-v", "/bar/", "--name", "dark_helmet", "run_volumes_clean_paths")
  1550. out, err := inspectMountSourceField("dark_helmet", "/foo/")
  1551. if err != errMountNotFound {
  1552. c.Fatalf("Found unexpected volume entry for '/foo/' in volumes\n%q", out)
  1553. }
  1554. out, err = inspectMountSourceField("dark_helmet", "/foo")
  1555. c.Assert(err, check.IsNil)
  1556. if !strings.Contains(out, volumesConfigPath) {
  1557. c.Fatalf("Volume was not defined for /foo\n%q", out)
  1558. }
  1559. out, err = inspectMountSourceField("dark_helmet", "/bar/")
  1560. if err != errMountNotFound {
  1561. c.Fatalf("Found unexpected volume entry for '/bar/' in volumes\n%q", out)
  1562. }
  1563. out, err = inspectMountSourceField("dark_helmet", "/bar")
  1564. c.Assert(err, check.IsNil)
  1565. if !strings.Contains(out, volumesConfigPath) {
  1566. c.Fatalf("Volume was not defined for /bar\n%q", out)
  1567. }
  1568. }
  1569. // Regression test for #3631
  1570. func (s *DockerSuite) TestRunSlowStdoutConsumer(c *check.C) {
  1571. cont := exec.Command(dockerBinary, "run", "--rm", "busybox", "/bin/sh", "-c", "dd if=/dev/zero of=/dev/stdout bs=1024 count=2000 | catv")
  1572. stdout, err := cont.StdoutPipe()
  1573. if err != nil {
  1574. c.Fatal(err)
  1575. }
  1576. if err := cont.Start(); err != nil {
  1577. c.Fatal(err)
  1578. }
  1579. n, err := consumeWithSpeed(stdout, 10000, 5*time.Millisecond, nil)
  1580. if err != nil {
  1581. c.Fatal(err)
  1582. }
  1583. expected := 2 * 1024 * 2000
  1584. if n != expected {
  1585. c.Fatalf("Expected %d, got %d", expected, n)
  1586. }
  1587. }
  1588. func (s *DockerSuite) TestRunAllowPortRangeThroughExpose(c *check.C) {
  1589. out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top")
  1590. id := strings.TrimSpace(out)
  1591. portstr, err := inspectFieldJSON(id, "NetworkSettings.Ports")
  1592. c.Assert(err, check.IsNil)
  1593. var ports nat.PortMap
  1594. if err = unmarshalJSON([]byte(portstr), &ports); err != nil {
  1595. c.Fatal(err)
  1596. }
  1597. for port, binding := range ports {
  1598. portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  1599. if portnum < 3000 || portnum > 3003 {
  1600. c.Fatalf("Port %d is out of range ", portnum)
  1601. }
  1602. if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  1603. c.Fatalf("Port is not mapped for the port %s", port)
  1604. }
  1605. }
  1606. }
  1607. // test docker run expose a invalid port
  1608. func (s *DockerSuite) TestRunExposePort(c *check.C) {
  1609. out, _, err := dockerCmdWithError("run", "--expose", "80000", "busybox")
  1610. //expose a invalid port should with a error out
  1611. if err == nil || !strings.Contains(out, "Invalid range format for --expose") {
  1612. c.Fatalf("run --expose a invalid port should with error out")
  1613. }
  1614. }
  1615. func (s *DockerSuite) TestRunUnknownCommand(c *check.C) {
  1616. testRequires(c, NativeExecDriver)
  1617. out, _, _ := dockerCmdWithStdoutStderr(c, "create", "busybox", "/bin/nada")
  1618. cID := strings.TrimSpace(out)
  1619. _, _, err := dockerCmdWithError("start", cID)
  1620. c.Assert(err, check.NotNil)
  1621. rc, err := inspectField(cID, "State.ExitCode")
  1622. c.Assert(err, check.IsNil)
  1623. if rc == "0" {
  1624. c.Fatalf("ExitCode(%v) cannot be 0", rc)
  1625. }
  1626. }
  1627. func (s *DockerSuite) TestRunModeIpcHost(c *check.C) {
  1628. testRequires(c, SameHostDaemon)
  1629. hostIpc, err := os.Readlink("/proc/1/ns/ipc")
  1630. if err != nil {
  1631. c.Fatal(err)
  1632. }
  1633. out, _ := dockerCmd(c, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc")
  1634. out = strings.Trim(out, "\n")
  1635. if hostIpc != out {
  1636. c.Fatalf("IPC different with --ipc=host %s != %s\n", hostIpc, out)
  1637. }
  1638. out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/ipc")
  1639. out = strings.Trim(out, "\n")
  1640. if hostIpc == out {
  1641. c.Fatalf("IPC should be different without --ipc=host %s == %s\n", hostIpc, out)
  1642. }
  1643. }
  1644. func (s *DockerSuite) TestRunModeIpcContainer(c *check.C) {
  1645. testRequires(c, SameHostDaemon)
  1646. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1647. id := strings.TrimSpace(out)
  1648. state, err := inspectField(id, "State.Running")
  1649. c.Assert(err, check.IsNil)
  1650. if state != "true" {
  1651. c.Fatal("Container state is 'not running'")
  1652. }
  1653. pid1, err := inspectField(id, "State.Pid")
  1654. c.Assert(err, check.IsNil)
  1655. parentContainerIpc, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/ipc", pid1))
  1656. if err != nil {
  1657. c.Fatal(err)
  1658. }
  1659. out, _ = dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "readlink", "/proc/self/ns/ipc")
  1660. out = strings.Trim(out, "\n")
  1661. if parentContainerIpc != out {
  1662. c.Fatalf("IPC different with --ipc=container:%s %s != %s\n", id, parentContainerIpc, out)
  1663. }
  1664. }
  1665. func (s *DockerSuite) TestRunModeIpcContainerNotExists(c *check.C) {
  1666. out, _, err := dockerCmdWithError("run", "-d", "--ipc", "container:abcd1234", "busybox", "top")
  1667. if !strings.Contains(out, "abcd1234") || err == nil {
  1668. c.Fatalf("run IPC from a non exists container should with correct error out")
  1669. }
  1670. }
  1671. func (s *DockerSuite) TestRunModeIpcContainerNotRunning(c *check.C) {
  1672. testRequires(c, SameHostDaemon)
  1673. out, _ := dockerCmd(c, "create", "busybox")
  1674. id := strings.TrimSpace(out)
  1675. out, _, err := dockerCmdWithError("run", fmt.Sprintf("--ipc=container:%s", id), "busybox")
  1676. if err == nil {
  1677. c.Fatalf("Run container with ipc mode container should fail with non running container: %s\n%s", out, err)
  1678. }
  1679. }
  1680. func (s *DockerSuite) TestContainerNetworkMode(c *check.C) {
  1681. testRequires(c, SameHostDaemon)
  1682. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1683. id := strings.TrimSpace(out)
  1684. c.Assert(waitRun(id), check.IsNil)
  1685. pid1, err := inspectField(id, "State.Pid")
  1686. c.Assert(err, check.IsNil)
  1687. parentContainerNet, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
  1688. if err != nil {
  1689. c.Fatal(err)
  1690. }
  1691. out, _ = dockerCmd(c, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net")
  1692. out = strings.Trim(out, "\n")
  1693. if parentContainerNet != out {
  1694. c.Fatalf("NET different with --net=container:%s %s != %s\n", id, parentContainerNet, out)
  1695. }
  1696. }
  1697. func (s *DockerSuite) TestRunModePidHost(c *check.C) {
  1698. testRequires(c, NativeExecDriver, SameHostDaemon)
  1699. hostPid, err := os.Readlink("/proc/1/ns/pid")
  1700. if err != nil {
  1701. c.Fatal(err)
  1702. }
  1703. out, _ := dockerCmd(c, "run", "--pid=host", "busybox", "readlink", "/proc/self/ns/pid")
  1704. out = strings.Trim(out, "\n")
  1705. if hostPid != out {
  1706. c.Fatalf("PID different with --pid=host %s != %s\n", hostPid, out)
  1707. }
  1708. out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/pid")
  1709. out = strings.Trim(out, "\n")
  1710. if hostPid == out {
  1711. c.Fatalf("PID should be different without --pid=host %s == %s\n", hostPid, out)
  1712. }
  1713. }
  1714. func (s *DockerSuite) TestRunModeUTSHost(c *check.C) {
  1715. testRequires(c, NativeExecDriver, SameHostDaemon)
  1716. hostUTS, err := os.Readlink("/proc/1/ns/uts")
  1717. if err != nil {
  1718. c.Fatal(err)
  1719. }
  1720. out, _ := dockerCmd(c, "run", "--uts=host", "busybox", "readlink", "/proc/self/ns/uts")
  1721. out = strings.Trim(out, "\n")
  1722. if hostUTS != out {
  1723. c.Fatalf("UTS different with --uts=host %s != %s\n", hostUTS, out)
  1724. }
  1725. out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/uts")
  1726. out = strings.Trim(out, "\n")
  1727. if hostUTS == out {
  1728. c.Fatalf("UTS should be different without --uts=host %s == %s\n", hostUTS, out)
  1729. }
  1730. }
  1731. func (s *DockerSuite) TestRunTLSverify(c *check.C) {
  1732. if out, code, err := dockerCmdWithError("ps"); err != nil || code != 0 {
  1733. c.Fatalf("Should have worked: %v:\n%v", err, out)
  1734. }
  1735. // Regardless of whether we specify true or false we need to
  1736. // test to make sure tls is turned on if --tlsverify is specified at all
  1737. out, code, err := dockerCmdWithError("--tlsverify=false", "ps")
  1738. if err == nil || code == 0 || !strings.Contains(out, "trying to connect") {
  1739. c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err)
  1740. }
  1741. out, code, err = dockerCmdWithError("--tlsverify=true", "ps")
  1742. if err == nil || code == 0 || !strings.Contains(out, "cert") {
  1743. c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err)
  1744. }
  1745. }
  1746. func (s *DockerSuite) TestRunPortFromDockerRangeInUse(c *check.C) {
  1747. // first find allocator current position
  1748. out, _ := dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
  1749. id := strings.TrimSpace(out)
  1750. out, _ = dockerCmd(c, "port", id)
  1751. out = strings.TrimSpace(out)
  1752. if out == "" {
  1753. c.Fatal("docker port command output is empty")
  1754. }
  1755. out = strings.Split(out, ":")[1]
  1756. lastPort, err := strconv.Atoi(out)
  1757. if err != nil {
  1758. c.Fatal(err)
  1759. }
  1760. port := lastPort + 1
  1761. l, err := net.Listen("tcp", ":"+strconv.Itoa(port))
  1762. if err != nil {
  1763. c.Fatal(err)
  1764. }
  1765. defer l.Close()
  1766. out, _ = dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
  1767. id = strings.TrimSpace(out)
  1768. dockerCmd(c, "port", id)
  1769. }
  1770. func (s *DockerSuite) TestRunTtyWithPipe(c *check.C) {
  1771. errChan := make(chan error)
  1772. go func() {
  1773. defer close(errChan)
  1774. cmd := exec.Command(dockerBinary, "run", "-ti", "busybox", "true")
  1775. if _, err := cmd.StdinPipe(); err != nil {
  1776. errChan <- err
  1777. return
  1778. }
  1779. expected := "cannot enable tty mode"
  1780. if out, _, err := runCommandWithOutput(cmd); err == nil {
  1781. errChan <- fmt.Errorf("run should have failed")
  1782. return
  1783. } else if !strings.Contains(out, expected) {
  1784. errChan <- fmt.Errorf("run failed with error %q: expected %q", out, expected)
  1785. return
  1786. }
  1787. }()
  1788. select {
  1789. case err := <-errChan:
  1790. c.Assert(err, check.IsNil)
  1791. case <-time.After(3 * time.Second):
  1792. c.Fatal("container is running but should have failed")
  1793. }
  1794. }
  1795. func (s *DockerSuite) TestRunNonLocalMacAddress(c *check.C) {
  1796. addr := "00:16:3E:08:00:50"
  1797. if out, _ := dockerCmd(c, "run", "--mac-address", addr, "busybox", "ifconfig"); !strings.Contains(out, addr) {
  1798. c.Fatalf("Output should have contained %q: %s", addr, out)
  1799. }
  1800. }
  1801. func (s *DockerSuite) TestRunNetHost(c *check.C) {
  1802. testRequires(c, SameHostDaemon)
  1803. hostNet, err := os.Readlink("/proc/1/ns/net")
  1804. if err != nil {
  1805. c.Fatal(err)
  1806. }
  1807. out, _ := dockerCmd(c, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net")
  1808. out = strings.Trim(out, "\n")
  1809. if hostNet != out {
  1810. c.Fatalf("Net namespace different with --net=host %s != %s\n", hostNet, out)
  1811. }
  1812. out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/net")
  1813. out = strings.Trim(out, "\n")
  1814. if hostNet == out {
  1815. c.Fatalf("Net namespace should be different without --net=host %s == %s\n", hostNet, out)
  1816. }
  1817. }
  1818. func (s *DockerSuite) TestRunNetHostTwiceSameName(c *check.C) {
  1819. testRequires(c, SameHostDaemon)
  1820. dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
  1821. dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
  1822. }
  1823. func (s *DockerSuite) TestRunNetContainerWhichHost(c *check.C) {
  1824. testRequires(c, SameHostDaemon)
  1825. hostNet, err := os.Readlink("/proc/1/ns/net")
  1826. if err != nil {
  1827. c.Fatal(err)
  1828. }
  1829. dockerCmd(c, "run", "-d", "--net=host", "--name=test", "busybox", "top")
  1830. out, _ := dockerCmd(c, "run", "--net=container:test", "busybox", "readlink", "/proc/self/ns/net")
  1831. out = strings.Trim(out, "\n")
  1832. if hostNet != out {
  1833. c.Fatalf("Container should have host network namespace")
  1834. }
  1835. }
  1836. func (s *DockerSuite) TestRunAllowPortRangeThroughPublish(c *check.C) {
  1837. out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top")
  1838. id := strings.TrimSpace(out)
  1839. portstr, err := inspectFieldJSON(id, "NetworkSettings.Ports")
  1840. c.Assert(err, check.IsNil)
  1841. var ports nat.PortMap
  1842. err = unmarshalJSON([]byte(portstr), &ports)
  1843. for port, binding := range ports {
  1844. portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  1845. if portnum < 3000 || portnum > 3003 {
  1846. c.Fatalf("Port %d is out of range ", portnum)
  1847. }
  1848. if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  1849. c.Fatal("Port is not mapped for the port "+port, out)
  1850. }
  1851. }
  1852. }
  1853. func (s *DockerSuite) TestRunSetDefaultRestartPolicy(c *check.C) {
  1854. dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")
  1855. out, err := inspectField("test", "HostConfig.RestartPolicy.Name")
  1856. c.Assert(err, check.IsNil)
  1857. if out != "no" {
  1858. c.Fatalf("Set default restart policy failed")
  1859. }
  1860. }
  1861. func (s *DockerSuite) TestRunRestartMaxRetries(c *check.C) {
  1862. out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false")
  1863. id := strings.TrimSpace(string(out))
  1864. if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", 10); err != nil {
  1865. c.Fatal(err)
  1866. }
  1867. count, err := inspectField(id, "RestartCount")
  1868. c.Assert(err, check.IsNil)
  1869. if count != "3" {
  1870. c.Fatalf("Container was restarted %s times, expected %d", count, 3)
  1871. }
  1872. MaximumRetryCount, err := inspectField(id, "HostConfig.RestartPolicy.MaximumRetryCount")
  1873. c.Assert(err, check.IsNil)
  1874. if MaximumRetryCount != "3" {
  1875. c.Fatalf("Container Maximum Retry Count is %s, expected %s", MaximumRetryCount, "3")
  1876. }
  1877. }
  1878. func (s *DockerSuite) TestRunContainerWithWritableRootfs(c *check.C) {
  1879. dockerCmd(c, "run", "--rm", "busybox", "touch", "/file")
  1880. }
  1881. func (s *DockerSuite) TestRunContainerWithReadonlyRootfs(c *check.C) {
  1882. testRequires(c, NativeExecDriver)
  1883. for _, f := range []string{"/file", "/etc/hosts", "/etc/resolv.conf", "/etc/hostname", "/sys/kernel", "/dev/.dont.touch.me"} {
  1884. testReadOnlyFile(f, c)
  1885. }
  1886. }
  1887. func (s *DockerSuite) TestPermissionsPtsReadonlyRootfs(c *check.C) {
  1888. testRequires(c, NativeExecDriver)
  1889. // Ensure we have not broken writing /dev/pts
  1890. out, status := dockerCmd(c, "run", "--read-only", "--rm", "busybox", "mount")
  1891. if status != 0 {
  1892. c.Fatal("Could not obtain mounts when checking /dev/pts mntpnt.")
  1893. }
  1894. expected := "type devpts (rw,"
  1895. if !strings.Contains(string(out), expected) {
  1896. c.Fatalf("expected output to contain %s but contains %s", expected, out)
  1897. }
  1898. }
  1899. func testReadOnlyFile(filename string, c *check.C) {
  1900. testRequires(c, NativeExecDriver)
  1901. out, _, err := dockerCmdWithError("run", "--read-only", "--rm", "busybox", "touch", filename)
  1902. if err == nil {
  1903. c.Fatal("expected container to error on run with read only error")
  1904. }
  1905. expected := "Read-only file system"
  1906. if !strings.Contains(string(out), expected) {
  1907. c.Fatalf("expected output from failure to contain %s but contains %s", expected, out)
  1908. }
  1909. out, _, err = dockerCmdWithError("run", "--read-only", "--privileged", "--rm", "busybox", "touch", filename)
  1910. if err == nil {
  1911. c.Fatal("expected container to error on run with read only error")
  1912. }
  1913. expected = "Read-only file system"
  1914. if !strings.Contains(string(out), expected) {
  1915. c.Fatalf("expected output from failure to contain %s but contains %s", expected, out)
  1916. }
  1917. }
  1918. func (s *DockerSuite) TestRunContainerWithReadonlyEtcHostsAndLinkedContainer(c *check.C) {
  1919. testRequires(c, NativeExecDriver)
  1920. dockerCmd(c, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top")
  1921. out, _ := dockerCmd(c, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts")
  1922. if !strings.Contains(string(out), "testlinked") {
  1923. c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled")
  1924. }
  1925. }
  1926. func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithDnsFlag(c *check.C) {
  1927. testRequires(c, NativeExecDriver)
  1928. out, _ := dockerCmd(c, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf")
  1929. if !strings.Contains(string(out), "1.1.1.1") {
  1930. c.Fatal("Expected /etc/resolv.conf to be updated even if --read-only enabled and --dns flag used")
  1931. }
  1932. }
  1933. func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithAddHostFlag(c *check.C) {
  1934. testRequires(c, NativeExecDriver)
  1935. out, _ := dockerCmd(c, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts")
  1936. if !strings.Contains(string(out), "testreadonly") {
  1937. c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled and --add-host flag used")
  1938. }
  1939. }
  1940. func (s *DockerSuite) TestRunVolumesFromRestartAfterRemoved(c *check.C) {
  1941. dockerCmd(c, "run", "-d", "--name", "voltest", "-v", "/foo", "busybox")
  1942. dockerCmd(c, "run", "-d", "--name", "restarter", "--volumes-from", "voltest", "busybox", "top")
  1943. // Remove the main volume container and restart the consuming container
  1944. dockerCmd(c, "rm", "-f", "voltest")
  1945. // This should not fail since the volumes-from were already applied
  1946. dockerCmd(c, "restart", "restarter")
  1947. }
  1948. // run container with --rm should remove container if exit code != 0
  1949. func (s *DockerSuite) TestRunContainerWithRmFlagExitCodeNotEqualToZero(c *check.C) {
  1950. name := "flowers"
  1951. out, _, err := dockerCmdWithError("run", "--name", name, "--rm", "busybox", "ls", "/notexists")
  1952. if err == nil {
  1953. c.Fatal("Expected docker run to fail", out, err)
  1954. }
  1955. out, err = getAllContainers()
  1956. if err != nil {
  1957. c.Fatal(out, err)
  1958. }
  1959. if out != "" {
  1960. c.Fatal("Expected not to have containers", out)
  1961. }
  1962. }
  1963. func (s *DockerSuite) TestRunContainerWithRmFlagCannotStartContainer(c *check.C) {
  1964. name := "sparkles"
  1965. out, _, err := dockerCmdWithError("run", "--name", name, "--rm", "busybox", "commandNotFound")
  1966. if err == nil {
  1967. c.Fatal("Expected docker run to fail", out, err)
  1968. }
  1969. out, err = getAllContainers()
  1970. if err != nil {
  1971. c.Fatal(out, err)
  1972. }
  1973. if out != "" {
  1974. c.Fatal("Expected not to have containers", out)
  1975. }
  1976. }
  1977. func (s *DockerSuite) TestRunPidHostWithChildIsKillable(c *check.C) {
  1978. name := "ibuildthecloud"
  1979. dockerCmd(c, "run", "-d", "--pid=host", "--name", name, "busybox", "sh", "-c", "sleep 30; echo hi")
  1980. c.Assert(waitRun(name), check.IsNil)
  1981. errchan := make(chan error)
  1982. go func() {
  1983. if out, _, err := dockerCmdWithError("kill", name); err != nil {
  1984. errchan <- fmt.Errorf("%v:\n%s", err, out)
  1985. }
  1986. close(errchan)
  1987. }()
  1988. select {
  1989. case err := <-errchan:
  1990. c.Assert(err, check.IsNil)
  1991. case <-time.After(5 * time.Second):
  1992. c.Fatal("Kill container timed out")
  1993. }
  1994. }
  1995. func (s *DockerSuite) TestRunWithTooSmallMemoryLimit(c *check.C) {
  1996. // this memory limit is 1 byte less than the min, which is 4MB
  1997. // https://github.com/docker/docker/blob/v1.5.0/daemon/create.go#L22
  1998. out, _, err := dockerCmdWithError("run", "-m", "4194303", "busybox")
  1999. if err == nil || !strings.Contains(out, "Minimum memory limit allowed is 4MB") {
  2000. c.Fatalf("expected run to fail when using too low a memory limit: %q", out)
  2001. }
  2002. }
  2003. func (s *DockerSuite) TestRunWriteToProcAsound(c *check.C) {
  2004. _, code, err := dockerCmdWithError("run", "busybox", "sh", "-c", "echo 111 >> /proc/asound/version")
  2005. if err == nil || code == 0 {
  2006. c.Fatal("standard container should not be able to write to /proc/asound")
  2007. }
  2008. }
  2009. func (s *DockerSuite) TestRunReadProcTimer(c *check.C) {
  2010. testRequires(c, NativeExecDriver)
  2011. out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/timer_stats")
  2012. if code != 0 {
  2013. return
  2014. }
  2015. if err != nil {
  2016. c.Fatal(err)
  2017. }
  2018. if strings.Trim(out, "\n ") != "" {
  2019. c.Fatalf("expected to receive no output from /proc/timer_stats but received %q", out)
  2020. }
  2021. }
  2022. func (s *DockerSuite) TestRunReadProcLatency(c *check.C) {
  2023. testRequires(c, NativeExecDriver)
  2024. // some kernels don't have this configured so skip the test if this file is not found
  2025. // on the host running the tests.
  2026. if _, err := os.Stat("/proc/latency_stats"); err != nil {
  2027. c.Skip("kernel doesnt have latency_stats configured")
  2028. return
  2029. }
  2030. out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/latency_stats")
  2031. if code != 0 {
  2032. return
  2033. }
  2034. if err != nil {
  2035. c.Fatal(err)
  2036. }
  2037. if strings.Trim(out, "\n ") != "" {
  2038. c.Fatalf("expected to receive no output from /proc/latency_stats but received %q", out)
  2039. }
  2040. }
  2041. func (s *DockerSuite) TestRunReadFilteredProc(c *check.C) {
  2042. testRequires(c, Apparmor)
  2043. testReadPaths := []string{
  2044. "/proc/latency_stats",
  2045. "/proc/timer_stats",
  2046. "/proc/kcore",
  2047. }
  2048. for i, filePath := range testReadPaths {
  2049. name := fmt.Sprintf("procsieve-%d", i)
  2050. shellCmd := fmt.Sprintf("exec 3<%s", filePath)
  2051. out, exitCode, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor:docker-default", "--name", name, "busybox", "sh", "-c", shellCmd)
  2052. if exitCode != 0 {
  2053. return
  2054. }
  2055. if err != nil {
  2056. c.Fatalf("Open FD for read should have failed with permission denied, got: %s, %v", out, err)
  2057. }
  2058. }
  2059. }
  2060. func (s *DockerSuite) TestMountIntoProc(c *check.C) {
  2061. testRequires(c, NativeExecDriver)
  2062. _, code, err := dockerCmdWithError("run", "-v", "/proc//sys", "busybox", "true")
  2063. if err == nil || code == 0 {
  2064. c.Fatal("container should not be able to mount into /proc")
  2065. }
  2066. }
  2067. func (s *DockerSuite) TestMountIntoSys(c *check.C) {
  2068. testRequires(c, NativeExecDriver)
  2069. dockerCmd(c, "run", "-v", "/sys/fs/cgroup", "busybox", "true")
  2070. }
  2071. func (s *DockerSuite) TestRunUnshareProc(c *check.C) {
  2072. testRequires(c, Apparmor, NativeExecDriver)
  2073. name := "acidburn"
  2074. if out, _, err := dockerCmdWithError("run", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "--mount-proc=/proc", "mount"); err == nil || !strings.Contains(out, "Permission denied") {
  2075. c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err)
  2076. }
  2077. name = "cereal"
  2078. if out, _, err := dockerCmdWithError("run", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc"); err == nil || !strings.Contains(out, "Permission denied") {
  2079. c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err)
  2080. }
  2081. /* Ensure still fails if running privileged with the default policy */
  2082. name = "crashoverride"
  2083. if out, _, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor:docker-default", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc"); err == nil || !strings.Contains(out, "Permission denied") {
  2084. c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err)
  2085. }
  2086. }
  2087. func (s *DockerSuite) TestRunPublishPort(c *check.C) {
  2088. dockerCmd(c, "run", "-d", "--name", "test", "--expose", "8080", "busybox", "top")
  2089. out, _ := dockerCmd(c, "port", "test")
  2090. out = strings.Trim(out, "\r\n")
  2091. if out != "" {
  2092. c.Fatalf("run without --publish-all should not publish port, out should be nil, but got: %s", out)
  2093. }
  2094. }
  2095. // Issue #10184.
  2096. func (s *DockerSuite) TestDevicePermissions(c *check.C) {
  2097. testRequires(c, NativeExecDriver)
  2098. const permissions = "crw-rw-rw-"
  2099. out, status := dockerCmd(c, "run", "--device", "/dev/fuse:/dev/fuse:mrw", "busybox:latest", "ls", "-l", "/dev/fuse")
  2100. if status != 0 {
  2101. c.Fatalf("expected status 0, got %d", status)
  2102. }
  2103. if !strings.HasPrefix(out, permissions) {
  2104. c.Fatalf("output should begin with %q, got %q", permissions, out)
  2105. }
  2106. }
  2107. func (s *DockerSuite) TestRunCapAddCHOWN(c *check.C) {
  2108. testRequires(c, NativeExecDriver)
  2109. out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok")
  2110. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  2111. c.Fatalf("expected output ok received %s", actual)
  2112. }
  2113. }
  2114. // https://github.com/docker/docker/pull/14498
  2115. func (s *DockerSuite) TestVolumeFromMixedRWOptions(c *check.C) {
  2116. dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true")
  2117. dockerCmd(c, "run", "--volumes-from", "parent:ro", "--name", "test-volumes-1", "busybox", "true")
  2118. dockerCmd(c, "run", "--volumes-from", "parent:rw", "--name", "test-volumes-2", "busybox", "true")
  2119. mRO, err := inspectMountPoint("test-volumes-1", "/test")
  2120. c.Assert(err, check.IsNil)
  2121. if mRO.RW {
  2122. c.Fatalf("Expected RO volume was RW")
  2123. }
  2124. mRW, err := inspectMountPoint("test-volumes-2", "/test")
  2125. c.Assert(err, check.IsNil)
  2126. if !mRW.RW {
  2127. c.Fatalf("Expected RW volume was RO")
  2128. }
  2129. }
  2130. func (s *DockerSuite) TestRunWriteFilteredProc(c *check.C) {
  2131. testRequires(c, Apparmor, NativeExecDriver)
  2132. testWritePaths := []string{
  2133. /* modprobe and core_pattern should both be denied by generic
  2134. * policy of denials for /proc/sys/kernel. These files have been
  2135. * picked to be checked as they are particularly sensitive to writes */
  2136. "/proc/sys/kernel/modprobe",
  2137. "/proc/sys/kernel/core_pattern",
  2138. "/proc/sysrq-trigger",
  2139. "/proc/kcore",
  2140. }
  2141. for i, filePath := range testWritePaths {
  2142. name := fmt.Sprintf("writeprocsieve-%d", i)
  2143. shellCmd := fmt.Sprintf("exec 3>%s", filePath)
  2144. out, code, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor:docker-default", "--name", name, "busybox", "sh", "-c", shellCmd)
  2145. if code != 0 {
  2146. return
  2147. }
  2148. if err != nil {
  2149. c.Fatalf("Open FD for write should have failed with permission denied, got: %s, %v", out, err)
  2150. }
  2151. }
  2152. }
  2153. func (s *DockerSuite) TestRunNetworkFilesBindMount(c *check.C) {
  2154. testRequires(c, SameHostDaemon)
  2155. expected := "test123"
  2156. filename := createTmpFile(c, expected)
  2157. defer os.Remove(filename)
  2158. nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  2159. for i := range nwfiles {
  2160. actual, _ := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "busybox", "cat", nwfiles[i])
  2161. if actual != expected {
  2162. c.Fatalf("expected %s be: %q, but was: %q", nwfiles[i], expected, actual)
  2163. }
  2164. }
  2165. }
  2166. func (s *DockerSuite) TestRunNetworkFilesBindMountRO(c *check.C) {
  2167. testRequires(c, SameHostDaemon)
  2168. filename := createTmpFile(c, "test123")
  2169. defer os.Remove(filename)
  2170. nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  2171. for i := range nwfiles {
  2172. _, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "busybox", "touch", nwfiles[i])
  2173. if err == nil || exitCode == 0 {
  2174. c.Fatalf("run should fail because bind mount of %s is ro: exit code %d", nwfiles[i], exitCode)
  2175. }
  2176. }
  2177. }
  2178. func (s *DockerSuite) TestRunNetworkFilesBindMountROFilesystem(c *check.C) {
  2179. testRequires(c, SameHostDaemon)
  2180. filename := createTmpFile(c, "test123")
  2181. defer os.Remove(filename)
  2182. nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  2183. for i := range nwfiles {
  2184. _, exitCode := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "--read-only", "busybox", "touch", nwfiles[i])
  2185. if exitCode != 0 {
  2186. c.Fatalf("run should not fail because %s is mounted writable on read-only root filesystem: exit code %d", nwfiles[i], exitCode)
  2187. }
  2188. }
  2189. for i := range nwfiles {
  2190. _, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "--read-only", "busybox", "touch", nwfiles[i])
  2191. if err == nil || exitCode == 0 {
  2192. c.Fatalf("run should fail because %s is mounted read-only on read-only root filesystem: exit code %d", nwfiles[i], exitCode)
  2193. }
  2194. }
  2195. }
  2196. func (s *DockerTrustSuite) TestTrustedRun(c *check.C) {
  2197. repoName := s.setupTrustedImage(c, "trusted-run")
  2198. // Try run
  2199. runCmd := exec.Command(dockerBinary, "run", repoName)
  2200. s.trustedCmd(runCmd)
  2201. out, _, err := runCommandWithOutput(runCmd)
  2202. if err != nil {
  2203. c.Fatalf("Error running trusted run: %s\n%s\n", err, out)
  2204. }
  2205. if !strings.Contains(string(out), "Tagging") {
  2206. c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2207. }
  2208. dockerCmd(c, "rmi", repoName)
  2209. // Try untrusted run to ensure we pushed the tag to the registry
  2210. runCmd = exec.Command(dockerBinary, "run", "--disable-content-trust=true", repoName)
  2211. s.trustedCmd(runCmd)
  2212. out, _, err = runCommandWithOutput(runCmd)
  2213. if err != nil {
  2214. c.Fatalf("Error running trusted run: %s\n%s", err, out)
  2215. }
  2216. if !strings.Contains(string(out), "Status: Downloaded") {
  2217. c.Fatalf("Missing expected output on trusted run with --disable-content-trust:\n%s", out)
  2218. }
  2219. }
  2220. func (s *DockerTrustSuite) TestUntrustedRun(c *check.C) {
  2221. repoName := fmt.Sprintf("%v/dockercli/trusted:latest", privateRegistryURL)
  2222. // tag the image and upload it to the private registry
  2223. dockerCmd(c, "tag", "busybox", repoName)
  2224. dockerCmd(c, "push", repoName)
  2225. dockerCmd(c, "rmi", repoName)
  2226. // Try trusted run on untrusted tag
  2227. runCmd := exec.Command(dockerBinary, "run", repoName)
  2228. s.trustedCmd(runCmd)
  2229. out, _, err := runCommandWithOutput(runCmd)
  2230. if err == nil {
  2231. c.Fatalf("Error expected when running trusted run with:\n%s", out)
  2232. }
  2233. if !strings.Contains(string(out), "no trust data available") {
  2234. c.Fatalf("Missing expected output on trusted run:\n%s", out)
  2235. }
  2236. }
  2237. func (s *DockerTrustSuite) TestRunWhenCertExpired(c *check.C) {
  2238. c.Skip("Currently changes system time, causing instability")
  2239. repoName := s.setupTrustedImage(c, "trusted-run-expired")
  2240. // Certificates have 10 years of expiration
  2241. elevenYearsFromNow := time.Now().Add(time.Hour * 24 * 365 * 11)
  2242. runAtDifferentDate(elevenYearsFromNow, func() {
  2243. // Try run
  2244. runCmd := exec.Command(dockerBinary, "run", repoName)
  2245. s.trustedCmd(runCmd)
  2246. out, _, err := runCommandWithOutput(runCmd)
  2247. if err == nil {
  2248. c.Fatalf("Error running trusted run in the distant future: %s\n%s", err, out)
  2249. }
  2250. if !strings.Contains(string(out), "could not validate the path to a trusted root") {
  2251. c.Fatalf("Missing expected output on trusted run in the distant future:\n%s", out)
  2252. }
  2253. })
  2254. runAtDifferentDate(elevenYearsFromNow, func() {
  2255. // Try run
  2256. runCmd := exec.Command(dockerBinary, "run", "--disable-content-trust", repoName)
  2257. s.trustedCmd(runCmd)
  2258. out, _, err := runCommandWithOutput(runCmd)
  2259. if err != nil {
  2260. c.Fatalf("Error running untrusted run in the distant future: %s\n%s", err, out)
  2261. }
  2262. if !strings.Contains(string(out), "Status: Downloaded") {
  2263. c.Fatalf("Missing expected output on untrusted run in the distant future:\n%s", out)
  2264. }
  2265. })
  2266. }
  2267. func (s *DockerTrustSuite) TestTrustedRunFromBadTrustServer(c *check.C) {
  2268. repoName := fmt.Sprintf("%v/dockerclievilrun/trusted:latest", privateRegistryURL)
  2269. evilLocalConfigDir, err := ioutil.TempDir("", "evil-local-config-dir")
  2270. if err != nil {
  2271. c.Fatalf("Failed to create local temp dir")
  2272. }
  2273. // tag the image and upload it to the private registry
  2274. dockerCmd(c, "tag", "busybox", repoName)
  2275. pushCmd := exec.Command(dockerBinary, "push", repoName)
  2276. s.trustedCmd(pushCmd)
  2277. out, _, err := runCommandWithOutput(pushCmd)
  2278. if err != nil {
  2279. c.Fatalf("Error running trusted push: %s\n%s", err, out)
  2280. }
  2281. if !strings.Contains(string(out), "Signing and pushing trust metadata") {
  2282. c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2283. }
  2284. dockerCmd(c, "rmi", repoName)
  2285. // Try run
  2286. runCmd := exec.Command(dockerBinary, "run", repoName)
  2287. s.trustedCmd(runCmd)
  2288. out, _, err = runCommandWithOutput(runCmd)
  2289. if err != nil {
  2290. c.Fatalf("Error running trusted run: %s\n%s", err, out)
  2291. }
  2292. if !strings.Contains(string(out), "Tagging") {
  2293. c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2294. }
  2295. dockerCmd(c, "rmi", repoName)
  2296. // Kill the notary server, start a new "evil" one.
  2297. s.not.Close()
  2298. s.not, err = newTestNotary(c)
  2299. if err != nil {
  2300. c.Fatalf("Restarting notary server failed.")
  2301. }
  2302. // In order to make an evil server, lets re-init a client (with a different trust dir) and push new data.
  2303. // tag an image and upload it to the private registry
  2304. dockerCmd(c, "--config", evilLocalConfigDir, "tag", "busybox", repoName)
  2305. // Push up to the new server
  2306. pushCmd = exec.Command(dockerBinary, "--config", evilLocalConfigDir, "push", repoName)
  2307. s.trustedCmd(pushCmd)
  2308. out, _, err = runCommandWithOutput(pushCmd)
  2309. if err != nil {
  2310. c.Fatalf("Error running trusted push: %s\n%s", err, out)
  2311. }
  2312. if !strings.Contains(string(out), "Signing and pushing trust metadata") {
  2313. c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2314. }
  2315. // Now, try running with the original client from this new trust server. This should fail.
  2316. runCmd = exec.Command(dockerBinary, "run", repoName)
  2317. s.trustedCmd(runCmd)
  2318. out, _, err = runCommandWithOutput(runCmd)
  2319. if err == nil {
  2320. c.Fatalf("Expected to fail on this run due to different remote data: %s\n%s", err, out)
  2321. }
  2322. if !strings.Contains(string(out), "failed to validate data with current trusted certificates") {
  2323. c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2324. }
  2325. }
  2326. func (s *DockerSuite) TestPtraceContainerProcsFromHost(c *check.C) {
  2327. testRequires(c, SameHostDaemon)
  2328. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  2329. id := strings.TrimSpace(out)
  2330. c.Assert(waitRun(id), check.IsNil)
  2331. pid1, err := inspectField(id, "State.Pid")
  2332. c.Assert(err, check.IsNil)
  2333. _, err = os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
  2334. if err != nil {
  2335. c.Fatal(err)
  2336. }
  2337. }
  2338. func (s *DockerSuite) TestAppArmorDeniesPtrace(c *check.C) {
  2339. testRequires(c, SameHostDaemon, NativeExecDriver, Apparmor)
  2340. // Run through 'sh' so we are NOT pid 1. Pid 1 may be able to trace
  2341. // itself, but pid>1 should not be able to trace pid1.
  2342. _, exitCode, _ := dockerCmdWithError("run", "busybox", "sh", "-c", "readlink /proc/1/ns/net")
  2343. if exitCode == 0 {
  2344. c.Fatal("ptrace was not successfully restricted by AppArmor")
  2345. }
  2346. }
  2347. func (s *DockerSuite) TestAppArmorTraceSelf(c *check.C) {
  2348. testRequires(c, SameHostDaemon)
  2349. testRequires(c, Apparmor)
  2350. _, exitCode, _ := dockerCmdWithError("run", "busybox", "readlink", "/proc/1/ns/net")
  2351. if exitCode != 0 {
  2352. c.Fatal("ptrace of self failed.")
  2353. }
  2354. }
  2355. func (s *DockerSuite) TestRunCapAddSYSTIME(c *check.C) {
  2356. testRequires(c, NativeExecDriver)
  2357. dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=SYS_TIME", "busybox", "sh", "-c", "grep ^CapEff /proc/self/status | sed 's/^CapEff:\t//' | grep ^0000000002000000$")
  2358. }
  2359. // run create container failed should clean up the container
  2360. func (s *DockerSuite) TestRunCreateContainerFailedCleanUp(c *check.C) {
  2361. name := "unique_name"
  2362. _, _, err := dockerCmdWithError("run", "--name", name, "--link", "nothing:nothing", "busybox")
  2363. c.Assert(err, check.Not(check.IsNil), check.Commentf("Expected docker run to fail!"))
  2364. containerID, err := inspectField(name, "Id")
  2365. c.Assert(containerID, check.Equals, "", check.Commentf("Expected not to have this container: %s!", containerID))
  2366. }