docker_cli_run_test.go 155 KB

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