docker_cli_run_test.go 97 KB

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