docker_cli_run_test.go 90 KB

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