docker_cli_run_test.go 157 KB

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