docker_cli_run_test.go 104 KB

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