docker_cli_run_test.go 96 KB

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