docker_cli_run_test.go 96 KB

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