docker_cli_run_test.go 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128
  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", "--dns-opt=ndots:9", "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 options ndots:9" {
  810. c.Fatalf("expected 'search mydomain nameserver 127.0.0.1 options ndots:9', but says: %q", actual)
  811. }
  812. out, stderr, _ = dockerCmdWithStdoutStderr(c, "run", "--dns=127.0.0.1", "--dns-search=.", "--dns-opt=ndots:3", "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 options ndots:3" {
  815. c.Fatalf("expected 'nameserver 127.0.0.1 options ndots:3', but says: %q", actual)
  816. }
  817. }
  818. func (s *DockerSuite) TestRunDnsRepeatOptions(c *check.C) {
  819. testRequires(c, DaemonIsLinux)
  820. out, _, _ := dockerCmdWithStdoutStderr(c, "run", "--dns=1.1.1.1", "--dns=2.2.2.2", "--dns-search=mydomain", "--dns-search=mydomain2", "--dns-opt=ndots:9", "--dns-opt=timeout:3", "busybox", "cat", "/etc/resolv.conf")
  821. actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1)
  822. if actual != "search mydomain mydomain2 nameserver 1.1.1.1 nameserver 2.2.2.2 options ndots:9 timeout:3" {
  823. c.Fatalf("expected 'search mydomain mydomain2 nameserver 1.1.1.1 nameserver 2.2.2.2 options ndots:9 timeout:3', but says: %q", actual)
  824. }
  825. }
  826. func (s *DockerSuite) TestRunDnsOptionsBasedOnHostResolvConf(c *check.C) {
  827. testRequires(c, SameHostDaemon, DaemonIsLinux)
  828. origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  829. if os.IsNotExist(err) {
  830. c.Fatalf("/etc/resolv.conf does not exist")
  831. }
  832. hostNamservers := resolvconf.GetNameservers(origResolvConf)
  833. hostSearch := resolvconf.GetSearchDomains(origResolvConf)
  834. var out string
  835. out, _ = dockerCmd(c, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf")
  836. if actualNameservers := resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "127.0.0.1" {
  837. c.Fatalf("expected '127.0.0.1', but says: %q", string(actualNameservers[0]))
  838. }
  839. actualSearch := resolvconf.GetSearchDomains([]byte(out))
  840. if len(actualSearch) != len(hostSearch) {
  841. c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch))
  842. }
  843. for i := range actualSearch {
  844. if actualSearch[i] != hostSearch[i] {
  845. c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i])
  846. }
  847. }
  848. out, _ = dockerCmd(c, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
  849. actualNameservers := resolvconf.GetNameservers([]byte(out))
  850. if len(actualNameservers) != len(hostNamservers) {
  851. c.Fatalf("expected %q nameserver(s), but it has: %q", len(hostNamservers), len(actualNameservers))
  852. }
  853. for i := range actualNameservers {
  854. if actualNameservers[i] != hostNamservers[i] {
  855. c.Fatalf("expected %q nameserver, but says: %q", actualNameservers[i], hostNamservers[i])
  856. }
  857. }
  858. if actualSearch = resolvconf.GetSearchDomains([]byte(out)); string(actualSearch[0]) != "mydomain" {
  859. c.Fatalf("expected 'mydomain', but says: %q", string(actualSearch[0]))
  860. }
  861. // test with file
  862. tmpResolvConf := []byte("search example.com\nnameserver 12.34.56.78\nnameserver 127.0.0.1")
  863. if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
  864. c.Fatal(err)
  865. }
  866. // put the old resolvconf back
  867. defer func() {
  868. if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil {
  869. c.Fatal(err)
  870. }
  871. }()
  872. resolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  873. if os.IsNotExist(err) {
  874. c.Fatalf("/etc/resolv.conf does not exist")
  875. }
  876. hostNamservers = resolvconf.GetNameservers(resolvConf)
  877. hostSearch = resolvconf.GetSearchDomains(resolvConf)
  878. out, _ = dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf")
  879. if actualNameservers = resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "12.34.56.78" || len(actualNameservers) != 1 {
  880. c.Fatalf("expected '12.34.56.78', but has: %v", actualNameservers)
  881. }
  882. actualSearch = resolvconf.GetSearchDomains([]byte(out))
  883. if len(actualSearch) != len(hostSearch) {
  884. c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch))
  885. }
  886. for i := range actualSearch {
  887. if actualSearch[i] != hostSearch[i] {
  888. c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i])
  889. }
  890. }
  891. }
  892. // Test to see if a non-root user can resolve a DNS name and reach out to it. Also
  893. // check if the container resolv.conf file has at least 0644 perm.
  894. func (s *DockerSuite) TestRunNonRootUserResolvName(c *check.C) {
  895. testRequires(c, SameHostDaemon, Network, DaemonIsLinux)
  896. dockerCmd(c, "run", "--name=testperm", "--user=default", "busybox", "ping", "-c", "1", "apt.dockerproject.org")
  897. cID, err := getIDByName("testperm")
  898. if err != nil {
  899. c.Fatal(err)
  900. }
  901. fmode := (os.FileMode)(0644)
  902. finfo, err := os.Stat(containerStorageFile(cID, "resolv.conf"))
  903. if err != nil {
  904. c.Fatal(err)
  905. }
  906. if (finfo.Mode() & fmode) != fmode {
  907. c.Fatalf("Expected container resolv.conf mode to be at least %s, instead got %s", fmode.String(), finfo.Mode().String())
  908. }
  909. }
  910. // Test if container resolv.conf gets updated the next time it restarts
  911. // if host /etc/resolv.conf has changed. This only applies if the container
  912. // uses the host's /etc/resolv.conf and does not have any dns options provided.
  913. func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) {
  914. testRequires(c, SameHostDaemon, DaemonIsLinux)
  915. tmpResolvConf := []byte("search pommesfrites.fr\nnameserver 12.34.56.78\n")
  916. tmpLocalhostResolvConf := []byte("nameserver 127.0.0.1")
  917. //take a copy of resolv.conf for restoring after test completes
  918. resolvConfSystem, err := ioutil.ReadFile("/etc/resolv.conf")
  919. if err != nil {
  920. c.Fatal(err)
  921. }
  922. // This test case is meant to test monitoring resolv.conf when it is
  923. // a regular file not a bind mounc. So we unmount resolv.conf and replace
  924. // it with a file containing the original settings.
  925. cmd := exec.Command("umount", "/etc/resolv.conf")
  926. if _, err = runCommand(cmd); err != nil {
  927. c.Fatal(err)
  928. }
  929. //cleanup
  930. defer func() {
  931. if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  932. c.Fatal(err)
  933. }
  934. }()
  935. //1. test that a restarting container gets an updated resolv.conf
  936. dockerCmd(c, "run", "--name='first'", "busybox", "true")
  937. containerID1, err := getIDByName("first")
  938. if err != nil {
  939. c.Fatal(err)
  940. }
  941. // replace resolv.conf with our temporary copy
  942. bytesResolvConf := []byte(tmpResolvConf)
  943. if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  944. c.Fatal(err)
  945. }
  946. // start the container again to pickup changes
  947. dockerCmd(c, "start", "first")
  948. // check for update in container
  949. containerResolv, err := readContainerFile(containerID1, "resolv.conf")
  950. if err != nil {
  951. c.Fatal(err)
  952. }
  953. if !bytes.Equal(containerResolv, bytesResolvConf) {
  954. c.Fatalf("Restarted container does not have updated resolv.conf; expected %q, got %q", tmpResolvConf, string(containerResolv))
  955. }
  956. /* //make a change to resolv.conf (in this case replacing our tmp copy with orig copy)
  957. if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  958. c.Fatal(err)
  959. } */
  960. //2. test that a restarting container does not receive resolv.conf updates
  961. // if it modified the container copy of the starting point resolv.conf
  962. dockerCmd(c, "run", "--name='second'", "busybox", "sh", "-c", "echo 'search mylittlepony.com' >>/etc/resolv.conf")
  963. containerID2, err := getIDByName("second")
  964. if err != nil {
  965. c.Fatal(err)
  966. }
  967. //make a change to resolv.conf (in this case replacing our tmp copy with orig copy)
  968. if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  969. c.Fatal(err)
  970. }
  971. // start the container again
  972. dockerCmd(c, "start", "second")
  973. // check for update in container
  974. containerResolv, err = readContainerFile(containerID2, "resolv.conf")
  975. if err != nil {
  976. c.Fatal(err)
  977. }
  978. if bytes.Equal(containerResolv, resolvConfSystem) {
  979. c.Fatalf("Restarting a container after container updated resolv.conf should not pick up host changes; expected %q, got %q", string(containerResolv), string(resolvConfSystem))
  980. }
  981. //3. test that a running container's resolv.conf is not modified while running
  982. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  983. runningContainerID := strings.TrimSpace(out)
  984. // replace resolv.conf
  985. if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  986. c.Fatal(err)
  987. }
  988. // check for update in container
  989. containerResolv, err = readContainerFile(runningContainerID, "resolv.conf")
  990. if err != nil {
  991. c.Fatal(err)
  992. }
  993. if bytes.Equal(containerResolv, bytesResolvConf) {
  994. c.Fatalf("Running container should not have updated resolv.conf; expected %q, got %q", string(resolvConfSystem), string(containerResolv))
  995. }
  996. //4. test that a running container's resolv.conf is updated upon restart
  997. // (the above container is still running..)
  998. dockerCmd(c, "restart", runningContainerID)
  999. // check for update in container
  1000. containerResolv, err = readContainerFile(runningContainerID, "resolv.conf")
  1001. if err != nil {
  1002. c.Fatal(err)
  1003. }
  1004. if !bytes.Equal(containerResolv, bytesResolvConf) {
  1005. c.Fatalf("Restarted container should have updated resolv.conf; expected %q, got %q", string(bytesResolvConf), string(containerResolv))
  1006. }
  1007. //5. test that additions of a localhost resolver are cleaned from
  1008. // host resolv.conf before updating container's resolv.conf copies
  1009. // replace resolv.conf with a localhost-only nameserver copy
  1010. bytesResolvConf = []byte(tmpLocalhostResolvConf)
  1011. if err = ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  1012. c.Fatal(err)
  1013. }
  1014. // start the container again to pickup changes
  1015. dockerCmd(c, "start", "first")
  1016. // our first exited container ID should have been updated, but with default DNS
  1017. // after the cleanup of resolv.conf found only a localhost nameserver:
  1018. containerResolv, err = readContainerFile(containerID1, "resolv.conf")
  1019. if err != nil {
  1020. c.Fatal(err)
  1021. }
  1022. expected := "\nnameserver 8.8.8.8\nnameserver 8.8.4.4\n"
  1023. if !bytes.Equal(containerResolv, []byte(expected)) {
  1024. c.Fatalf("Container does not have cleaned/replaced DNS in resolv.conf; expected %q, got %q", expected, string(containerResolv))
  1025. }
  1026. //6. Test that replacing (as opposed to modifying) resolv.conf triggers an update
  1027. // of containers' resolv.conf.
  1028. // Restore the original resolv.conf
  1029. if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1030. c.Fatal(err)
  1031. }
  1032. // Run the container so it picks up the old settings
  1033. dockerCmd(c, "run", "--name='third'", "busybox", "true")
  1034. containerID3, err := getIDByName("third")
  1035. if err != nil {
  1036. c.Fatal(err)
  1037. }
  1038. // Create a modified resolv.conf.aside and override resolv.conf with it
  1039. bytesResolvConf = []byte(tmpResolvConf)
  1040. if err := ioutil.WriteFile("/etc/resolv.conf.aside", bytesResolvConf, 0644); err != nil {
  1041. c.Fatal(err)
  1042. }
  1043. err = os.Rename("/etc/resolv.conf.aside", "/etc/resolv.conf")
  1044. if err != nil {
  1045. c.Fatal(err)
  1046. }
  1047. // start the container again to pickup changes
  1048. dockerCmd(c, "start", "third")
  1049. // check for update in container
  1050. containerResolv, err = readContainerFile(containerID3, "resolv.conf")
  1051. if err != nil {
  1052. c.Fatal(err)
  1053. }
  1054. if !bytes.Equal(containerResolv, bytesResolvConf) {
  1055. c.Fatalf("Stopped container does not have updated resolv.conf; expected\n%q\n got\n%q", tmpResolvConf, string(containerResolv))
  1056. }
  1057. //cleanup, restore original resolv.conf happens in defer func()
  1058. }
  1059. func (s *DockerSuite) TestRunAddHost(c *check.C) {
  1060. testRequires(c, DaemonIsLinux)
  1061. out, _ := dockerCmd(c, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts")
  1062. actual := strings.Trim(out, "\r\n")
  1063. if actual != "86.75.30.9\textra" {
  1064. c.Fatalf("expected '86.75.30.9\textra', but says: %q", actual)
  1065. }
  1066. }
  1067. // Regression test for #6983
  1068. func (s *DockerSuite) TestRunAttachStdErrOnlyTTYMode(c *check.C) {
  1069. testRequires(c, DaemonIsLinux)
  1070. _, exitCode := dockerCmd(c, "run", "-t", "-a", "stderr", "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) TestRunAttachStdOutOnlyTTYMode(c *check.C) {
  1077. testRequires(c, DaemonIsLinux)
  1078. _, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "busybox", "true")
  1079. if exitCode != 0 {
  1080. c.Fatalf("Container should have exited with error code 0")
  1081. }
  1082. }
  1083. // Regression test for #6983
  1084. func (s *DockerSuite) TestRunAttachStdOutAndErrTTYMode(c *check.C) {
  1085. testRequires(c, DaemonIsLinux)
  1086. _, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true")
  1087. if exitCode != 0 {
  1088. c.Fatalf("Container should have exited with error code 0")
  1089. }
  1090. }
  1091. // Test for #10388 - this will run the same test as TestRunAttachStdOutAndErrTTYMode
  1092. // but using --attach instead of -a to make sure we read the flag correctly
  1093. func (s *DockerSuite) TestRunAttachWithDetach(c *check.C) {
  1094. testRequires(c, DaemonIsLinux)
  1095. cmd := exec.Command(dockerBinary, "run", "-d", "--attach", "stdout", "busybox", "true")
  1096. _, stderr, _, err := runCommandWithStdoutStderr(cmd)
  1097. if err == nil {
  1098. c.Fatal("Container should have exited with error code different than 0")
  1099. } else if !strings.Contains(stderr, "Conflicting options: -a and -d") {
  1100. c.Fatal("Should have been returned an error with conflicting options -a and -d")
  1101. }
  1102. }
  1103. func (s *DockerSuite) TestRunState(c *check.C) {
  1104. testRequires(c, DaemonIsLinux)
  1105. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1106. id := strings.TrimSpace(out)
  1107. state, err := inspectField(id, "State.Running")
  1108. c.Assert(err, check.IsNil)
  1109. if state != "true" {
  1110. c.Fatal("Container state is 'not running'")
  1111. }
  1112. pid1, err := inspectField(id, "State.Pid")
  1113. c.Assert(err, check.IsNil)
  1114. if pid1 == "0" {
  1115. c.Fatal("Container state Pid 0")
  1116. }
  1117. dockerCmd(c, "stop", id)
  1118. state, err = inspectField(id, "State.Running")
  1119. c.Assert(err, check.IsNil)
  1120. if state != "false" {
  1121. c.Fatal("Container state is 'running'")
  1122. }
  1123. pid2, err := inspectField(id, "State.Pid")
  1124. c.Assert(err, check.IsNil)
  1125. if pid2 == pid1 {
  1126. c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1127. }
  1128. dockerCmd(c, "start", id)
  1129. state, err = inspectField(id, "State.Running")
  1130. c.Assert(err, check.IsNil)
  1131. if state != "true" {
  1132. c.Fatal("Container state is 'not running'")
  1133. }
  1134. pid3, err := inspectField(id, "State.Pid")
  1135. c.Assert(err, check.IsNil)
  1136. if pid3 == pid1 {
  1137. c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1138. }
  1139. }
  1140. // Test for #1737
  1141. func (s *DockerSuite) TestRunCopyVolumeUidGid(c *check.C) {
  1142. testRequires(c, DaemonIsLinux)
  1143. name := "testrunvolumesuidgid"
  1144. _, err := buildImage(name,
  1145. `FROM busybox
  1146. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1147. RUN echo 'dockerio:x:1001:' >> /etc/group
  1148. RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`,
  1149. true)
  1150. if err != nil {
  1151. c.Fatal(err)
  1152. }
  1153. // Test that the uid and gid is copied from the image to the volume
  1154. out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'")
  1155. out = strings.TrimSpace(out)
  1156. if out != "dockerio:dockerio" {
  1157. c.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out)
  1158. }
  1159. }
  1160. // Test for #1582
  1161. func (s *DockerSuite) TestRunCopyVolumeContent(c *check.C) {
  1162. testRequires(c, DaemonIsLinux)
  1163. name := "testruncopyvolumecontent"
  1164. _, err := buildImage(name,
  1165. `FROM busybox
  1166. RUN mkdir -p /hello/local && echo hello > /hello/local/world`,
  1167. true)
  1168. if err != nil {
  1169. c.Fatal(err)
  1170. }
  1171. // Test that the content is copied from the image to the volume
  1172. out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "find", "/hello")
  1173. if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) {
  1174. c.Fatal("Container failed to transfer content to volume")
  1175. }
  1176. }
  1177. func (s *DockerSuite) TestRunCleanupCmdOnEntrypoint(c *check.C) {
  1178. testRequires(c, DaemonIsLinux)
  1179. name := "testrunmdcleanuponentrypoint"
  1180. if _, err := buildImage(name,
  1181. `FROM busybox
  1182. ENTRYPOINT ["echo"]
  1183. CMD ["testingpoint"]`,
  1184. true); err != nil {
  1185. c.Fatal(err)
  1186. }
  1187. out, exit := dockerCmd(c, "run", "--entrypoint", "whoami", name)
  1188. if exit != 0 {
  1189. c.Fatalf("expected exit code 0 received %d, out: %q", exit, out)
  1190. }
  1191. out = strings.TrimSpace(out)
  1192. if out != "root" {
  1193. c.Fatalf("Expected output root, got %q", out)
  1194. }
  1195. }
  1196. // TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected
  1197. func (s *DockerSuite) TestRunWorkdirExistsAndIsFile(c *check.C) {
  1198. testRequires(c, DaemonIsLinux)
  1199. out, exit, err := dockerCmdWithError("run", "-w", "/bin/cat", "busybox")
  1200. if !(err != nil && exit == 1 && strings.Contains(out, "Cannot mkdir: /bin/cat is not a directory")) {
  1201. c.Fatalf("Docker must complains about making dir, but we got out: %s, exit: %d, err: %s", out, exit, err)
  1202. }
  1203. }
  1204. func (s *DockerSuite) TestRunExitOnStdinClose(c *check.C) {
  1205. testRequires(c, DaemonIsLinux)
  1206. name := "testrunexitonstdinclose"
  1207. runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", "/bin/cat")
  1208. stdin, err := runCmd.StdinPipe()
  1209. if err != nil {
  1210. c.Fatal(err)
  1211. }
  1212. stdout, err := runCmd.StdoutPipe()
  1213. if err != nil {
  1214. c.Fatal(err)
  1215. }
  1216. if err := runCmd.Start(); err != nil {
  1217. c.Fatal(err)
  1218. }
  1219. if _, err := stdin.Write([]byte("hello\n")); err != nil {
  1220. c.Fatal(err)
  1221. }
  1222. r := bufio.NewReader(stdout)
  1223. line, err := r.ReadString('\n')
  1224. if err != nil {
  1225. c.Fatal(err)
  1226. }
  1227. line = strings.TrimSpace(line)
  1228. if line != "hello" {
  1229. c.Fatalf("Output should be 'hello', got '%q'", line)
  1230. }
  1231. if err := stdin.Close(); err != nil {
  1232. c.Fatal(err)
  1233. }
  1234. finish := make(chan error)
  1235. go func() {
  1236. finish <- runCmd.Wait()
  1237. close(finish)
  1238. }()
  1239. select {
  1240. case err := <-finish:
  1241. c.Assert(err, check.IsNil)
  1242. case <-time.After(1 * time.Second):
  1243. c.Fatal("docker run failed to exit on stdin close")
  1244. }
  1245. state, err := inspectField(name, "State.Running")
  1246. c.Assert(err, check.IsNil)
  1247. if state != "false" {
  1248. c.Fatal("Container must be stopped after stdin closing")
  1249. }
  1250. }
  1251. // Test for #2267
  1252. func (s *DockerSuite) TestRunWriteHostsFileAndNotCommit(c *check.C) {
  1253. testRequires(c, DaemonIsLinux)
  1254. name := "writehosts"
  1255. out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hosts && cat /etc/hosts")
  1256. if !strings.Contains(out, "test2267") {
  1257. c.Fatal("/etc/hosts should contain 'test2267'")
  1258. }
  1259. out, _ = dockerCmd(c, "diff", name)
  1260. if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1261. c.Fatal("diff should be empty")
  1262. }
  1263. }
  1264. func eqToBaseDiff(out string, c *check.C) bool {
  1265. out1, _ := dockerCmd(c, "run", "-d", "busybox", "echo", "hello")
  1266. cID := strings.TrimSpace(out1)
  1267. baseDiff, _ := dockerCmd(c, "diff", cID)
  1268. baseArr := strings.Split(baseDiff, "\n")
  1269. sort.Strings(baseArr)
  1270. outArr := strings.Split(out, "\n")
  1271. sort.Strings(outArr)
  1272. return sliceEq(baseArr, outArr)
  1273. }
  1274. func sliceEq(a, b []string) bool {
  1275. if len(a) != len(b) {
  1276. return false
  1277. }
  1278. for i := range a {
  1279. if a[i] != b[i] {
  1280. return false
  1281. }
  1282. }
  1283. return true
  1284. }
  1285. // Test for #2267
  1286. func (s *DockerSuite) TestRunWriteHostnameFileAndNotCommit(c *check.C) {
  1287. testRequires(c, DaemonIsLinux)
  1288. name := "writehostname"
  1289. out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hostname && cat /etc/hostname")
  1290. if !strings.Contains(out, "test2267") {
  1291. c.Fatal("/etc/hostname should contain 'test2267'")
  1292. }
  1293. out, _ = dockerCmd(c, "diff", name)
  1294. if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1295. c.Fatal("diff should be empty")
  1296. }
  1297. }
  1298. // Test for #2267
  1299. func (s *DockerSuite) TestRunWriteResolvFileAndNotCommit(c *check.C) {
  1300. testRequires(c, DaemonIsLinux)
  1301. name := "writeresolv"
  1302. out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/resolv.conf && cat /etc/resolv.conf")
  1303. if !strings.Contains(out, "test2267") {
  1304. c.Fatal("/etc/resolv.conf should contain 'test2267'")
  1305. }
  1306. out, _ = dockerCmd(c, "diff", name)
  1307. if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1308. c.Fatal("diff should be empty")
  1309. }
  1310. }
  1311. func (s *DockerSuite) TestRunWithBadDevice(c *check.C) {
  1312. testRequires(c, DaemonIsLinux)
  1313. name := "baddevice"
  1314. out, _, err := dockerCmdWithError("run", "--name", name, "--device", "/etc", "busybox", "true")
  1315. if err == nil {
  1316. c.Fatal("Run should fail with bad device")
  1317. }
  1318. expected := `"/etc": not a device node`
  1319. if !strings.Contains(out, expected) {
  1320. c.Fatalf("Output should contain %q, actual out: %q", expected, out)
  1321. }
  1322. }
  1323. func (s *DockerSuite) TestRunEntrypoint(c *check.C) {
  1324. testRequires(c, DaemonIsLinux)
  1325. name := "entrypoint"
  1326. out, _ := dockerCmd(c, "run", "--name", name, "--entrypoint", "/bin/echo", "busybox", "-n", "foobar")
  1327. expected := "foobar"
  1328. if out != expected {
  1329. c.Fatalf("Output should be %q, actual out: %q", expected, out)
  1330. }
  1331. }
  1332. func (s *DockerSuite) TestRunBindMounts(c *check.C) {
  1333. testRequires(c, DaemonIsLinux)
  1334. testRequires(c, SameHostDaemon)
  1335. tmpDir, err := ioutil.TempDir("", "docker-test-container")
  1336. if err != nil {
  1337. c.Fatal(err)
  1338. }
  1339. defer os.RemoveAll(tmpDir)
  1340. writeFile(path.Join(tmpDir, "touch-me"), "", c)
  1341. // Test reading from a read-only bind mount
  1342. out, _ := dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox", "ls", "/tmp")
  1343. if !strings.Contains(out, "touch-me") {
  1344. c.Fatal("Container failed to read from bind mount")
  1345. }
  1346. // test writing to bind mount
  1347. dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla")
  1348. readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist
  1349. // test mounting to an illegal destination directory
  1350. _, _, err = dockerCmdWithError("run", "-v", fmt.Sprintf("%s:.", tmpDir), "busybox", "ls", ".")
  1351. if err == nil {
  1352. c.Fatal("Container bind mounted illegal directory")
  1353. }
  1354. // test mount a file
  1355. dockerCmd(c, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla")
  1356. content := readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist
  1357. expected := "yotta"
  1358. if content != expected {
  1359. c.Fatalf("Output should be %q, actual out: %q", expected, content)
  1360. }
  1361. }
  1362. // Ensure that CIDFile gets deleted if it's empty
  1363. // Perform this test by making `docker run` fail
  1364. func (s *DockerSuite) TestRunCidFileCleanupIfEmpty(c *check.C) {
  1365. testRequires(c, DaemonIsLinux)
  1366. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1367. if err != nil {
  1368. c.Fatal(err)
  1369. }
  1370. defer os.RemoveAll(tmpDir)
  1371. tmpCidFile := path.Join(tmpDir, "cid")
  1372. out, _, err := dockerCmdWithError("run", "--cidfile", tmpCidFile, "emptyfs")
  1373. if err == nil {
  1374. c.Fatalf("Run without command must fail. out=%s", out)
  1375. } else if !strings.Contains(out, "No command specified") {
  1376. c.Fatalf("Run without command failed with wrong output. out=%s\nerr=%v", out, err)
  1377. }
  1378. if _, err := os.Stat(tmpCidFile); err == nil {
  1379. c.Fatalf("empty CIDFile %q should've been deleted", tmpCidFile)
  1380. }
  1381. }
  1382. // #2098 - Docker cidFiles only contain short version of the containerId
  1383. //sudo docker run --cidfile /tmp/docker_tesc.cid ubuntu echo "test"
  1384. // TestRunCidFile tests that run --cidfile returns the longid
  1385. func (s *DockerSuite) TestRunCidFileCheckIDLength(c *check.C) {
  1386. testRequires(c, DaemonIsLinux)
  1387. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1388. if err != nil {
  1389. c.Fatal(err)
  1390. }
  1391. tmpCidFile := path.Join(tmpDir, "cid")
  1392. defer os.RemoveAll(tmpDir)
  1393. out, _ := dockerCmd(c, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true")
  1394. id := strings.TrimSpace(out)
  1395. buffer, err := ioutil.ReadFile(tmpCidFile)
  1396. if err != nil {
  1397. c.Fatal(err)
  1398. }
  1399. cid := string(buffer)
  1400. if len(cid) != 64 {
  1401. c.Fatalf("--cidfile should be a long id, not %q", id)
  1402. }
  1403. if cid != id {
  1404. c.Fatalf("cid must be equal to %s, got %s", id, cid)
  1405. }
  1406. }
  1407. func (s *DockerSuite) TestRunSetMacAddress(c *check.C) {
  1408. testRequires(c, DaemonIsLinux)
  1409. mac := "12:34:56:78:9a:bc"
  1410. 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}'")
  1411. actualMac := strings.TrimSpace(out)
  1412. if actualMac != mac {
  1413. c.Fatalf("Set MAC address with --mac-address failed. The container has an incorrect MAC address: %q, expected: %q", actualMac, mac)
  1414. }
  1415. }
  1416. func (s *DockerSuite) TestRunInspectMacAddress(c *check.C) {
  1417. testRequires(c, DaemonIsLinux)
  1418. mac := "12:34:56:78:9a:bc"
  1419. out, _ := dockerCmd(c, "run", "-d", "--mac-address="+mac, "busybox", "top")
  1420. id := strings.TrimSpace(out)
  1421. inspectedMac, err := inspectField(id, "NetworkSettings.MacAddress")
  1422. c.Assert(err, check.IsNil)
  1423. if inspectedMac != mac {
  1424. c.Fatalf("docker inspect outputs wrong MAC address: %q, should be: %q", inspectedMac, mac)
  1425. }
  1426. }
  1427. // test docker run use a invalid mac address
  1428. func (s *DockerSuite) TestRunWithInvalidMacAddress(c *check.C) {
  1429. testRequires(c, DaemonIsLinux)
  1430. out, _, err := dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29", "busybox")
  1431. //use a invalid mac address should with a error out
  1432. if err == nil || !strings.Contains(out, "is not a valid mac address") {
  1433. c.Fatalf("run with an invalid --mac-address should with error out")
  1434. }
  1435. }
  1436. func (s *DockerSuite) TestRunDeallocatePortOnMissingIptablesRule(c *check.C) {
  1437. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1438. out, _ := dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top")
  1439. id := strings.TrimSpace(out)
  1440. ip, err := inspectField(id, "NetworkSettings.IPAddress")
  1441. c.Assert(err, check.IsNil)
  1442. iptCmd := exec.Command("iptables", "-D", "DOCKER", "-d", fmt.Sprintf("%s/32", ip),
  1443. "!", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-m", "tcp", "--dport", "23", "-j", "ACCEPT")
  1444. out, _, err = runCommandWithOutput(iptCmd)
  1445. if err != nil {
  1446. c.Fatal(err, out)
  1447. }
  1448. if err := deleteContainer(id); err != nil {
  1449. c.Fatal(err)
  1450. }
  1451. dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top")
  1452. }
  1453. func (s *DockerSuite) TestRunPortInUse(c *check.C) {
  1454. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1455. port := "1234"
  1456. dockerCmd(c, "run", "-d", "-p", port+":80", "busybox", "top")
  1457. out, _, err := dockerCmdWithError("run", "-d", "-p", port+":80", "busybox", "top")
  1458. if err == nil {
  1459. c.Fatalf("Binding on used port must fail")
  1460. }
  1461. if !strings.Contains(out, "port is already allocated") {
  1462. c.Fatalf("Out must be about \"port is already allocated\", got %s", out)
  1463. }
  1464. }
  1465. // https://github.com/docker/docker/issues/12148
  1466. func (s *DockerSuite) TestRunAllocatePortInReservedRange(c *check.C) {
  1467. testRequires(c, DaemonIsLinux)
  1468. // allocate a dynamic port to get the most recent
  1469. out, _ := dockerCmd(c, "run", "-d", "-P", "-p", "80", "busybox", "top")
  1470. id := strings.TrimSpace(out)
  1471. out, _ = dockerCmd(c, "port", id, "80")
  1472. strPort := strings.Split(strings.TrimSpace(out), ":")[1]
  1473. port, err := strconv.ParseInt(strPort, 10, 64)
  1474. if err != nil {
  1475. c.Fatalf("invalid port, got: %s, error: %s", strPort, err)
  1476. }
  1477. // allocate a static port and a dynamic port together, with static port
  1478. // takes the next recent port in dynamic port range.
  1479. dockerCmd(c, "run", "-d", "-P", "-p", "80", "-p", fmt.Sprintf("%d:8080", port+1), "busybox", "top")
  1480. }
  1481. // Regression test for #7792
  1482. func (s *DockerSuite) TestRunMountOrdering(c *check.C) {
  1483. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1484. tmpDir, err := ioutil.TempDir("", "docker_nested_mount_test")
  1485. if err != nil {
  1486. c.Fatal(err)
  1487. }
  1488. defer os.RemoveAll(tmpDir)
  1489. tmpDir2, err := ioutil.TempDir("", "docker_nested_mount_test2")
  1490. if err != nil {
  1491. c.Fatal(err)
  1492. }
  1493. defer os.RemoveAll(tmpDir2)
  1494. // Create a temporary tmpfs mounc.
  1495. fooDir := filepath.Join(tmpDir, "foo")
  1496. if err := os.MkdirAll(filepath.Join(tmpDir, "foo"), 0755); err != nil {
  1497. c.Fatalf("failed to mkdir at %s - %s", fooDir, err)
  1498. }
  1499. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", fooDir), []byte{}, 0644); err != nil {
  1500. c.Fatal(err)
  1501. }
  1502. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir), []byte{}, 0644); err != nil {
  1503. c.Fatal(err)
  1504. }
  1505. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir2), []byte{}, 0644); err != nil {
  1506. c.Fatal(err)
  1507. }
  1508. dockerCmd(c, "run",
  1509. "-v", fmt.Sprintf("%s:/tmp", tmpDir),
  1510. "-v", fmt.Sprintf("%s:/tmp/foo", fooDir),
  1511. "-v", fmt.Sprintf("%s:/tmp/tmp2", tmpDir2),
  1512. "-v", fmt.Sprintf("%s:/tmp/tmp2/foo", fooDir),
  1513. "busybox:latest", "sh", "-c",
  1514. "ls /tmp/touch-me && ls /tmp/foo/touch-me && ls /tmp/tmp2/touch-me && ls /tmp/tmp2/foo/touch-me")
  1515. }
  1516. // Regression test for https://github.com/docker/docker/issues/8259
  1517. func (s *DockerSuite) TestRunReuseBindVolumeThatIsSymlink(c *check.C) {
  1518. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1519. tmpDir, err := ioutil.TempDir(os.TempDir(), "testlink")
  1520. if err != nil {
  1521. c.Fatal(err)
  1522. }
  1523. defer os.RemoveAll(tmpDir)
  1524. linkPath := os.TempDir() + "/testlink2"
  1525. if err := os.Symlink(tmpDir, linkPath); err != nil {
  1526. c.Fatal(err)
  1527. }
  1528. defer os.RemoveAll(linkPath)
  1529. // Create first container
  1530. dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
  1531. // Create second container with same symlinked path
  1532. // This will fail if the referenced issue is hit with a "Volume exists" error
  1533. dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
  1534. }
  1535. //GH#10604: Test an "/etc" volume doesn't overlay special bind mounts in container
  1536. func (s *DockerSuite) TestRunCreateVolumeEtc(c *check.C) {
  1537. testRequires(c, DaemonIsLinux)
  1538. out, _ := dockerCmd(c, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf")
  1539. if !strings.Contains(out, "nameserver 127.0.0.1") {
  1540. c.Fatal("/etc volume mount hides /etc/resolv.conf")
  1541. }
  1542. out, _ = dockerCmd(c, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname")
  1543. if !strings.Contains(out, "test123") {
  1544. c.Fatal("/etc volume mount hides /etc/hostname")
  1545. }
  1546. out, _ = dockerCmd(c, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts")
  1547. out = strings.Replace(out, "\n", " ", -1)
  1548. if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") {
  1549. c.Fatal("/etc volume mount hides /etc/hosts")
  1550. }
  1551. }
  1552. func (s *DockerSuite) TestVolumesNoCopyData(c *check.C) {
  1553. testRequires(c, DaemonIsLinux)
  1554. if _, err := buildImage("dataimage",
  1555. `FROM busybox
  1556. RUN mkdir -p /foo
  1557. RUN touch /foo/bar`,
  1558. true); err != nil {
  1559. c.Fatal(err)
  1560. }
  1561. dockerCmd(c, "run", "--name", "test", "-v", "/foo", "busybox")
  1562. if out, _, err := dockerCmdWithError("run", "--volumes-from", "test", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") {
  1563. c.Fatalf("Data was copied on volumes-from but shouldn't be:\n%q", out)
  1564. }
  1565. tmpDir := randomUnixTmpDirPath("docker_test_bind_mount_copy_data")
  1566. if out, _, err := dockerCmdWithError("run", "-v", tmpDir+":/foo", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") {
  1567. c.Fatalf("Data was copied on bind-mount but shouldn't be:\n%q", out)
  1568. }
  1569. }
  1570. func (s *DockerSuite) TestRunNoOutputFromPullInStdout(c *check.C) {
  1571. // just run with unknown image
  1572. cmd := exec.Command(dockerBinary, "run", "asdfsg")
  1573. stdout := bytes.NewBuffer(nil)
  1574. cmd.Stdout = stdout
  1575. if err := cmd.Run(); err == nil {
  1576. c.Fatal("Run with unknown image should fail")
  1577. }
  1578. if stdout.Len() != 0 {
  1579. c.Fatalf("Stdout contains output from pull: %s", stdout)
  1580. }
  1581. }
  1582. func (s *DockerSuite) TestRunVolumesCleanPaths(c *check.C) {
  1583. testRequires(c, DaemonIsLinux)
  1584. if _, err := buildImage("run_volumes_clean_paths",
  1585. `FROM busybox
  1586. VOLUME /foo/`,
  1587. true); err != nil {
  1588. c.Fatal(err)
  1589. }
  1590. dockerCmd(c, "run", "-v", "/foo", "-v", "/bar/", "--name", "dark_helmet", "run_volumes_clean_paths")
  1591. out, err := inspectMountSourceField("dark_helmet", "/foo/")
  1592. if err != errMountNotFound {
  1593. c.Fatalf("Found unexpected volume entry for '/foo/' in volumes\n%q", out)
  1594. }
  1595. out, err = inspectMountSourceField("dark_helmet", "/foo")
  1596. c.Assert(err, check.IsNil)
  1597. if !strings.Contains(out, volumesConfigPath) {
  1598. c.Fatalf("Volume was not defined for /foo\n%q", out)
  1599. }
  1600. out, err = inspectMountSourceField("dark_helmet", "/bar/")
  1601. if err != errMountNotFound {
  1602. c.Fatalf("Found unexpected volume entry for '/bar/' in volumes\n%q", out)
  1603. }
  1604. out, err = inspectMountSourceField("dark_helmet", "/bar")
  1605. c.Assert(err, check.IsNil)
  1606. if !strings.Contains(out, volumesConfigPath) {
  1607. c.Fatalf("Volume was not defined for /bar\n%q", out)
  1608. }
  1609. }
  1610. // Regression test for #3631
  1611. func (s *DockerSuite) TestRunSlowStdoutConsumer(c *check.C) {
  1612. testRequires(c, DaemonIsLinux)
  1613. cont := exec.Command(dockerBinary, "run", "--rm", "busybox", "/bin/sh", "-c", "dd if=/dev/zero of=/dev/stdout bs=1024 count=2000 | catv")
  1614. stdout, err := cont.StdoutPipe()
  1615. if err != nil {
  1616. c.Fatal(err)
  1617. }
  1618. if err := cont.Start(); err != nil {
  1619. c.Fatal(err)
  1620. }
  1621. n, err := consumeWithSpeed(stdout, 10000, 5*time.Millisecond, nil)
  1622. if err != nil {
  1623. c.Fatal(err)
  1624. }
  1625. expected := 2 * 1024 * 2000
  1626. if n != expected {
  1627. c.Fatalf("Expected %d, got %d", expected, n)
  1628. }
  1629. }
  1630. func (s *DockerSuite) TestRunAllowPortRangeThroughExpose(c *check.C) {
  1631. testRequires(c, DaemonIsLinux)
  1632. out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top")
  1633. id := strings.TrimSpace(out)
  1634. portstr, err := inspectFieldJSON(id, "NetworkSettings.Ports")
  1635. c.Assert(err, check.IsNil)
  1636. var ports nat.PortMap
  1637. if err = unmarshalJSON([]byte(portstr), &ports); err != nil {
  1638. c.Fatal(err)
  1639. }
  1640. for port, binding := range ports {
  1641. portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  1642. if portnum < 3000 || portnum > 3003 {
  1643. c.Fatalf("Port %d is out of range ", portnum)
  1644. }
  1645. if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  1646. c.Fatalf("Port is not mapped for the port %s", port)
  1647. }
  1648. }
  1649. }
  1650. // test docker run expose a invalid port
  1651. func (s *DockerSuite) TestRunExposePort(c *check.C) {
  1652. testRequires(c, DaemonIsLinux)
  1653. out, _, err := dockerCmdWithError("run", "--expose", "80000", "busybox")
  1654. //expose a invalid port should with a error out
  1655. if err == nil || !strings.Contains(out, "Invalid range format for --expose") {
  1656. c.Fatalf("run --expose a invalid port should with error out")
  1657. }
  1658. }
  1659. func (s *DockerSuite) TestRunUnknownCommand(c *check.C) {
  1660. testRequires(c, NativeExecDriver, DaemonIsLinux)
  1661. out, _, _ := dockerCmdWithStdoutStderr(c, "create", "busybox", "/bin/nada")
  1662. cID := strings.TrimSpace(out)
  1663. _, _, err := dockerCmdWithError("start", cID)
  1664. c.Assert(err, check.NotNil)
  1665. rc, err := inspectField(cID, "State.ExitCode")
  1666. c.Assert(err, check.IsNil)
  1667. if rc == "0" {
  1668. c.Fatalf("ExitCode(%v) cannot be 0", rc)
  1669. }
  1670. }
  1671. func (s *DockerSuite) TestRunModeIpcHost(c *check.C) {
  1672. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1673. hostIpc, err := os.Readlink("/proc/1/ns/ipc")
  1674. if err != nil {
  1675. c.Fatal(err)
  1676. }
  1677. out, _ := dockerCmd(c, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc")
  1678. out = strings.Trim(out, "\n")
  1679. if hostIpc != out {
  1680. c.Fatalf("IPC different with --ipc=host %s != %s\n", hostIpc, out)
  1681. }
  1682. out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/ipc")
  1683. out = strings.Trim(out, "\n")
  1684. if hostIpc == out {
  1685. c.Fatalf("IPC should be different without --ipc=host %s == %s\n", hostIpc, out)
  1686. }
  1687. }
  1688. func (s *DockerSuite) TestRunModeIpcContainer(c *check.C) {
  1689. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1690. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1691. id := strings.TrimSpace(out)
  1692. state, err := inspectField(id, "State.Running")
  1693. c.Assert(err, check.IsNil)
  1694. if state != "true" {
  1695. c.Fatal("Container state is 'not running'")
  1696. }
  1697. pid1, err := inspectField(id, "State.Pid")
  1698. c.Assert(err, check.IsNil)
  1699. parentContainerIpc, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/ipc", pid1))
  1700. if err != nil {
  1701. c.Fatal(err)
  1702. }
  1703. out, _ = dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "readlink", "/proc/self/ns/ipc")
  1704. out = strings.Trim(out, "\n")
  1705. if parentContainerIpc != out {
  1706. c.Fatalf("IPC different with --ipc=container:%s %s != %s\n", id, parentContainerIpc, out)
  1707. }
  1708. }
  1709. func (s *DockerSuite) TestRunModeIpcContainerNotExists(c *check.C) {
  1710. testRequires(c, DaemonIsLinux)
  1711. out, _, err := dockerCmdWithError("run", "-d", "--ipc", "container:abcd1234", "busybox", "top")
  1712. if !strings.Contains(out, "abcd1234") || err == nil {
  1713. c.Fatalf("run IPC from a non exists container should with correct error out")
  1714. }
  1715. }
  1716. func (s *DockerSuite) TestRunModeIpcContainerNotRunning(c *check.C) {
  1717. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1718. out, _ := dockerCmd(c, "create", "busybox")
  1719. id := strings.TrimSpace(out)
  1720. out, _, err := dockerCmdWithError("run", fmt.Sprintf("--ipc=container:%s", id), "busybox")
  1721. if err == nil {
  1722. c.Fatalf("Run container with ipc mode container should fail with non running container: %s\n%s", out, err)
  1723. }
  1724. }
  1725. func (s *DockerSuite) TestContainerNetworkMode(c *check.C) {
  1726. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1727. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1728. id := strings.TrimSpace(out)
  1729. c.Assert(waitRun(id), check.IsNil)
  1730. pid1, err := inspectField(id, "State.Pid")
  1731. c.Assert(err, check.IsNil)
  1732. parentContainerNet, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
  1733. if err != nil {
  1734. c.Fatal(err)
  1735. }
  1736. out, _ = dockerCmd(c, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net")
  1737. out = strings.Trim(out, "\n")
  1738. if parentContainerNet != out {
  1739. c.Fatalf("NET different with --net=container:%s %s != %s\n", id, parentContainerNet, out)
  1740. }
  1741. }
  1742. func (s *DockerSuite) TestRunModePidHost(c *check.C) {
  1743. testRequires(c, NativeExecDriver, SameHostDaemon, DaemonIsLinux)
  1744. hostPid, err := os.Readlink("/proc/1/ns/pid")
  1745. if err != nil {
  1746. c.Fatal(err)
  1747. }
  1748. out, _ := dockerCmd(c, "run", "--pid=host", "busybox", "readlink", "/proc/self/ns/pid")
  1749. out = strings.Trim(out, "\n")
  1750. if hostPid != out {
  1751. c.Fatalf("PID different with --pid=host %s != %s\n", hostPid, out)
  1752. }
  1753. out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/pid")
  1754. out = strings.Trim(out, "\n")
  1755. if hostPid == out {
  1756. c.Fatalf("PID should be different without --pid=host %s == %s\n", hostPid, out)
  1757. }
  1758. }
  1759. func (s *DockerSuite) TestRunModeUTSHost(c *check.C) {
  1760. testRequires(c, NativeExecDriver, SameHostDaemon, DaemonIsLinux)
  1761. hostUTS, err := os.Readlink("/proc/1/ns/uts")
  1762. if err != nil {
  1763. c.Fatal(err)
  1764. }
  1765. out, _ := dockerCmd(c, "run", "--uts=host", "busybox", "readlink", "/proc/self/ns/uts")
  1766. out = strings.Trim(out, "\n")
  1767. if hostUTS != out {
  1768. c.Fatalf("UTS different with --uts=host %s != %s\n", hostUTS, out)
  1769. }
  1770. out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/uts")
  1771. out = strings.Trim(out, "\n")
  1772. if hostUTS == out {
  1773. c.Fatalf("UTS should be different without --uts=host %s == %s\n", hostUTS, out)
  1774. }
  1775. }
  1776. func (s *DockerSuite) TestRunTLSverify(c *check.C) {
  1777. testRequires(c, DaemonIsLinux)
  1778. if out, code, err := dockerCmdWithError("ps"); err != nil || code != 0 {
  1779. c.Fatalf("Should have worked: %v:\n%v", err, out)
  1780. }
  1781. // Regardless of whether we specify true or false we need to
  1782. // test to make sure tls is turned on if --tlsverify is specified at all
  1783. out, code, err := dockerCmdWithError("--tlsverify=false", "ps")
  1784. if err == nil || code == 0 || !strings.Contains(out, "trying to connect") {
  1785. c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err)
  1786. }
  1787. out, code, err = dockerCmdWithError("--tlsverify=true", "ps")
  1788. if err == nil || code == 0 || !strings.Contains(out, "cert") {
  1789. c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err)
  1790. }
  1791. }
  1792. func (s *DockerSuite) TestRunPortFromDockerRangeInUse(c *check.C) {
  1793. testRequires(c, DaemonIsLinux)
  1794. // first find allocator current position
  1795. out, _ := dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
  1796. id := strings.TrimSpace(out)
  1797. out, _ = dockerCmd(c, "port", id)
  1798. out = strings.TrimSpace(out)
  1799. if out == "" {
  1800. c.Fatal("docker port command output is empty")
  1801. }
  1802. out = strings.Split(out, ":")[1]
  1803. lastPort, err := strconv.Atoi(out)
  1804. if err != nil {
  1805. c.Fatal(err)
  1806. }
  1807. port := lastPort + 1
  1808. l, err := net.Listen("tcp", ":"+strconv.Itoa(port))
  1809. if err != nil {
  1810. c.Fatal(err)
  1811. }
  1812. defer l.Close()
  1813. out, _ = dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
  1814. id = strings.TrimSpace(out)
  1815. dockerCmd(c, "port", id)
  1816. }
  1817. func (s *DockerSuite) TestRunTtyWithPipe(c *check.C) {
  1818. testRequires(c, DaemonIsLinux)
  1819. errChan := make(chan error)
  1820. go func() {
  1821. defer close(errChan)
  1822. cmd := exec.Command(dockerBinary, "run", "-ti", "busybox", "true")
  1823. if _, err := cmd.StdinPipe(); err != nil {
  1824. errChan <- err
  1825. return
  1826. }
  1827. expected := "cannot enable tty mode"
  1828. if out, _, err := runCommandWithOutput(cmd); err == nil {
  1829. errChan <- fmt.Errorf("run should have failed")
  1830. return
  1831. } else if !strings.Contains(out, expected) {
  1832. errChan <- fmt.Errorf("run failed with error %q: expected %q", out, expected)
  1833. return
  1834. }
  1835. }()
  1836. select {
  1837. case err := <-errChan:
  1838. c.Assert(err, check.IsNil)
  1839. case <-time.After(3 * time.Second):
  1840. c.Fatal("container is running but should have failed")
  1841. }
  1842. }
  1843. func (s *DockerSuite) TestRunNonLocalMacAddress(c *check.C) {
  1844. testRequires(c, DaemonIsLinux)
  1845. addr := "00:16:3E:08:00:50"
  1846. if out, _ := dockerCmd(c, "run", "--mac-address", addr, "busybox", "ifconfig"); !strings.Contains(out, addr) {
  1847. c.Fatalf("Output should have contained %q: %s", addr, out)
  1848. }
  1849. }
  1850. func (s *DockerSuite) TestRunNetHost(c *check.C) {
  1851. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1852. hostNet, err := os.Readlink("/proc/1/ns/net")
  1853. if err != nil {
  1854. c.Fatal(err)
  1855. }
  1856. out, _ := dockerCmd(c, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net")
  1857. out = strings.Trim(out, "\n")
  1858. if hostNet != out {
  1859. c.Fatalf("Net namespace different with --net=host %s != %s\n", hostNet, out)
  1860. }
  1861. out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/net")
  1862. out = strings.Trim(out, "\n")
  1863. if hostNet == out {
  1864. c.Fatalf("Net namespace should be different without --net=host %s == %s\n", hostNet, out)
  1865. }
  1866. }
  1867. func (s *DockerSuite) TestRunNetHostTwiceSameName(c *check.C) {
  1868. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1869. dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
  1870. dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
  1871. }
  1872. func (s *DockerSuite) TestRunNetContainerWhichHost(c *check.C) {
  1873. testRequires(c, SameHostDaemon, DaemonIsLinux)
  1874. hostNet, err := os.Readlink("/proc/1/ns/net")
  1875. if err != nil {
  1876. c.Fatal(err)
  1877. }
  1878. dockerCmd(c, "run", "-d", "--net=host", "--name=test", "busybox", "top")
  1879. out, _ := dockerCmd(c, "run", "--net=container:test", "busybox", "readlink", "/proc/self/ns/net")
  1880. out = strings.Trim(out, "\n")
  1881. if hostNet != out {
  1882. c.Fatalf("Container should have host network namespace")
  1883. }
  1884. }
  1885. func (s *DockerSuite) TestRunAllowPortRangeThroughPublish(c *check.C) {
  1886. testRequires(c, DaemonIsLinux)
  1887. out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top")
  1888. id := strings.TrimSpace(out)
  1889. portstr, err := inspectFieldJSON(id, "NetworkSettings.Ports")
  1890. c.Assert(err, check.IsNil)
  1891. var ports nat.PortMap
  1892. err = unmarshalJSON([]byte(portstr), &ports)
  1893. for port, binding := range ports {
  1894. portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  1895. if portnum < 3000 || portnum > 3003 {
  1896. c.Fatalf("Port %d is out of range ", portnum)
  1897. }
  1898. if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  1899. c.Fatal("Port is not mapped for the port "+port, out)
  1900. }
  1901. }
  1902. }
  1903. func (s *DockerSuite) TestRunSetDefaultRestartPolicy(c *check.C) {
  1904. testRequires(c, DaemonIsLinux)
  1905. dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")
  1906. out, err := inspectField("test", "HostConfig.RestartPolicy.Name")
  1907. c.Assert(err, check.IsNil)
  1908. if out != "no" {
  1909. c.Fatalf("Set default restart policy failed")
  1910. }
  1911. }
  1912. func (s *DockerSuite) TestRunRestartMaxRetries(c *check.C) {
  1913. testRequires(c, DaemonIsLinux)
  1914. out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false")
  1915. id := strings.TrimSpace(string(out))
  1916. if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", 10); err != nil {
  1917. c.Fatal(err)
  1918. }
  1919. count, err := inspectField(id, "RestartCount")
  1920. c.Assert(err, check.IsNil)
  1921. if count != "3" {
  1922. c.Fatalf("Container was restarted %s times, expected %d", count, 3)
  1923. }
  1924. MaximumRetryCount, err := inspectField(id, "HostConfig.RestartPolicy.MaximumRetryCount")
  1925. c.Assert(err, check.IsNil)
  1926. if MaximumRetryCount != "3" {
  1927. c.Fatalf("Container Maximum Retry Count is %s, expected %s", MaximumRetryCount, "3")
  1928. }
  1929. }
  1930. func (s *DockerSuite) TestRunContainerWithWritableRootfs(c *check.C) {
  1931. testRequires(c, DaemonIsLinux)
  1932. dockerCmd(c, "run", "--rm", "busybox", "touch", "/file")
  1933. }
  1934. func (s *DockerSuite) TestRunContainerWithReadonlyRootfs(c *check.C) {
  1935. testRequires(c, NativeExecDriver, DaemonIsLinux)
  1936. for _, f := range []string{"/file", "/etc/hosts", "/etc/resolv.conf", "/etc/hostname", "/sys/kernel", "/dev/.dont.touch.me"} {
  1937. testReadOnlyFile(f, c)
  1938. }
  1939. }
  1940. func (s *DockerSuite) TestPermissionsPtsReadonlyRootfs(c *check.C) {
  1941. testRequires(c, DaemonIsLinux)
  1942. testRequires(c, NativeExecDriver)
  1943. // Ensure we have not broken writing /dev/pts
  1944. out, status := dockerCmd(c, "run", "--read-only", "--rm", "busybox", "mount")
  1945. if status != 0 {
  1946. c.Fatal("Could not obtain mounts when checking /dev/pts mntpnt.")
  1947. }
  1948. expected := "type devpts (rw,"
  1949. if !strings.Contains(string(out), expected) {
  1950. c.Fatalf("expected output to contain %s but contains %s", expected, out)
  1951. }
  1952. }
  1953. func testReadOnlyFile(filename string, c *check.C) {
  1954. testRequires(c, NativeExecDriver, DaemonIsLinux)
  1955. out, _, err := dockerCmdWithError("run", "--read-only", "--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. out, _, err = dockerCmdWithError("run", "--read-only", "--privileged", "--rm", "busybox", "touch", filename)
  1964. if err == nil {
  1965. c.Fatal("expected container to error on run with read only error")
  1966. }
  1967. expected = "Read-only file system"
  1968. if !strings.Contains(string(out), expected) {
  1969. c.Fatalf("expected output from failure to contain %s but contains %s", expected, out)
  1970. }
  1971. }
  1972. func (s *DockerSuite) TestRunContainerWithReadonlyEtcHostsAndLinkedContainer(c *check.C) {
  1973. testRequires(c, NativeExecDriver, DaemonIsLinux)
  1974. dockerCmd(c, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top")
  1975. out, _ := dockerCmd(c, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts")
  1976. if !strings.Contains(string(out), "testlinked") {
  1977. c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled")
  1978. }
  1979. }
  1980. func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithDnsFlag(c *check.C) {
  1981. testRequires(c, NativeExecDriver, DaemonIsLinux)
  1982. out, _ := dockerCmd(c, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf")
  1983. if !strings.Contains(string(out), "1.1.1.1") {
  1984. c.Fatal("Expected /etc/resolv.conf to be updated even if --read-only enabled and --dns flag used")
  1985. }
  1986. }
  1987. func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithAddHostFlag(c *check.C) {
  1988. testRequires(c, NativeExecDriver, DaemonIsLinux)
  1989. out, _ := dockerCmd(c, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts")
  1990. if !strings.Contains(string(out), "testreadonly") {
  1991. c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled and --add-host flag used")
  1992. }
  1993. }
  1994. func (s *DockerSuite) TestRunVolumesFromRestartAfterRemoved(c *check.C) {
  1995. testRequires(c, DaemonIsLinux)
  1996. dockerCmd(c, "run", "-d", "--name", "voltest", "-v", "/foo", "busybox")
  1997. dockerCmd(c, "run", "-d", "--name", "restarter", "--volumes-from", "voltest", "busybox", "top")
  1998. // Remove the main volume container and restart the consuming container
  1999. dockerCmd(c, "rm", "-f", "voltest")
  2000. // This should not fail since the volumes-from were already applied
  2001. dockerCmd(c, "restart", "restarter")
  2002. }
  2003. // run container with --rm should remove container if exit code != 0
  2004. func (s *DockerSuite) TestRunContainerWithRmFlagExitCodeNotEqualToZero(c *check.C) {
  2005. testRequires(c, DaemonIsLinux)
  2006. name := "flowers"
  2007. out, _, err := dockerCmdWithError("run", "--name", name, "--rm", "busybox", "ls", "/notexists")
  2008. if err == nil {
  2009. c.Fatal("Expected docker run to fail", out, err)
  2010. }
  2011. out, err = getAllContainers()
  2012. if err != nil {
  2013. c.Fatal(out, err)
  2014. }
  2015. if out != "" {
  2016. c.Fatal("Expected not to have containers", out)
  2017. }
  2018. }
  2019. func (s *DockerSuite) TestRunContainerWithRmFlagCannotStartContainer(c *check.C) {
  2020. testRequires(c, DaemonIsLinux)
  2021. name := "sparkles"
  2022. out, _, err := dockerCmdWithError("run", "--name", name, "--rm", "busybox", "commandNotFound")
  2023. if err == nil {
  2024. c.Fatal("Expected docker run to fail", out, err)
  2025. }
  2026. out, err = getAllContainers()
  2027. if err != nil {
  2028. c.Fatal(out, err)
  2029. }
  2030. if out != "" {
  2031. c.Fatal("Expected not to have containers", out)
  2032. }
  2033. }
  2034. func (s *DockerSuite) TestRunPidHostWithChildIsKillable(c *check.C) {
  2035. testRequires(c, DaemonIsLinux)
  2036. name := "ibuildthecloud"
  2037. dockerCmd(c, "run", "-d", "--pid=host", "--name", name, "busybox", "sh", "-c", "sleep 30; echo hi")
  2038. c.Assert(waitRun(name), check.IsNil)
  2039. errchan := make(chan error)
  2040. go func() {
  2041. if out, _, err := dockerCmdWithError("kill", name); err != nil {
  2042. errchan <- fmt.Errorf("%v:\n%s", err, out)
  2043. }
  2044. close(errchan)
  2045. }()
  2046. select {
  2047. case err := <-errchan:
  2048. c.Assert(err, check.IsNil)
  2049. case <-time.After(5 * time.Second):
  2050. c.Fatal("Kill container timed out")
  2051. }
  2052. }
  2053. func (s *DockerSuite) TestRunWithTooSmallMemoryLimit(c *check.C) {
  2054. testRequires(c, DaemonIsLinux)
  2055. // this memory limit is 1 byte less than the min, which is 4MB
  2056. // https://github.com/docker/docker/blob/v1.5.0/daemon/create.go#L22
  2057. out, _, err := dockerCmdWithError("run", "-m", "4194303", "busybox")
  2058. if err == nil || !strings.Contains(out, "Minimum memory limit allowed is 4MB") {
  2059. c.Fatalf("expected run to fail when using too low a memory limit: %q", out)
  2060. }
  2061. }
  2062. func (s *DockerSuite) TestRunWriteToProcAsound(c *check.C) {
  2063. testRequires(c, DaemonIsLinux)
  2064. _, code, err := dockerCmdWithError("run", "busybox", "sh", "-c", "echo 111 >> /proc/asound/version")
  2065. if err == nil || code == 0 {
  2066. c.Fatal("standard container should not be able to write to /proc/asound")
  2067. }
  2068. }
  2069. func (s *DockerSuite) TestRunReadProcTimer(c *check.C) {
  2070. testRequires(c, NativeExecDriver, DaemonIsLinux)
  2071. out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/timer_stats")
  2072. if code != 0 {
  2073. return
  2074. }
  2075. if err != nil {
  2076. c.Fatal(err)
  2077. }
  2078. if strings.Trim(out, "\n ") != "" {
  2079. c.Fatalf("expected to receive no output from /proc/timer_stats but received %q", out)
  2080. }
  2081. }
  2082. func (s *DockerSuite) TestRunReadProcLatency(c *check.C) {
  2083. testRequires(c, NativeExecDriver, DaemonIsLinux)
  2084. // some kernels don't have this configured so skip the test if this file is not found
  2085. // on the host running the tests.
  2086. if _, err := os.Stat("/proc/latency_stats"); err != nil {
  2087. c.Skip("kernel doesnt have latency_stats configured")
  2088. return
  2089. }
  2090. out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/latency_stats")
  2091. if code != 0 {
  2092. return
  2093. }
  2094. if err != nil {
  2095. c.Fatal(err)
  2096. }
  2097. if strings.Trim(out, "\n ") != "" {
  2098. c.Fatalf("expected to receive no output from /proc/latency_stats but received %q", out)
  2099. }
  2100. }
  2101. func (s *DockerSuite) TestRunReadFilteredProc(c *check.C) {
  2102. testRequires(c, Apparmor, DaemonIsLinux)
  2103. testReadPaths := []string{
  2104. "/proc/latency_stats",
  2105. "/proc/timer_stats",
  2106. "/proc/kcore",
  2107. }
  2108. for i, filePath := range testReadPaths {
  2109. name := fmt.Sprintf("procsieve-%d", i)
  2110. shellCmd := fmt.Sprintf("exec 3<%s", filePath)
  2111. out, exitCode, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor:docker-default", "--name", name, "busybox", "sh", "-c", shellCmd)
  2112. if exitCode != 0 {
  2113. return
  2114. }
  2115. if err != nil {
  2116. c.Fatalf("Open FD for read should have failed with permission denied, got: %s, %v", out, err)
  2117. }
  2118. }
  2119. }
  2120. func (s *DockerSuite) TestMountIntoProc(c *check.C) {
  2121. testRequires(c, DaemonIsLinux)
  2122. testRequires(c, NativeExecDriver)
  2123. _, code, err := dockerCmdWithError("run", "-v", "/proc//sys", "busybox", "true")
  2124. if err == nil || code == 0 {
  2125. c.Fatal("container should not be able to mount into /proc")
  2126. }
  2127. }
  2128. func (s *DockerSuite) TestMountIntoSys(c *check.C) {
  2129. testRequires(c, DaemonIsLinux)
  2130. testRequires(c, NativeExecDriver)
  2131. dockerCmd(c, "run", "-v", "/sys/fs/cgroup", "busybox", "true")
  2132. }
  2133. func (s *DockerSuite) TestRunUnshareProc(c *check.C) {
  2134. testRequires(c, Apparmor, NativeExecDriver, DaemonIsLinux)
  2135. name := "acidburn"
  2136. 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") {
  2137. c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err)
  2138. }
  2139. name = "cereal"
  2140. 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") {
  2141. c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err)
  2142. }
  2143. /* Ensure still fails if running privileged with the default policy */
  2144. name = "crashoverride"
  2145. 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") {
  2146. c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err)
  2147. }
  2148. }
  2149. func (s *DockerSuite) TestRunPublishPort(c *check.C) {
  2150. testRequires(c, DaemonIsLinux)
  2151. dockerCmd(c, "run", "-d", "--name", "test", "--expose", "8080", "busybox", "top")
  2152. out, _ := dockerCmd(c, "port", "test")
  2153. out = strings.Trim(out, "\r\n")
  2154. if out != "" {
  2155. c.Fatalf("run without --publish-all should not publish port, out should be nil, but got: %s", out)
  2156. }
  2157. }
  2158. // Issue #10184.
  2159. func (s *DockerSuite) TestDevicePermissions(c *check.C) {
  2160. testRequires(c, DaemonIsLinux)
  2161. testRequires(c, NativeExecDriver)
  2162. const permissions = "crw-rw-rw-"
  2163. out, status := dockerCmd(c, "run", "--device", "/dev/fuse:/dev/fuse:mrw", "busybox:latest", "ls", "-l", "/dev/fuse")
  2164. if status != 0 {
  2165. c.Fatalf("expected status 0, got %d", status)
  2166. }
  2167. if !strings.HasPrefix(out, permissions) {
  2168. c.Fatalf("output should begin with %q, got %q", permissions, out)
  2169. }
  2170. }
  2171. func (s *DockerSuite) TestRunCapAddCHOWN(c *check.C) {
  2172. testRequires(c, DaemonIsLinux)
  2173. testRequires(c, NativeExecDriver)
  2174. out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok")
  2175. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  2176. c.Fatalf("expected output ok received %s", actual)
  2177. }
  2178. }
  2179. // https://github.com/docker/docker/pull/14498
  2180. func (s *DockerSuite) TestVolumeFromMixedRWOptions(c *check.C) {
  2181. testRequires(c, DaemonIsLinux)
  2182. dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true")
  2183. dockerCmd(c, "run", "--volumes-from", "parent:ro", "--name", "test-volumes-1", "busybox", "true")
  2184. dockerCmd(c, "run", "--volumes-from", "parent:rw", "--name", "test-volumes-2", "busybox", "true")
  2185. mRO, err := inspectMountPoint("test-volumes-1", "/test")
  2186. c.Assert(err, check.IsNil)
  2187. if mRO.RW {
  2188. c.Fatalf("Expected RO volume was RW")
  2189. }
  2190. mRW, err := inspectMountPoint("test-volumes-2", "/test")
  2191. c.Assert(err, check.IsNil)
  2192. if !mRW.RW {
  2193. c.Fatalf("Expected RW volume was RO")
  2194. }
  2195. }
  2196. func (s *DockerSuite) TestRunWriteFilteredProc(c *check.C) {
  2197. testRequires(c, Apparmor, NativeExecDriver, DaemonIsLinux)
  2198. testWritePaths := []string{
  2199. /* modprobe and core_pattern should both be denied by generic
  2200. * policy of denials for /proc/sys/kernel. These files have been
  2201. * picked to be checked as they are particularly sensitive to writes */
  2202. "/proc/sys/kernel/modprobe",
  2203. "/proc/sys/kernel/core_pattern",
  2204. "/proc/sysrq-trigger",
  2205. "/proc/kcore",
  2206. }
  2207. for i, filePath := range testWritePaths {
  2208. name := fmt.Sprintf("writeprocsieve-%d", i)
  2209. shellCmd := fmt.Sprintf("exec 3>%s", filePath)
  2210. out, code, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor:docker-default", "--name", name, "busybox", "sh", "-c", shellCmd)
  2211. if code != 0 {
  2212. return
  2213. }
  2214. if err != nil {
  2215. c.Fatalf("Open FD for write should have failed with permission denied, got: %s, %v", out, err)
  2216. }
  2217. }
  2218. }
  2219. func (s *DockerSuite) TestRunNetworkFilesBindMount(c *check.C) {
  2220. testRequires(c, SameHostDaemon, DaemonIsLinux)
  2221. expected := "test123"
  2222. filename := createTmpFile(c, expected)
  2223. defer os.Remove(filename)
  2224. nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  2225. for i := range nwfiles {
  2226. actual, _ := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "busybox", "cat", nwfiles[i])
  2227. if actual != expected {
  2228. c.Fatalf("expected %s be: %q, but was: %q", nwfiles[i], expected, actual)
  2229. }
  2230. }
  2231. }
  2232. func (s *DockerSuite) TestRunNetworkFilesBindMountRO(c *check.C) {
  2233. testRequires(c, SameHostDaemon, DaemonIsLinux)
  2234. filename := createTmpFile(c, "test123")
  2235. defer os.Remove(filename)
  2236. nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  2237. for i := range nwfiles {
  2238. _, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "busybox", "touch", nwfiles[i])
  2239. if err == nil || exitCode == 0 {
  2240. c.Fatalf("run should fail because bind mount of %s is ro: exit code %d", nwfiles[i], exitCode)
  2241. }
  2242. }
  2243. }
  2244. func (s *DockerSuite) TestRunNetworkFilesBindMountROFilesystem(c *check.C) {
  2245. testRequires(c, SameHostDaemon, DaemonIsLinux)
  2246. filename := createTmpFile(c, "test123")
  2247. defer os.Remove(filename)
  2248. nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  2249. for i := range nwfiles {
  2250. _, exitCode := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "--read-only", "busybox", "touch", nwfiles[i])
  2251. if exitCode != 0 {
  2252. c.Fatalf("run should not fail because %s is mounted writable on read-only root filesystem: exit code %d", nwfiles[i], exitCode)
  2253. }
  2254. }
  2255. for i := range nwfiles {
  2256. _, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "--read-only", "busybox", "touch", nwfiles[i])
  2257. if err == nil || exitCode == 0 {
  2258. c.Fatalf("run should fail because %s is mounted read-only on read-only root filesystem: exit code %d", nwfiles[i], exitCode)
  2259. }
  2260. }
  2261. }
  2262. func (s *DockerTrustSuite) TestTrustedRun(c *check.C) {
  2263. testRequires(c, DaemonIsLinux)
  2264. repoName := s.setupTrustedImage(c, "trusted-run")
  2265. // Try run
  2266. runCmd := exec.Command(dockerBinary, "run", repoName)
  2267. s.trustedCmd(runCmd)
  2268. out, _, err := runCommandWithOutput(runCmd)
  2269. if err != nil {
  2270. c.Fatalf("Error running trusted run: %s\n%s\n", err, out)
  2271. }
  2272. if !strings.Contains(string(out), "Tagging") {
  2273. c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2274. }
  2275. dockerCmd(c, "rmi", repoName)
  2276. // Try untrusted run to ensure we pushed the tag to the registry
  2277. runCmd = exec.Command(dockerBinary, "run", "--disable-content-trust=true", repoName)
  2278. s.trustedCmd(runCmd)
  2279. out, _, err = runCommandWithOutput(runCmd)
  2280. if err != nil {
  2281. c.Fatalf("Error running trusted run: %s\n%s", err, out)
  2282. }
  2283. if !strings.Contains(string(out), "Status: Downloaded") {
  2284. c.Fatalf("Missing expected output on trusted run with --disable-content-trust:\n%s", out)
  2285. }
  2286. }
  2287. func (s *DockerTrustSuite) TestUntrustedRun(c *check.C) {
  2288. testRequires(c, DaemonIsLinux)
  2289. repoName := fmt.Sprintf("%v/dockercli/trusted:latest", privateRegistryURL)
  2290. // tag the image and upload it to the private registry
  2291. dockerCmd(c, "tag", "busybox", repoName)
  2292. dockerCmd(c, "push", repoName)
  2293. dockerCmd(c, "rmi", repoName)
  2294. // Try trusted run on untrusted tag
  2295. runCmd := exec.Command(dockerBinary, "run", repoName)
  2296. s.trustedCmd(runCmd)
  2297. out, _, err := runCommandWithOutput(runCmd)
  2298. if err == nil {
  2299. c.Fatalf("Error expected when running trusted run with:\n%s", out)
  2300. }
  2301. if !strings.Contains(string(out), "no trust data available") {
  2302. c.Fatalf("Missing expected output on trusted run:\n%s", out)
  2303. }
  2304. }
  2305. func (s *DockerTrustSuite) TestRunWhenCertExpired(c *check.C) {
  2306. testRequires(c, DaemonIsLinux)
  2307. c.Skip("Currently changes system time, causing instability")
  2308. repoName := s.setupTrustedImage(c, "trusted-run-expired")
  2309. // Certificates have 10 years of expiration
  2310. elevenYearsFromNow := time.Now().Add(time.Hour * 24 * 365 * 11)
  2311. runAtDifferentDate(elevenYearsFromNow, func() {
  2312. // Try run
  2313. runCmd := exec.Command(dockerBinary, "run", repoName)
  2314. s.trustedCmd(runCmd)
  2315. out, _, err := runCommandWithOutput(runCmd)
  2316. if err == nil {
  2317. c.Fatalf("Error running trusted run in the distant future: %s\n%s", err, out)
  2318. }
  2319. if !strings.Contains(string(out), "could not validate the path to a trusted root") {
  2320. c.Fatalf("Missing expected output on trusted run in the distant future:\n%s", out)
  2321. }
  2322. })
  2323. runAtDifferentDate(elevenYearsFromNow, func() {
  2324. // Try run
  2325. runCmd := exec.Command(dockerBinary, "run", "--disable-content-trust", repoName)
  2326. s.trustedCmd(runCmd)
  2327. out, _, err := runCommandWithOutput(runCmd)
  2328. if err != nil {
  2329. c.Fatalf("Error running untrusted run in the distant future: %s\n%s", err, out)
  2330. }
  2331. if !strings.Contains(string(out), "Status: Downloaded") {
  2332. c.Fatalf("Missing expected output on untrusted run in the distant future:\n%s", out)
  2333. }
  2334. })
  2335. }
  2336. func (s *DockerTrustSuite) TestTrustedRunFromBadTrustServer(c *check.C) {
  2337. testRequires(c, DaemonIsLinux)
  2338. repoName := fmt.Sprintf("%v/dockerclievilrun/trusted:latest", privateRegistryURL)
  2339. evilLocalConfigDir, err := ioutil.TempDir("", "evil-local-config-dir")
  2340. if err != nil {
  2341. c.Fatalf("Failed to create local temp dir")
  2342. }
  2343. // tag the image and upload it to the private registry
  2344. dockerCmd(c, "tag", "busybox", repoName)
  2345. pushCmd := exec.Command(dockerBinary, "push", repoName)
  2346. s.trustedCmd(pushCmd)
  2347. out, _, err := runCommandWithOutput(pushCmd)
  2348. if err != nil {
  2349. c.Fatalf("Error running trusted push: %s\n%s", err, out)
  2350. }
  2351. if !strings.Contains(string(out), "Signing and pushing trust metadata") {
  2352. c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2353. }
  2354. dockerCmd(c, "rmi", repoName)
  2355. // Try run
  2356. runCmd := exec.Command(dockerBinary, "run", repoName)
  2357. s.trustedCmd(runCmd)
  2358. out, _, err = runCommandWithOutput(runCmd)
  2359. if err != nil {
  2360. c.Fatalf("Error running trusted run: %s\n%s", err, out)
  2361. }
  2362. if !strings.Contains(string(out), "Tagging") {
  2363. c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2364. }
  2365. dockerCmd(c, "rmi", repoName)
  2366. // Kill the notary server, start a new "evil" one.
  2367. s.not.Close()
  2368. s.not, err = newTestNotary(c)
  2369. if err != nil {
  2370. c.Fatalf("Restarting notary server failed.")
  2371. }
  2372. // In order to make an evil server, lets re-init a client (with a different trust dir) and push new data.
  2373. // tag an image and upload it to the private registry
  2374. dockerCmd(c, "--config", evilLocalConfigDir, "tag", "busybox", repoName)
  2375. // Push up to the new server
  2376. pushCmd = exec.Command(dockerBinary, "--config", evilLocalConfigDir, "push", repoName)
  2377. s.trustedCmd(pushCmd)
  2378. out, _, err = runCommandWithOutput(pushCmd)
  2379. if err != nil {
  2380. c.Fatalf("Error running trusted push: %s\n%s", err, out)
  2381. }
  2382. if !strings.Contains(string(out), "Signing and pushing trust metadata") {
  2383. c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2384. }
  2385. // Now, try running with the original client from this new trust server. This should fail.
  2386. runCmd = exec.Command(dockerBinary, "run", repoName)
  2387. s.trustedCmd(runCmd)
  2388. out, _, err = runCommandWithOutput(runCmd)
  2389. if err == nil {
  2390. c.Fatalf("Expected to fail on this run due to different remote data: %s\n%s", err, out)
  2391. }
  2392. if !strings.Contains(string(out), "failed to validate data with current trusted certificates") {
  2393. c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2394. }
  2395. }
  2396. func (s *DockerSuite) TestPtraceContainerProcsFromHost(c *check.C) {
  2397. testRequires(c, DaemonIsLinux)
  2398. testRequires(c, SameHostDaemon)
  2399. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  2400. id := strings.TrimSpace(out)
  2401. c.Assert(waitRun(id), check.IsNil)
  2402. pid1, err := inspectField(id, "State.Pid")
  2403. c.Assert(err, check.IsNil)
  2404. _, err = os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
  2405. if err != nil {
  2406. c.Fatal(err)
  2407. }
  2408. }
  2409. func (s *DockerSuite) TestAppArmorDeniesPtrace(c *check.C) {
  2410. testRequires(c, SameHostDaemon, NativeExecDriver, Apparmor, DaemonIsLinux, NotGCCGO)
  2411. // Run through 'sh' so we are NOT pid 1. Pid 1 may be able to trace
  2412. // itself, but pid>1 should not be able to trace pid1.
  2413. _, exitCode, _ := dockerCmdWithError("run", "busybox", "sh", "-c", "readlink /proc/1/ns/net")
  2414. if exitCode == 0 {
  2415. c.Fatal("ptrace was not successfully restricted by AppArmor")
  2416. }
  2417. }
  2418. func (s *DockerSuite) TestAppArmorTraceSelf(c *check.C) {
  2419. testRequires(c, DaemonIsLinux)
  2420. testRequires(c, SameHostDaemon)
  2421. testRequires(c, Apparmor)
  2422. _, exitCode, _ := dockerCmdWithError("run", "busybox", "readlink", "/proc/1/ns/net")
  2423. if exitCode != 0 {
  2424. c.Fatal("ptrace of self failed.")
  2425. }
  2426. }
  2427. func (s *DockerSuite) TestAppArmorDeniesChmodProc(c *check.C) {
  2428. testRequires(c, SameHostDaemon, NativeExecDriver, Apparmor, DaemonIsLinux)
  2429. _, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "744", "/proc/cpuinfo")
  2430. if exitCode == 0 {
  2431. // If our test failed, attempt to repair the host system...
  2432. _, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "444", "/proc/cpuinfo")
  2433. if exitCode == 0 {
  2434. c.Fatal("AppArmor was unsuccessful in prohibiting chmod of /proc/* files.")
  2435. }
  2436. }
  2437. }
  2438. func (s *DockerSuite) TestRunCapAddSYSTIME(c *check.C) {
  2439. testRequires(c, DaemonIsLinux)
  2440. testRequires(c, NativeExecDriver)
  2441. dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=SYS_TIME", "busybox", "sh", "-c", "grep ^CapEff /proc/self/status | sed 's/^CapEff:\t//' | grep ^0000000002000000$")
  2442. }
  2443. // run create container failed should clean up the container
  2444. func (s *DockerSuite) TestRunCreateContainerFailedCleanUp(c *check.C) {
  2445. testRequires(c, DaemonIsLinux)
  2446. name := "unique_name"
  2447. _, _, err := dockerCmdWithError("run", "--name", name, "--link", "nothing:nothing", "busybox")
  2448. c.Assert(err, check.Not(check.IsNil), check.Commentf("Expected docker run to fail!"))
  2449. containerID, err := inspectField(name, "Id")
  2450. c.Assert(containerID, check.Equals, "", check.Commentf("Expected not to have this container: %s!", containerID))
  2451. }
  2452. func (s *DockerSuite) TestRunNamedVolume(c *check.C) {
  2453. testRequires(c, DaemonIsLinux)
  2454. dockerCmd(c, "run", "--name=test", "-v", "testing:/foo", "busybox", "sh", "-c", "echo hello > /foo/bar")
  2455. out, _ := dockerCmd(c, "run", "--volumes-from", "test", "busybox", "sh", "-c", "cat /foo/bar")
  2456. c.Assert(strings.TrimSpace(out), check.Equals, "hello")
  2457. out, _ = dockerCmd(c, "run", "-v", "testing:/foo", "busybox", "sh", "-c", "cat /foo/bar")
  2458. c.Assert(strings.TrimSpace(out), check.Equals, "hello")
  2459. }
  2460. func (s *DockerSuite) TestRunWithUlimits(c *check.C) {
  2461. testRequires(c, NativeExecDriver)
  2462. out, _ := dockerCmd(c, "run", "--name=testulimits", "--ulimit", "nofile=42", "busybox", "/bin/sh", "-c", "ulimit -n")
  2463. ul := strings.TrimSpace(out)
  2464. if ul != "42" {
  2465. c.Fatalf("expected `ulimit -n` to be 42, got %s", ul)
  2466. }
  2467. }
  2468. func (s *DockerSuite) TestRunContainerWithCgroupParent(c *check.C) {
  2469. testRequires(c, NativeExecDriver)
  2470. cgroupParent := "test"
  2471. name := "cgroup-test"
  2472. out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup")
  2473. if err != nil {
  2474. c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
  2475. }
  2476. cgroupPaths := parseCgroupPaths(string(out))
  2477. if len(cgroupPaths) == 0 {
  2478. c.Fatalf("unexpected output - %q", string(out))
  2479. }
  2480. id, err := getIDByName(name)
  2481. c.Assert(err, check.IsNil)
  2482. expectedCgroup := path.Join(cgroupParent, id)
  2483. found := false
  2484. for _, path := range cgroupPaths {
  2485. if strings.HasSuffix(path, expectedCgroup) {
  2486. found = true
  2487. break
  2488. }
  2489. }
  2490. if !found {
  2491. c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths)
  2492. }
  2493. }
  2494. func (s *DockerSuite) TestRunContainerWithCgroupParentAbsPath(c *check.C) {
  2495. testRequires(c, NativeExecDriver)
  2496. cgroupParent := "/cgroup-parent/test"
  2497. name := "cgroup-test"
  2498. out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup")
  2499. if err != nil {
  2500. c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
  2501. }
  2502. cgroupPaths := parseCgroupPaths(string(out))
  2503. if len(cgroupPaths) == 0 {
  2504. c.Fatalf("unexpected output - %q", string(out))
  2505. }
  2506. id, err := getIDByName(name)
  2507. c.Assert(err, check.IsNil)
  2508. expectedCgroup := path.Join(cgroupParent, id)
  2509. found := false
  2510. for _, path := range cgroupPaths {
  2511. if strings.HasSuffix(path, expectedCgroup) {
  2512. found = true
  2513. break
  2514. }
  2515. }
  2516. if !found {
  2517. c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths)
  2518. }
  2519. }
  2520. func (s *DockerSuite) TestRunContainerWithCgroupMountRO(c *check.C) {
  2521. testRequires(c, NativeExecDriver)
  2522. filename := "/sys/fs/cgroup/devices/test123"
  2523. out, _, err := dockerCmdWithError("run", "busybox", "touch", filename)
  2524. if err == nil {
  2525. c.Fatal("expected cgroup mount point to be read-only, touch file should fail")
  2526. }
  2527. expected := "Read-only file system"
  2528. if !strings.Contains(out, expected) {
  2529. c.Fatalf("expected output from failure to contain %s but contains %s", expected, out)
  2530. }
  2531. }
  2532. func (s *DockerSuite) TestRunContainerNetworkModeToSelf(c *check.C) {
  2533. testRequires(c, DaemonIsLinux)
  2534. out, _, err := dockerCmdWithError("run", "--name=me", "--net=container:me", "busybox", "true")
  2535. if err == nil || !strings.Contains(out, "cannot join own network") {
  2536. c.Fatalf("using container net mode to self should result in an error\nerr: %q\nout: %s", err, out)
  2537. }
  2538. }
  2539. func (s *DockerSuite) TestRunContainerNetModeWithDnsMacHosts(c *check.C) {
  2540. testRequires(c, DaemonIsLinux)
  2541. out, _, err := dockerCmdWithError("run", "-d", "--name", "parent", "busybox", "top")
  2542. if err != nil {
  2543. c.Fatalf("failed to run container: %v, output: %q", err, out)
  2544. }
  2545. out, _, err = dockerCmdWithError("run", "--dns", "1.2.3.4", "--net=container:parent", "busybox")
  2546. if err == nil || !strings.Contains(out, "Conflicting options: --dns and the network mode") {
  2547. c.Fatalf("run --net=container with --dns should error out")
  2548. }
  2549. out, _, err = dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29:33", "--net=container:parent", "busybox")
  2550. if err == nil || !strings.Contains(out, "--mac-address and the network mode") {
  2551. c.Fatalf("run --net=container with --mac-address should error out")
  2552. }
  2553. out, _, err = dockerCmdWithError("run", "--add-host", "test:192.168.2.109", "--net=container:parent", "busybox")
  2554. if err == nil || !strings.Contains(out, "--add-host and the network mode") {
  2555. c.Fatalf("run --net=container with --add-host should error out")
  2556. }
  2557. }
  2558. func (s *DockerSuite) TestRunContainerNetModeWithExposePort(c *check.C) {
  2559. testRequires(c, DaemonIsLinux)
  2560. dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top")
  2561. out, _, err := dockerCmdWithError("run", "-p", "5000:5000", "--net=container:parent", "busybox")
  2562. if err == nil || !strings.Contains(out, "Conflicting options: -p, -P, --publish-all, --publish and the network mode (--net)") {
  2563. c.Fatalf("run --net=container with -p should error out")
  2564. }
  2565. out, _, err = dockerCmdWithError("run", "-P", "--net=container:parent", "busybox")
  2566. if err == nil || !strings.Contains(out, "Conflicting options: -p, -P, --publish-all, --publish and the network mode (--net)") {
  2567. c.Fatalf("run --net=container with -P should error out")
  2568. }
  2569. out, _, err = dockerCmdWithError("run", "--expose", "5000", "--net=container:parent", "busybox")
  2570. if err == nil || !strings.Contains(out, "Conflicting options: --expose and the network mode (--expose)") {
  2571. c.Fatalf("run --net=container with --expose should error out")
  2572. }
  2573. }
  2574. func (s *DockerSuite) TestRunLinkToContainerNetMode(c *check.C) {
  2575. testRequires(c, DaemonIsLinux)
  2576. dockerCmd(c, "run", "--name", "test", "-d", "busybox", "top")
  2577. dockerCmd(c, "run", "--name", "parent", "-d", "--net=container:test", "busybox", "top")
  2578. dockerCmd(c, "run", "-d", "--link=parent:parent", "busybox", "top")
  2579. dockerCmd(c, "run", "--name", "child", "-d", "--net=container:parent", "busybox", "top")
  2580. dockerCmd(c, "run", "-d", "--link=child:child", "busybox", "top")
  2581. }
  2582. func (s *DockerSuite) TestRunLoopbackOnlyExistsWhenNetworkingDisabled(c *check.C) {
  2583. testRequires(c, DaemonIsLinux)
  2584. out, _ := dockerCmd(c, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up")
  2585. var (
  2586. count = 0
  2587. parts = strings.Split(out, "\n")
  2588. )
  2589. for _, l := range parts {
  2590. if l != "" {
  2591. count++
  2592. }
  2593. }
  2594. if count != 1 {
  2595. c.Fatalf("Wrong interface count in container %d", count)
  2596. }
  2597. if !strings.HasPrefix(out, "1: lo") {
  2598. c.Fatalf("Wrong interface in test container: expected [1: lo], got %s", out)
  2599. }
  2600. }
  2601. // Issue #4681
  2602. func (s *DockerSuite) TestRunLoopbackWhenNetworkDisabled(c *check.C) {
  2603. testRequires(c, DaemonIsLinux)
  2604. dockerCmd(c, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1")
  2605. }
  2606. func (s *DockerSuite) TestRunModeNetContainerHostname(c *check.C) {
  2607. testRequires(c, DaemonIsLinux, ExecSupport)
  2608. dockerCmd(c, "run", "-i", "-d", "--name", "parent", "busybox", "top")
  2609. out, _ := dockerCmd(c, "exec", "parent", "cat", "/etc/hostname")
  2610. out1, _ := dockerCmd(c, "run", "--net=container:parent", "busybox", "cat", "/etc/hostname")
  2611. if out1 != out {
  2612. c.Fatal("containers with shared net namespace should have same hostname")
  2613. }
  2614. }
  2615. func (s *DockerSuite) TestRunNetworkNotInitializedNoneMode(c *check.C) {
  2616. testRequires(c, DaemonIsLinux)
  2617. out, _ := dockerCmd(c, "run", "-d", "--net=none", "busybox", "top")
  2618. id := strings.TrimSpace(out)
  2619. res, err := inspectField(id, "NetworkSettings.IPAddress")
  2620. c.Assert(err, check.IsNil)
  2621. if res != "" {
  2622. c.Fatalf("For 'none' mode network must not be initialized, but container got IP: %s", res)
  2623. }
  2624. }
  2625. func (s *DockerSuite) TestTwoContainersInNetHost(c *check.C) {
  2626. testRequires(c, DaemonIsLinux)
  2627. dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top")
  2628. dockerCmd(c, "run", "-d", "--net=host", "--name=second", "busybox", "top")
  2629. dockerCmd(c, "stop", "first")
  2630. dockerCmd(c, "stop", "second")
  2631. }