docker_cli_run_test.go 99 KB

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