docker_cli_run_test.go 88 KB

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