docker_cli_run_test.go 104 KB

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