docker_cli_run_test.go 90 KB

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