docker_cli_run_test.go 103 KB

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