docker_cli_run_test.go 163 KB

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