docker_cli_run_test.go 100 KB

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