docker_cli_run_test.go 164 KB

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