docker_cli_run_test.go 128 KB

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