docker_cli_run_test.go 89 KB

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