docker_cli_run_test.go 94 KB

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