docker_cli_run_test.go 100 KB

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