docker_cli_run_test.go 167 KB

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