docker_cli_run_test.go 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014
  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/nat"
  20. "github.com/docker/docker/pkg/resolvconf"
  21. "github.com/go-check/check"
  22. )
  23. // "test123" should be printed by docker run
  24. func (s *DockerSuite) TestRunEchoStdout(c *check.C) {
  25. runCmd := exec.Command(dockerBinary, "run", "busybox", "echo", "test123")
  26. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  27. if err != nil {
  28. c.Fatalf("failed to run container: %v, output: %q", err, out)
  29. }
  30. if out != "test123\n" {
  31. c.Fatalf("container should've printed 'test123'")
  32. }
  33. }
  34. // "test" should be printed
  35. func (s *DockerSuite) TestRunEchoStdoutWithMemoryLimit(c *check.C) {
  36. runCmd := exec.Command(dockerBinary, "run", "-m", "16m", "busybox", "echo", "test")
  37. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  38. if err != nil {
  39. c.Fatalf("failed to run container: %v, output: %q", err, out)
  40. }
  41. out = strings.Trim(out, "\r\n")
  42. if expected := "test"; out != expected {
  43. c.Fatalf("container should've printed %q but printed %q", expected, out)
  44. }
  45. }
  46. // should run without memory swap
  47. func (s *DockerSuite) TestRunWithoutMemoryswapLimit(c *check.C) {
  48. runCmd := exec.Command(dockerBinary, "run", "-m", "16m", "--memory-swap", "-1", "busybox", "true")
  49. out, _, err := runCommandWithOutput(runCmd)
  50. if err != nil {
  51. c.Fatalf("failed to run container, output: %q", out)
  52. }
  53. }
  54. // "test" should be printed
  55. func (s *DockerSuite) TestRunEchoStdoutWitCPULimit(c *check.C) {
  56. runCmd := exec.Command(dockerBinary, "run", "-c", "1000", "busybox", "echo", "test")
  57. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  58. if err != nil {
  59. c.Fatalf("failed to run container: %v, output: %q", err, out)
  60. }
  61. if out != "test\n" {
  62. c.Errorf("container should've printed 'test'")
  63. }
  64. }
  65. // "test" should be printed
  66. func (s *DockerSuite) TestRunEchoStdoutWithCPUAndMemoryLimit(c *check.C) {
  67. runCmd := exec.Command(dockerBinary, "run", "-c", "1000", "-m", "16m", "busybox", "echo", "test")
  68. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  69. if err != nil {
  70. c.Fatalf("failed to run container: %v, output: %q", err, out)
  71. }
  72. if out != "test\n" {
  73. c.Errorf("container should've printed 'test', got %q instead", out)
  74. }
  75. }
  76. // "test" should be printed
  77. func (s *DockerSuite) TestRunEchoStdoutWitCPUQuota(c *check.C) {
  78. runCmd := exec.Command(dockerBinary, "run", "--cpu-quota", "8000", "--name", "test", "busybox", "echo", "test")
  79. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  80. if err != nil {
  81. c.Fatalf("failed to run container: %v, output: %q", err, out)
  82. }
  83. out = strings.TrimSpace(out)
  84. if strings.Contains(out, "Your kernel does not support CPU cfs quota") {
  85. c.Skip("Your kernel does not support CPU cfs quota, skip this test")
  86. }
  87. if out != "test" {
  88. c.Errorf("container should've printed 'test'")
  89. }
  90. cmd := exec.Command(dockerBinary, "inspect", "-f", "{{.HostConfig.CpuQuota}}", "test")
  91. out, _, err = runCommandWithOutput(cmd)
  92. if err != nil {
  93. c.Fatalf("failed to inspect container: %s, %v", out, err)
  94. }
  95. out = strings.TrimSpace(out)
  96. if out != "8000" {
  97. c.Errorf("setting the CPU CFS quota failed")
  98. }
  99. }
  100. // "test" should be printed
  101. func (s *DockerSuite) TestRunEchoNamedContainer(c *check.C) {
  102. runCmd := exec.Command(dockerBinary, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test")
  103. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  104. if err != nil {
  105. c.Fatalf("failed to run container: %v, output: %q", err, out)
  106. }
  107. if out != "test\n" {
  108. c.Errorf("container should've printed 'test'")
  109. }
  110. if err := deleteContainer("testfoonamedcontainer"); err != nil {
  111. c.Errorf("failed to remove the named container: %v", err)
  112. }
  113. }
  114. // docker run should not leak file descriptors
  115. func (s *DockerSuite) TestRunLeakyFileDescriptors(c *check.C) {
  116. runCmd := exec.Command(dockerBinary, "run", "busybox", "ls", "-C", "/proc/self/fd")
  117. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  118. if err != nil {
  119. c.Fatalf("failed to run container: %v, output: %q", err, out)
  120. }
  121. // normally, we should only get 0, 1, and 2, but 3 gets created by "ls" when it does "opendir" on the "fd" directory
  122. if out != "0 1 2 3\n" {
  123. c.Errorf("container should've printed '0 1 2 3', not: %s", out)
  124. }
  125. }
  126. // it should be possible to lookup Google DNS
  127. // this will fail when Internet access is unavailable
  128. func (s *DockerSuite) TestRunLookupGoogleDns(c *check.C) {
  129. testRequires(c, Network)
  130. out, _, _, err := runCommandWithStdoutStderr(exec.Command(dockerBinary, "run", "busybox", "nslookup", "google.com"))
  131. if err != nil {
  132. c.Fatalf("failed to run container: %v, output: %q", err, out)
  133. }
  134. }
  135. // the exit code should be 0
  136. // some versions of lxc might make this test fail
  137. func (s *DockerSuite) TestRunExitCodeZero(c *check.C) {
  138. runCmd := exec.Command(dockerBinary, "run", "busybox", "true")
  139. if out, _, err := runCommandWithOutput(runCmd); err != nil {
  140. c.Errorf("container should've exited with exit code 0: %s, %v", out, err)
  141. }
  142. }
  143. // the exit code should be 1
  144. // some versions of lxc might make this test fail
  145. func (s *DockerSuite) TestRunExitCodeOne(c *check.C) {
  146. runCmd := exec.Command(dockerBinary, "run", "busybox", "false")
  147. exitCode, err := runCommand(runCmd)
  148. if err != nil && !strings.Contains("exit status 1", fmt.Sprintf("%s", err)) {
  149. c.Fatal(err)
  150. }
  151. if exitCode != 1 {
  152. c.Errorf("container should've exited with exit code 1")
  153. }
  154. }
  155. // it should be possible to pipe in data via stdin to a process running in a container
  156. // some versions of lxc might make this test fail
  157. func (s *DockerSuite) TestRunStdinPipe(c *check.C) {
  158. runCmd := exec.Command("bash", "-c", `echo "blahblah" | docker run -i -a stdin busybox cat`)
  159. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  160. if err != nil {
  161. c.Fatalf("failed to run container: %v, output: %q", err, out)
  162. }
  163. out = strings.TrimSpace(out)
  164. inspectCmd := exec.Command(dockerBinary, "inspect", out)
  165. if out, _, err := runCommandWithOutput(inspectCmd); err != nil {
  166. c.Fatalf("out should've been a container id: %s %v", out, err)
  167. }
  168. waitCmd := exec.Command(dockerBinary, "wait", out)
  169. if waitOut, _, err := runCommandWithOutput(waitCmd); err != nil {
  170. c.Fatalf("error thrown while waiting for container: %s, %v", waitOut, err)
  171. }
  172. logsCmd := exec.Command(dockerBinary, "logs", out)
  173. logsOut, _, err := runCommandWithOutput(logsCmd)
  174. if err != nil {
  175. c.Fatalf("error thrown while trying to get container logs: %s, %v", logsOut, err)
  176. }
  177. containerLogs := strings.TrimSpace(logsOut)
  178. if containerLogs != "blahblah" {
  179. c.Errorf("logs didn't print the container's logs %s", containerLogs)
  180. }
  181. rmCmd := exec.Command(dockerBinary, "rm", out)
  182. if out, _, err = runCommandWithOutput(rmCmd); err != nil {
  183. c.Fatalf("rm failed to remove container: %s, %v", out, err)
  184. }
  185. }
  186. // the container's ID should be printed when starting a container in detached mode
  187. func (s *DockerSuite) TestRunDetachedContainerIDPrinting(c *check.C) {
  188. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "true")
  189. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  190. if err != nil {
  191. c.Fatalf("failed to run container: %v, output: %q", err, out)
  192. }
  193. out = strings.TrimSpace(out)
  194. inspectCmd := exec.Command(dockerBinary, "inspect", out)
  195. if inspectOut, _, err := runCommandWithOutput(inspectCmd); err != nil {
  196. c.Fatalf("out should've been a container id: %s %v", inspectOut, err)
  197. }
  198. waitCmd := exec.Command(dockerBinary, "wait", out)
  199. if waitOut, _, err := runCommandWithOutput(waitCmd); err != nil {
  200. c.Fatalf("error thrown while waiting for container: %s, %v", waitOut, err)
  201. }
  202. rmCmd := exec.Command(dockerBinary, "rm", out)
  203. rmOut, _, err := runCommandWithOutput(rmCmd)
  204. if err != nil {
  205. c.Fatalf("rm failed to remove container: %s, %v", rmOut, err)
  206. }
  207. rmOut = strings.TrimSpace(rmOut)
  208. if rmOut != out {
  209. c.Errorf("rm didn't print the container ID %s %s", out, rmOut)
  210. }
  211. }
  212. // the working directory should be set correctly
  213. func (s *DockerSuite) TestRunWorkingDirectory(c *check.C) {
  214. runCmd := exec.Command(dockerBinary, "run", "-w", "/root", "busybox", "pwd")
  215. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  216. if err != nil {
  217. c.Fatalf("failed to run container: %v, output: %q", err, out)
  218. }
  219. out = strings.TrimSpace(out)
  220. if out != "/root" {
  221. c.Errorf("-w failed to set working directory")
  222. }
  223. runCmd = exec.Command(dockerBinary, "run", "--workdir", "/root", "busybox", "pwd")
  224. out, _, _, err = runCommandWithStdoutStderr(runCmd)
  225. if err != nil {
  226. c.Fatal(out, err)
  227. }
  228. out = strings.TrimSpace(out)
  229. if out != "/root" {
  230. c.Errorf("--workdir failed to set working directory")
  231. }
  232. }
  233. // pinging Google's DNS resolver should fail when we disable the networking
  234. func (s *DockerSuite) TestRunWithoutNetworking(c *check.C) {
  235. runCmd := exec.Command(dockerBinary, "run", "--net=none", "busybox", "ping", "-c", "1", "8.8.8.8")
  236. out, _, exitCode, err := runCommandWithStdoutStderr(runCmd)
  237. if err != nil && exitCode != 1 {
  238. c.Fatal(out, err)
  239. }
  240. if exitCode != 1 {
  241. c.Errorf("--net=none should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
  242. }
  243. runCmd = exec.Command(dockerBinary, "run", "-n=false", "busybox", "ping", "-c", "1", "8.8.8.8")
  244. out, _, exitCode, err = runCommandWithStdoutStderr(runCmd)
  245. if err != nil && exitCode != 1 {
  246. c.Fatal(out, err)
  247. }
  248. if exitCode != 1 {
  249. c.Errorf("-n=false should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
  250. }
  251. }
  252. //test --link use container name to link target
  253. func (s *DockerSuite) TestRunLinksContainerWithContainerName(c *check.C) {
  254. cmd := exec.Command(dockerBinary, "run", "-i", "-t", "-d", "--name", "parent", "busybox")
  255. out, _, _, err := runCommandWithStdoutStderr(cmd)
  256. if err != nil {
  257. c.Fatalf("failed to run container: %v, output: %q", err, out)
  258. }
  259. cmd = exec.Command(dockerBinary, "inspect", "-f", "{{.NetworkSettings.IPAddress}}", "parent")
  260. ip, _, _, err := runCommandWithStdoutStderr(cmd)
  261. if err != nil {
  262. c.Fatalf("failed to inspect container: %v, output: %q", err, ip)
  263. }
  264. ip = strings.TrimSpace(ip)
  265. cmd = exec.Command(dockerBinary, "run", "--link", "parent:test", "busybox", "/bin/cat", "/etc/hosts")
  266. out, _, err = runCommandWithOutput(cmd)
  267. if err != nil {
  268. c.Fatalf("failed to run container: %v, output: %q", err, out)
  269. }
  270. if !strings.Contains(out, ip+" test") {
  271. c.Fatalf("use a container name to link target failed")
  272. }
  273. }
  274. //test --link use container id to link target
  275. func (s *DockerSuite) TestRunLinksContainerWithContainerId(c *check.C) {
  276. cmd := exec.Command(dockerBinary, "run", "-i", "-t", "-d", "busybox")
  277. cID, _, _, err := runCommandWithStdoutStderr(cmd)
  278. if err != nil {
  279. c.Fatalf("failed to run container: %v, output: %q", err, cID)
  280. }
  281. cID = strings.TrimSpace(cID)
  282. cmd = exec.Command(dockerBinary, "inspect", "-f", "{{.NetworkSettings.IPAddress}}", cID)
  283. ip, _, _, err := runCommandWithStdoutStderr(cmd)
  284. if err != nil {
  285. c.Fatalf("failed to inspect container: %v, output: %q", err, ip)
  286. }
  287. ip = strings.TrimSpace(ip)
  288. cmd = exec.Command(dockerBinary, "run", "--link", cID+":test", "busybox", "/bin/cat", "/etc/hosts")
  289. out, _, err := runCommandWithOutput(cmd)
  290. if err != nil {
  291. c.Fatalf("failed to run container: %v, output: %q", err, out)
  292. }
  293. if !strings.Contains(out, ip+" test") {
  294. c.Fatalf("use a container id to link target failed")
  295. }
  296. }
  297. func (s *DockerSuite) TestRunLinkToContainerNetMode(c *check.C) {
  298. cmd := exec.Command(dockerBinary, "run", "--name", "test", "-d", "busybox", "top")
  299. out, _, err := runCommandWithOutput(cmd)
  300. if err != nil {
  301. c.Fatalf("failed to run container: %v, output: %q", err, out)
  302. }
  303. cmd = exec.Command(dockerBinary, "run", "--name", "parent", "-d", "--net=container:test", "busybox", "top")
  304. out, _, err = runCommandWithOutput(cmd)
  305. if err != nil {
  306. c.Fatalf("failed to run container: %v, output: %q", err, out)
  307. }
  308. cmd = exec.Command(dockerBinary, "run", "-d", "--link=parent:parent", "busybox", "top")
  309. out, _, err = runCommandWithOutput(cmd)
  310. if err != nil {
  311. c.Fatalf("failed to run container: %v, output: %q", err, out)
  312. }
  313. cmd = exec.Command(dockerBinary, "run", "--name", "child", "-d", "--net=container:parent", "busybox", "top")
  314. out, _, err = runCommandWithOutput(cmd)
  315. if err != nil {
  316. c.Fatalf("failed to run container: %v, output: %q", err, out)
  317. }
  318. cmd = exec.Command(dockerBinary, "run", "-d", "--link=child:child", "busybox", "top")
  319. out, _, err = runCommandWithOutput(cmd)
  320. if err != nil {
  321. c.Fatalf("failed to run container: %v, output: %q", err, out)
  322. }
  323. }
  324. func (s *DockerSuite) TestRunModeNetContainerHostname(c *check.C) {
  325. testRequires(c, ExecSupport)
  326. cmd := exec.Command(dockerBinary, "run", "-i", "-d", "--name", "parent", "busybox", "top")
  327. out, _, err := runCommandWithOutput(cmd)
  328. if err != nil {
  329. c.Fatalf("failed to run container: %v, output: %q", err, out)
  330. }
  331. cmd = exec.Command(dockerBinary, "exec", "parent", "cat", "/etc/hostname")
  332. out, _, err = runCommandWithOutput(cmd)
  333. if err != nil {
  334. c.Fatalf("failed to exec command: %v, output: %q", err, out)
  335. }
  336. cmd = exec.Command(dockerBinary, "run", "--net=container:parent", "busybox", "cat", "/etc/hostname")
  337. out1, _, err := runCommandWithOutput(cmd)
  338. if err != nil {
  339. c.Fatalf("failed to run container: %v, output: %q", err, out1)
  340. }
  341. if out1 != out {
  342. c.Fatal("containers with shared net namespace should have same hostname")
  343. }
  344. }
  345. // Regression test for #4741
  346. func (s *DockerSuite) TestRunWithVolumesAsFiles(c *check.C) {
  347. runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", "/etc/hosts:/target-file", "busybox", "true")
  348. out, stderr, exitCode, err := runCommandWithStdoutStderr(runCmd)
  349. if err != nil && exitCode != 0 {
  350. c.Fatal("1", out, stderr, err)
  351. }
  352. runCmd = exec.Command(dockerBinary, "run", "--volumes-from", "test-data", "busybox", "cat", "/target-file")
  353. out, stderr, exitCode, err = runCommandWithStdoutStderr(runCmd)
  354. if err != nil && exitCode != 0 {
  355. c.Fatal("2", out, stderr, err)
  356. }
  357. }
  358. // Regression test for #4979
  359. func (s *DockerSuite) TestRunWithVolumesFromExited(c *check.C) {
  360. runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file")
  361. out, stderr, exitCode, err := runCommandWithStdoutStderr(runCmd)
  362. if err != nil && exitCode != 0 {
  363. c.Fatal("1", out, stderr, err)
  364. }
  365. runCmd = exec.Command(dockerBinary, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file")
  366. out, stderr, exitCode, err = runCommandWithStdoutStderr(runCmd)
  367. if err != nil && exitCode != 0 {
  368. c.Fatal("2", out, stderr, err)
  369. }
  370. }
  371. // Volume path is a symlink which also exists on the host, and the host side is a file not a dir
  372. // But the volume call is just a normal volume, not a bind mount
  373. func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir(c *check.C) {
  374. testRequires(c, SameHostDaemon)
  375. testRequires(c, NativeExecDriver)
  376. name := "test-volume-symlink"
  377. dir, err := ioutil.TempDir("", name)
  378. if err != nil {
  379. c.Fatal(err)
  380. }
  381. defer os.RemoveAll(dir)
  382. f, err := os.OpenFile(filepath.Join(dir, "test"), os.O_CREATE, 0700)
  383. if err != nil {
  384. c.Fatal(err)
  385. }
  386. f.Close()
  387. dockerFile := fmt.Sprintf("FROM busybox\nRUN mkdir -p %s\nRUN ln -s %s /test", dir, dir)
  388. if _, err := buildImage(name, dockerFile, false); err != nil {
  389. c.Fatal(err)
  390. }
  391. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-v", "/test/test", name))
  392. if err != nil {
  393. c.Fatalf("Failed with errors: %s, %v", out, err)
  394. }
  395. }
  396. // Regression test for #4830
  397. func (s *DockerSuite) TestRunWithRelativePath(c *check.C) {
  398. runCmd := exec.Command(dockerBinary, "run", "-v", "tmp:/other-tmp", "busybox", "true")
  399. if _, _, _, err := runCommandWithStdoutStderr(runCmd); err == nil {
  400. c.Fatalf("relative path should result in an error")
  401. }
  402. }
  403. func (s *DockerSuite) TestRunVolumesMountedAsReadonly(c *check.C) {
  404. cmd := exec.Command(dockerBinary, "run", "-v", "/test:/test:ro", "busybox", "touch", "/test/somefile")
  405. if code, err := runCommand(cmd); err == nil || code == 0 {
  406. c.Fatalf("run should fail because volume is ro: exit code %d", code)
  407. }
  408. }
  409. func (s *DockerSuite) TestRunVolumesFromInReadonlyMode(c *check.C) {
  410. cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test", "busybox", "true")
  411. if _, err := runCommand(cmd); err != nil {
  412. c.Fatal(err)
  413. }
  414. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent:ro", "busybox", "touch", "/test/file")
  415. if code, err := runCommand(cmd); err == nil || code == 0 {
  416. c.Fatalf("run should fail because volume is ro: exit code %d", code)
  417. }
  418. }
  419. // Regression test for #1201
  420. func (s *DockerSuite) TestRunVolumesFromInReadWriteMode(c *check.C) {
  421. cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test", "busybox", "true")
  422. if _, err := runCommand(cmd); err != nil {
  423. c.Fatal(err)
  424. }
  425. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file")
  426. if out, _, err := runCommandWithOutput(cmd); err != nil {
  427. c.Fatalf("running --volumes-from parent:rw failed with output: %q\nerror: %v", out, err)
  428. }
  429. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent:bar", "busybox", "touch", "/test/file")
  430. if out, _, err := runCommandWithOutput(cmd); err == nil || !strings.Contains(out, "invalid mode for volumes-from: bar") {
  431. c.Fatalf("running --volumes-from foo:bar should have failed with invalid mount mode: %q", out)
  432. }
  433. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent", "busybox", "touch", "/test/file")
  434. if out, _, err := runCommandWithOutput(cmd); err != nil {
  435. c.Fatalf("running --volumes-from parent failed with output: %q\nerror: %v", out, err)
  436. }
  437. }
  438. func (s *DockerSuite) TestVolumesFromGetsProperMode(c *check.C) {
  439. cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test:/test:ro", "busybox", "true")
  440. if _, err := runCommand(cmd); err != nil {
  441. c.Fatal(err)
  442. }
  443. // Expect this "rw" mode to be be ignored since the inherited volume is "ro"
  444. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file")
  445. if _, err := runCommand(cmd); err == nil {
  446. c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `rw`")
  447. }
  448. cmd = exec.Command(dockerBinary, "run", "--name", "parent2", "-v", "/test:/test:ro", "busybox", "true")
  449. if _, err := runCommand(cmd); err != nil {
  450. c.Fatal(err)
  451. }
  452. // Expect this to be read-only since both are "ro"
  453. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent2:ro", "busybox", "touch", "/test/file")
  454. if _, err := runCommand(cmd); err == nil {
  455. c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `ro`")
  456. }
  457. }
  458. // Test for GH#10618
  459. func (s *DockerSuite) TestRunNoDupVolumes(c *check.C) {
  460. mountstr1 := randomUnixTmpDirPath("test1") + ":/someplace"
  461. mountstr2 := randomUnixTmpDirPath("test2") + ":/someplace"
  462. cmd := exec.Command(dockerBinary, "run", "-v", mountstr1, "-v", mountstr2, "busybox", "true")
  463. if out, _, err := runCommandWithOutput(cmd); err == nil {
  464. c.Fatal("Expected error about duplicate volume definitions")
  465. } else {
  466. if !strings.Contains(out, "Duplicate volume") {
  467. c.Fatalf("Expected 'duplicate volume' error, got %v", err)
  468. }
  469. }
  470. }
  471. // Test for #1351
  472. func (s *DockerSuite) TestRunApplyVolumesFromBeforeVolumes(c *check.C) {
  473. cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test", "busybox", "touch", "/test/foo")
  474. if _, err := runCommand(cmd); err != nil {
  475. c.Fatal(err)
  476. }
  477. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent", "-v", "/test", "busybox", "cat", "/test/foo")
  478. if out, _, err := runCommandWithOutput(cmd); err != nil {
  479. c.Fatal(out, err)
  480. }
  481. }
  482. func (s *DockerSuite) TestRunMultipleVolumesFrom(c *check.C) {
  483. cmd := exec.Command(dockerBinary, "run", "--name", "parent1", "-v", "/test", "busybox", "touch", "/test/foo")
  484. if _, err := runCommand(cmd); err != nil {
  485. c.Fatal(err)
  486. }
  487. cmd = exec.Command(dockerBinary, "run", "--name", "parent2", "-v", "/other", "busybox", "touch", "/other/bar")
  488. if _, err := runCommand(cmd); err != nil {
  489. c.Fatal(err)
  490. }
  491. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent1", "--volumes-from", "parent2",
  492. "busybox", "sh", "-c", "cat /test/foo && cat /other/bar")
  493. if _, err := runCommand(cmd); err != nil {
  494. c.Fatal(err)
  495. }
  496. }
  497. // this tests verifies the ID format for the container
  498. func (s *DockerSuite) TestRunVerifyContainerID(c *check.C) {
  499. cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "true")
  500. out, exit, err := runCommandWithOutput(cmd)
  501. if err != nil {
  502. c.Fatal(err)
  503. }
  504. if exit != 0 {
  505. c.Fatalf("expected exit code 0 received %d", exit)
  506. }
  507. match, err := regexp.MatchString("^[0-9a-f]{64}$", strings.TrimSuffix(out, "\n"))
  508. if err != nil {
  509. c.Fatal(err)
  510. }
  511. if !match {
  512. c.Fatalf("Invalid container ID: %s", out)
  513. }
  514. }
  515. // Test that creating a container with a volume doesn't crash. Regression test for #995.
  516. func (s *DockerSuite) TestRunCreateVolume(c *check.C) {
  517. cmd := exec.Command(dockerBinary, "run", "-v", "/var/lib/data", "busybox", "true")
  518. if _, err := runCommand(cmd); err != nil {
  519. c.Fatal(err)
  520. }
  521. }
  522. // Test that creating a volume with a symlink in its path works correctly. Test for #5152.
  523. // Note that this bug happens only with symlinks with a target that starts with '/'.
  524. func (s *DockerSuite) TestRunCreateVolumeWithSymlink(c *check.C) {
  525. image := "docker-test-createvolumewithsymlink"
  526. buildCmd := exec.Command(dockerBinary, "build", "-t", image, "-")
  527. buildCmd.Stdin = strings.NewReader(`FROM busybox
  528. RUN ln -s home /bar`)
  529. buildCmd.Dir = workingDirectory
  530. err := buildCmd.Run()
  531. if err != nil {
  532. c.Fatalf("could not build '%s': %v", image, err)
  533. }
  534. cmd := exec.Command(dockerBinary, "run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", image, "sh", "-c", "mount | grep -q /home/foo")
  535. exitCode, err := runCommand(cmd)
  536. if err != nil || exitCode != 0 {
  537. c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
  538. }
  539. var volPath string
  540. cmd = exec.Command(dockerBinary, "inspect", "-f", "{{range .Volumes}}{{.}}{{end}}", "test-createvolumewithsymlink")
  541. volPath, exitCode, err = runCommandWithOutput(cmd)
  542. if err != nil || exitCode != 0 {
  543. c.Fatalf("[inspect] err: %v, exitcode: %d", err, exitCode)
  544. }
  545. cmd = exec.Command(dockerBinary, "rm", "-v", "test-createvolumewithsymlink")
  546. exitCode, err = runCommand(cmd)
  547. if err != nil || exitCode != 0 {
  548. c.Fatalf("[rm] err: %v, exitcode: %d", err, exitCode)
  549. }
  550. f, err := os.Open(volPath)
  551. defer f.Close()
  552. if !os.IsNotExist(err) {
  553. c.Fatalf("[open] (expecting 'file does not exist' error) err: %v, volPath: %s", err, volPath)
  554. }
  555. }
  556. // Tests that a volume path that has a symlink exists in a container mounting it with `--volumes-from`.
  557. func (s *DockerSuite) TestRunVolumesFromSymlinkPath(c *check.C) {
  558. name := "docker-test-volumesfromsymlinkpath"
  559. buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-")
  560. buildCmd.Stdin = strings.NewReader(`FROM busybox
  561. RUN ln -s home /foo
  562. VOLUME ["/foo/bar"]`)
  563. buildCmd.Dir = workingDirectory
  564. err := buildCmd.Run()
  565. if err != nil {
  566. c.Fatalf("could not build 'docker-test-volumesfromsymlinkpath': %v", err)
  567. }
  568. cmd := exec.Command(dockerBinary, "run", "--name", "test-volumesfromsymlinkpath", name)
  569. exitCode, err := runCommand(cmd)
  570. if err != nil || exitCode != 0 {
  571. c.Fatalf("[run] (volume) err: %v, exitcode: %d", err, exitCode)
  572. }
  573. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "test-volumesfromsymlinkpath", "busybox", "sh", "-c", "ls /foo | grep -q bar")
  574. exitCode, err = runCommand(cmd)
  575. if err != nil || exitCode != 0 {
  576. c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
  577. }
  578. }
  579. func (s *DockerSuite) TestRunExitCode(c *check.C) {
  580. cmd := exec.Command(dockerBinary, "run", "busybox", "/bin/sh", "-c", "exit 72")
  581. exit, err := runCommand(cmd)
  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) TestRunUserDefaultsToRoot(c *check.C) {
  590. cmd := exec.Command(dockerBinary, "run", "busybox", "id")
  591. out, _, err := runCommandWithOutput(cmd)
  592. if err != nil {
  593. c.Fatal(err, out)
  594. }
  595. if !strings.Contains(out, "uid=0(root) gid=0(root)") {
  596. c.Fatalf("expected root user got %s", out)
  597. }
  598. }
  599. func (s *DockerSuite) TestRunUserByName(c *check.C) {
  600. cmd := exec.Command(dockerBinary, "run", "-u", "root", "busybox", "id")
  601. out, _, err := runCommandWithOutput(cmd)
  602. if err != nil {
  603. c.Fatal(err, out)
  604. }
  605. if !strings.Contains(out, "uid=0(root) gid=0(root)") {
  606. c.Fatalf("expected root user got %s", out)
  607. }
  608. }
  609. func (s *DockerSuite) TestRunUserByID(c *check.C) {
  610. cmd := exec.Command(dockerBinary, "run", "-u", "1", "busybox", "id")
  611. out, _, err := runCommandWithOutput(cmd)
  612. if err != nil {
  613. c.Fatal(err, out)
  614. }
  615. if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") {
  616. c.Fatalf("expected daemon user got %s", out)
  617. }
  618. }
  619. func (s *DockerSuite) TestRunUserByIDBig(c *check.C) {
  620. cmd := exec.Command(dockerBinary, "run", "-u", "2147483648", "busybox", "id")
  621. out, _, err := runCommandWithOutput(cmd)
  622. if err == nil {
  623. c.Fatal("No error, but must be.", out)
  624. }
  625. if !strings.Contains(out, "Uids and gids must be in range") {
  626. c.Fatalf("expected error about uids range, got %s", out)
  627. }
  628. }
  629. func (s *DockerSuite) TestRunUserByIDNegative(c *check.C) {
  630. cmd := exec.Command(dockerBinary, "run", "-u", "-1", "busybox", "id")
  631. out, _, err := runCommandWithOutput(cmd)
  632. if err == nil {
  633. c.Fatal("No error, but must be.", out)
  634. }
  635. if !strings.Contains(out, "Uids and gids must be in range") {
  636. c.Fatalf("expected error about uids range, got %s", out)
  637. }
  638. }
  639. func (s *DockerSuite) TestRunUserByIDZero(c *check.C) {
  640. cmd := exec.Command(dockerBinary, "run", "-u", "0", "busybox", "id")
  641. out, _, err := runCommandWithOutput(cmd)
  642. if err != nil {
  643. c.Fatal(err, out)
  644. }
  645. if !strings.Contains(out, "uid=0(root) gid=0(root) groups=10(wheel)") {
  646. c.Fatalf("expected daemon user got %s", out)
  647. }
  648. }
  649. func (s *DockerSuite) TestRunUserNotFound(c *check.C) {
  650. cmd := exec.Command(dockerBinary, "run", "-u", "notme", "busybox", "id")
  651. _, err := runCommand(cmd)
  652. if err == nil {
  653. c.Fatal("unknown user should cause container to fail")
  654. }
  655. }
  656. func (s *DockerSuite) TestRunTwoConcurrentContainers(c *check.C) {
  657. group := sync.WaitGroup{}
  658. group.Add(2)
  659. errChan := make(chan error, 2)
  660. for i := 0; i < 2; i++ {
  661. go func() {
  662. defer group.Done()
  663. cmd := exec.Command(dockerBinary, "run", "busybox", "sleep", "2")
  664. _, err := runCommand(cmd)
  665. errChan <- err
  666. }()
  667. }
  668. group.Wait()
  669. close(errChan)
  670. for err := range errChan {
  671. c.Assert(err, check.IsNil)
  672. }
  673. }
  674. func (s *DockerSuite) TestRunEnvironment(c *check.C) {
  675. cmd := exec.Command(dockerBinary, "run", "-h", "testing", "-e=FALSE=true", "-e=TRUE", "-e=TRICKY", "-e=HOME=", "busybox", "env")
  676. cmd.Env = append(os.Environ(),
  677. "TRUE=false",
  678. "TRICKY=tri\ncky\n",
  679. )
  680. out, _, err := runCommandWithOutput(cmd)
  681. if err != nil {
  682. c.Fatal(err, out)
  683. }
  684. actualEnvLxc := strings.Split(strings.TrimSpace(out), "\n")
  685. actualEnv := []string{}
  686. for i := range actualEnvLxc {
  687. if actualEnvLxc[i] != "container=lxc" {
  688. actualEnv = append(actualEnv, actualEnvLxc[i])
  689. }
  690. }
  691. sort.Strings(actualEnv)
  692. goodEnv := []string{
  693. "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  694. "HOSTNAME=testing",
  695. "FALSE=true",
  696. "TRUE=false",
  697. "TRICKY=tri",
  698. "cky",
  699. "",
  700. "HOME=/root",
  701. }
  702. sort.Strings(goodEnv)
  703. if len(goodEnv) != len(actualEnv) {
  704. c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", "))
  705. }
  706. for i := range goodEnv {
  707. if actualEnv[i] != goodEnv[i] {
  708. c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
  709. }
  710. }
  711. }
  712. func (s *DockerSuite) TestRunEnvironmentErase(c *check.C) {
  713. // Test to make sure that when we use -e on env vars that are
  714. // not set in our local env that they're removed (if present) in
  715. // the container
  716. cmd := exec.Command(dockerBinary, "run", "-e", "FOO", "-e", "HOSTNAME", "busybox", "env")
  717. cmd.Env = appendBaseEnv([]string{})
  718. out, _, err := runCommandWithOutput(cmd)
  719. if err != nil {
  720. c.Fatal(err, out)
  721. }
  722. actualEnvLxc := strings.Split(strings.TrimSpace(out), "\n")
  723. actualEnv := []string{}
  724. for i := range actualEnvLxc {
  725. if actualEnvLxc[i] != "container=lxc" {
  726. actualEnv = append(actualEnv, actualEnvLxc[i])
  727. }
  728. }
  729. sort.Strings(actualEnv)
  730. goodEnv := []string{
  731. "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  732. "HOME=/root",
  733. }
  734. sort.Strings(goodEnv)
  735. if len(goodEnv) != len(actualEnv) {
  736. c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", "))
  737. }
  738. for i := range goodEnv {
  739. if actualEnv[i] != goodEnv[i] {
  740. c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
  741. }
  742. }
  743. }
  744. func (s *DockerSuite) TestRunEnvironmentOverride(c *check.C) {
  745. // Test to make sure that when we use -e on env vars that are
  746. // already in the env that we're overriding them
  747. cmd := exec.Command(dockerBinary, "run", "-e", "HOSTNAME", "-e", "HOME=/root2", "busybox", "env")
  748. cmd.Env = appendBaseEnv([]string{"HOSTNAME=bar"})
  749. out, _, err := runCommandWithOutput(cmd)
  750. if err != nil {
  751. c.Fatal(err, out)
  752. }
  753. actualEnvLxc := strings.Split(strings.TrimSpace(out), "\n")
  754. actualEnv := []string{}
  755. for i := range actualEnvLxc {
  756. if actualEnvLxc[i] != "container=lxc" {
  757. actualEnv = append(actualEnv, actualEnvLxc[i])
  758. }
  759. }
  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: %q\n", len(goodEnv), 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. cmd := exec.Command(dockerBinary, "run", "busybox", "ping", "-c", "1", "127.0.0.1")
  778. if _, err := runCommand(cmd); err != nil {
  779. c.Fatal(err)
  780. }
  781. }
  782. // Issue #4681
  783. func (s *DockerSuite) TestRunLoopbackWhenNetworkDisabled(c *check.C) {
  784. cmd := exec.Command(dockerBinary, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1")
  785. if _, err := runCommand(cmd); err != nil {
  786. c.Fatal(err)
  787. }
  788. }
  789. func (s *DockerSuite) TestRunNetHostNotAllowedWithLinks(c *check.C) {
  790. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--name", "linked", "busybox", "true"))
  791. if err != nil {
  792. c.Fatalf("Failed with errors: %s, %v", out, err)
  793. }
  794. cmd := exec.Command(dockerBinary, "run", "--net=host", "--link", "linked:linked", "busybox", "true")
  795. _, _, err = runCommandWithOutput(cmd)
  796. if err == nil {
  797. c.Fatal("Expected error")
  798. }
  799. }
  800. func (s *DockerSuite) TestRunLoopbackOnlyExistsWhenNetworkingDisabled(c *check.C) {
  801. cmd := exec.Command(dockerBinary, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up")
  802. out, _, err := runCommandWithOutput(cmd)
  803. if err != nil {
  804. c.Fatal(err, out)
  805. }
  806. var (
  807. count = 0
  808. parts = strings.Split(out, "\n")
  809. )
  810. for _, l := range parts {
  811. if l != "" {
  812. count++
  813. }
  814. }
  815. if count != 1 {
  816. c.Fatalf("Wrong interface count in container %d", count)
  817. }
  818. if !strings.HasPrefix(out, "1: lo") {
  819. c.Fatalf("Wrong interface in test container: expected [1: lo], got %s", out)
  820. }
  821. }
  822. // #7851 hostname outside container shows FQDN, inside only shortname
  823. // For testing purposes it is not required to set host's hostname directly
  824. // and use "--net=host" (as the original issue submitter did), as the same
  825. // codepath is executed with "docker run -h <hostname>". Both were manually
  826. // tested, but this testcase takes the simpler path of using "run -h .."
  827. func (s *DockerSuite) TestRunFullHostnameSet(c *check.C) {
  828. cmd := exec.Command(dockerBinary, "run", "-h", "foo.bar.baz", "busybox", "hostname")
  829. out, _, err := runCommandWithOutput(cmd)
  830. if err != nil {
  831. c.Fatal(err, out)
  832. }
  833. if actual := strings.Trim(out, "\r\n"); actual != "foo.bar.baz" {
  834. c.Fatalf("expected hostname 'foo.bar.baz', received %s", actual)
  835. }
  836. }
  837. func (s *DockerSuite) TestRunPrivilegedCanMknod(c *check.C) {
  838. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  839. out, _, err := runCommandWithOutput(cmd)
  840. if err != nil {
  841. c.Fatal(err)
  842. }
  843. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  844. c.Fatalf("expected output ok received %s", actual)
  845. }
  846. }
  847. func (s *DockerSuite) TestRunUnPrivilegedCanMknod(c *check.C) {
  848. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  849. out, _, err := runCommandWithOutput(cmd)
  850. if err != nil {
  851. c.Fatal(err)
  852. }
  853. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  854. c.Fatalf("expected output ok received %s", actual)
  855. }
  856. }
  857. func (s *DockerSuite) TestRunCapDropInvalid(c *check.C) {
  858. cmd := exec.Command(dockerBinary, "run", "--cap-drop=CHPASS", "busybox", "ls")
  859. out, _, err := runCommandWithOutput(cmd)
  860. if err == nil {
  861. c.Fatal(err, out)
  862. }
  863. }
  864. func (s *DockerSuite) TestRunCapDropCannotMknod(c *check.C) {
  865. cmd := exec.Command(dockerBinary, "run", "--cap-drop=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  866. out, _, err := runCommandWithOutput(cmd)
  867. if err == nil {
  868. c.Fatal(err, out)
  869. }
  870. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  871. c.Fatalf("expected output not ok received %s", actual)
  872. }
  873. }
  874. func (s *DockerSuite) TestRunCapDropCannotMknodLowerCase(c *check.C) {
  875. cmd := exec.Command(dockerBinary, "run", "--cap-drop=mknod", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  876. out, _, err := runCommandWithOutput(cmd)
  877. if err == nil {
  878. c.Fatal(err, out)
  879. }
  880. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  881. c.Fatalf("expected output not ok received %s", actual)
  882. }
  883. }
  884. func (s *DockerSuite) TestRunCapDropALLCannotMknod(c *check.C) {
  885. cmd := exec.Command(dockerBinary, "run", "--cap-drop=ALL", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  886. out, _, err := runCommandWithOutput(cmd)
  887. if err == nil {
  888. c.Fatal(err, out)
  889. }
  890. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  891. c.Fatalf("expected output not ok received %s", actual)
  892. }
  893. }
  894. func (s *DockerSuite) TestRunCapDropALLAddMknodCanMknod(c *check.C) {
  895. cmd := exec.Command(dockerBinary, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  896. out, _, err := runCommandWithOutput(cmd)
  897. if err != nil {
  898. c.Fatal(err, out)
  899. }
  900. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  901. c.Fatalf("expected output ok received %s", actual)
  902. }
  903. }
  904. func (s *DockerSuite) TestRunCapAddInvalid(c *check.C) {
  905. cmd := exec.Command(dockerBinary, "run", "--cap-add=CHPASS", "busybox", "ls")
  906. out, _, err := runCommandWithOutput(cmd)
  907. if err == nil {
  908. c.Fatal(err, out)
  909. }
  910. }
  911. func (s *DockerSuite) TestRunCapAddCanDownInterface(c *check.C) {
  912. cmd := exec.Command(dockerBinary, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  913. out, _, err := runCommandWithOutput(cmd)
  914. if err != nil {
  915. c.Fatal(err, out)
  916. }
  917. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  918. c.Fatalf("expected output ok received %s", actual)
  919. }
  920. }
  921. func (s *DockerSuite) TestRunCapAddALLCanDownInterface(c *check.C) {
  922. cmd := exec.Command(dockerBinary, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  923. out, _, err := runCommandWithOutput(cmd)
  924. if err != nil {
  925. c.Fatal(err, out)
  926. }
  927. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  928. c.Fatalf("expected output ok received %s", actual)
  929. }
  930. }
  931. func (s *DockerSuite) TestRunCapAddALLDropNetAdminCanDownInterface(c *check.C) {
  932. cmd := exec.Command(dockerBinary, "run", "--cap-add=ALL", "--cap-drop=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  933. out, _, err := runCommandWithOutput(cmd)
  934. if err == nil {
  935. c.Fatal(err, out)
  936. }
  937. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  938. c.Fatalf("expected output not ok received %s", actual)
  939. }
  940. }
  941. func (s *DockerSuite) TestRunPrivilegedCanMount(c *check.C) {
  942. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
  943. out, _, err := runCommandWithOutput(cmd)
  944. if err != nil {
  945. c.Fatal(err)
  946. }
  947. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  948. c.Fatalf("expected output ok received %s", actual)
  949. }
  950. }
  951. func (s *DockerSuite) TestRunUnPrivilegedCannotMount(c *check.C) {
  952. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
  953. out, _, err := runCommandWithOutput(cmd)
  954. if err == nil {
  955. c.Fatal(err, out)
  956. }
  957. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  958. c.Fatalf("expected output not ok received %s", actual)
  959. }
  960. }
  961. func (s *DockerSuite) TestRunSysNotWritableInNonPrivilegedContainers(c *check.C) {
  962. cmd := exec.Command(dockerBinary, "run", "busybox", "touch", "/sys/kernel/profiling")
  963. if code, err := runCommand(cmd); err == nil || code == 0 {
  964. c.Fatal("sys should not be writable in a non privileged container")
  965. }
  966. }
  967. func (s *DockerSuite) TestRunSysWritableInPrivilegedContainers(c *check.C) {
  968. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "touch", "/sys/kernel/profiling")
  969. if code, err := runCommand(cmd); err != nil || code != 0 {
  970. c.Fatalf("sys should be writable in privileged container")
  971. }
  972. }
  973. func (s *DockerSuite) TestRunProcNotWritableInNonPrivilegedContainers(c *check.C) {
  974. cmd := exec.Command(dockerBinary, "run", "busybox", "touch", "/proc/sysrq-trigger")
  975. if code, err := runCommand(cmd); err == nil || code == 0 {
  976. c.Fatal("proc should not be writable in a non privileged container")
  977. }
  978. }
  979. func (s *DockerSuite) TestRunProcWritableInPrivilegedContainers(c *check.C) {
  980. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "touch", "/proc/sysrq-trigger")
  981. if code, err := runCommand(cmd); err != nil || code != 0 {
  982. c.Fatalf("proc should be writable in privileged container")
  983. }
  984. }
  985. func (s *DockerSuite) TestRunWithCpuset(c *check.C) {
  986. cmd := exec.Command(dockerBinary, "run", "--cpuset", "0", "busybox", "true")
  987. if code, err := runCommand(cmd); err != nil || code != 0 {
  988. c.Fatalf("container should run successfully with cpuset of 0: %s", err)
  989. }
  990. }
  991. func (s *DockerSuite) TestRunWithCpusetCpus(c *check.C) {
  992. cmd := exec.Command(dockerBinary, "run", "--cpuset-cpus", "0", "busybox", "true")
  993. if code, err := runCommand(cmd); err != nil || code != 0 {
  994. c.Fatalf("container should run successfully with cpuset-cpus of 0: %s", err)
  995. }
  996. }
  997. func (s *DockerSuite) TestRunWithCpusetMems(c *check.C) {
  998. cmd := exec.Command(dockerBinary, "run", "--cpuset-mems", "0", "busybox", "true")
  999. if code, err := runCommand(cmd); err != nil || code != 0 {
  1000. c.Fatalf("container should run successfully with cpuset-mems of 0: %s", err)
  1001. }
  1002. }
  1003. func (s *DockerSuite) TestRunDeviceNumbers(c *check.C) {
  1004. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "ls -l /dev/null")
  1005. out, _, err := runCommandWithOutput(cmd)
  1006. if err != nil {
  1007. c.Fatal(err, out)
  1008. }
  1009. deviceLineFields := strings.Fields(out)
  1010. deviceLineFields[6] = ""
  1011. deviceLineFields[7] = ""
  1012. deviceLineFields[8] = ""
  1013. expected := []string{"crw-rw-rw-", "1", "root", "root", "1,", "3", "", "", "", "/dev/null"}
  1014. if !(reflect.DeepEqual(deviceLineFields, expected)) {
  1015. c.Fatalf("expected output\ncrw-rw-rw- 1 root root 1, 3 May 24 13:29 /dev/null\n received\n %s\n", out)
  1016. }
  1017. }
  1018. func (s *DockerSuite) TestRunThatCharacterDevicesActLikeCharacterDevices(c *check.C) {
  1019. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero")
  1020. out, _, err := runCommandWithOutput(cmd)
  1021. if err != nil {
  1022. c.Fatal(err, out)
  1023. }
  1024. if actual := strings.Trim(out, "\r\n"); actual[0] == '0' {
  1025. c.Fatalf("expected a new file called /zero to be create that is greater than 0 bytes long, but du says: %s", actual)
  1026. }
  1027. }
  1028. func (s *DockerSuite) TestRunUnprivilegedWithChroot(c *check.C) {
  1029. cmd := exec.Command(dockerBinary, "run", "busybox", "chroot", "/", "true")
  1030. if _, err := runCommand(cmd); err != nil {
  1031. c.Fatal(err)
  1032. }
  1033. }
  1034. func (s *DockerSuite) TestRunAddingOptionalDevices(c *check.C) {
  1035. cmd := exec.Command(dockerBinary, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo")
  1036. out, _, err := runCommandWithOutput(cmd)
  1037. if err != nil {
  1038. c.Fatal(err, out)
  1039. }
  1040. if actual := strings.Trim(out, "\r\n"); actual != "/dev/nulo" {
  1041. c.Fatalf("expected output /dev/nulo, received %s", actual)
  1042. }
  1043. }
  1044. func (s *DockerSuite) TestRunModeHostname(c *check.C) {
  1045. testRequires(c, SameHostDaemon)
  1046. cmd := exec.Command(dockerBinary, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname")
  1047. out, _, err := runCommandWithOutput(cmd)
  1048. if err != nil {
  1049. c.Fatal(err, out)
  1050. }
  1051. if actual := strings.Trim(out, "\r\n"); actual != "testhostname" {
  1052. c.Fatalf("expected 'testhostname', but says: %q", actual)
  1053. }
  1054. cmd = exec.Command(dockerBinary, "run", "--net=host", "busybox", "cat", "/etc/hostname")
  1055. out, _, err = runCommandWithOutput(cmd)
  1056. if err != nil {
  1057. c.Fatal(err, out)
  1058. }
  1059. hostname, err := os.Hostname()
  1060. if err != nil {
  1061. c.Fatal(err)
  1062. }
  1063. if actual := strings.Trim(out, "\r\n"); actual != hostname {
  1064. c.Fatalf("expected %q, but says: %q", hostname, actual)
  1065. }
  1066. }
  1067. func (s *DockerSuite) TestRunRootWorkdir(c *check.C) {
  1068. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--workdir", "/", "busybox", "pwd"))
  1069. if err != nil {
  1070. c.Fatalf("Failed with errors: %s, %v", out, err)
  1071. }
  1072. if out != "/\n" {
  1073. c.Fatalf("pwd returned %q (expected /\\n)", s)
  1074. }
  1075. }
  1076. func (s *DockerSuite) TestRunAllowBindMountingRoot(c *check.C) {
  1077. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-v", "/:/host", "busybox", "ls", "/host"))
  1078. if err != nil {
  1079. c.Fatalf("Failed with errors: %s, %v", out, err)
  1080. }
  1081. }
  1082. func (s *DockerSuite) TestRunDisallowBindMountingRootToRoot(c *check.C) {
  1083. cmd := exec.Command(dockerBinary, "run", "-v", "/:/", "busybox", "ls", "/host")
  1084. out, _, err := runCommandWithOutput(cmd)
  1085. if err == nil {
  1086. c.Fatal(out, err)
  1087. }
  1088. }
  1089. // Verify that a container gets default DNS when only localhost resolvers exist
  1090. func (s *DockerSuite) TestRunDnsDefaultOptions(c *check.C) {
  1091. testRequires(c, SameHostDaemon)
  1092. // preserve original resolv.conf for restoring after test
  1093. origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  1094. if os.IsNotExist(err) {
  1095. c.Fatalf("/etc/resolv.conf does not exist")
  1096. }
  1097. // defer restored original conf
  1098. defer func() {
  1099. if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil {
  1100. c.Fatal(err)
  1101. }
  1102. }()
  1103. // test 3 cases: standard IPv4 localhost, commented out localhost, and IPv6 localhost
  1104. // 2 are removed from the file at container start, and the 3rd (commented out) one is ignored by
  1105. // GetNameservers(), leading to a replacement of nameservers with the default set
  1106. tmpResolvConf := []byte("nameserver 127.0.0.1\n#nameserver 127.0.2.1\nnameserver ::1")
  1107. if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
  1108. c.Fatal(err)
  1109. }
  1110. cmd := exec.Command(dockerBinary, "run", "busybox", "cat", "/etc/resolv.conf")
  1111. actual, _, err := runCommandWithOutput(cmd)
  1112. if err != nil {
  1113. c.Fatal(err, actual)
  1114. }
  1115. // check that the actual defaults are appended to the commented out
  1116. // localhost resolver (which should be preserved)
  1117. // NOTE: if we ever change the defaults from google dns, this will break
  1118. expected := "#nameserver 127.0.2.1\n\nnameserver 8.8.8.8\nnameserver 8.8.4.4"
  1119. if actual != expected {
  1120. c.Fatalf("expected resolv.conf be: %q, but was: %q", expected, actual)
  1121. }
  1122. }
  1123. func (s *DockerSuite) TestRunDnsOptions(c *check.C) {
  1124. cmd := exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
  1125. out, stderr, _, err := runCommandWithStdoutStderr(cmd)
  1126. if err != nil {
  1127. c.Fatal(err, out)
  1128. }
  1129. // The client will get a warning on stderr when setting DNS to a localhost address; verify this:
  1130. if !strings.Contains(stderr, "Localhost DNS setting") {
  1131. c.Fatalf("Expected warning on stderr about localhost resolver, but got %q", stderr)
  1132. }
  1133. actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1)
  1134. if actual != "nameserver 127.0.0.1 search mydomain" {
  1135. c.Fatalf("expected 'nameserver 127.0.0.1 search mydomain', but says: %q", actual)
  1136. }
  1137. cmd = exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "--dns-search=.", "busybox", "cat", "/etc/resolv.conf")
  1138. out, _, _, err = runCommandWithStdoutStderr(cmd)
  1139. if err != nil {
  1140. c.Fatal(err, out)
  1141. }
  1142. actual = strings.Replace(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ", -1)
  1143. if actual != "nameserver 127.0.0.1" {
  1144. c.Fatalf("expected 'nameserver 127.0.0.1', but says: %q", actual)
  1145. }
  1146. }
  1147. func (s *DockerSuite) TestRunDnsOptionsBasedOnHostResolvConf(c *check.C) {
  1148. testRequires(c, SameHostDaemon)
  1149. origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  1150. if os.IsNotExist(err) {
  1151. c.Fatalf("/etc/resolv.conf does not exist")
  1152. }
  1153. hostNamservers := resolvconf.GetNameservers(origResolvConf)
  1154. hostSearch := resolvconf.GetSearchDomains(origResolvConf)
  1155. var out string
  1156. cmd := exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf")
  1157. if out, _, _, err = runCommandWithStdoutStderr(cmd); err != nil {
  1158. c.Fatal(err, out)
  1159. }
  1160. if actualNameservers := resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "127.0.0.1" {
  1161. c.Fatalf("expected '127.0.0.1', but says: %q", string(actualNameservers[0]))
  1162. }
  1163. actualSearch := resolvconf.GetSearchDomains([]byte(out))
  1164. if len(actualSearch) != len(hostSearch) {
  1165. c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch))
  1166. }
  1167. for i := range actualSearch {
  1168. if actualSearch[i] != hostSearch[i] {
  1169. c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i])
  1170. }
  1171. }
  1172. cmd = exec.Command(dockerBinary, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
  1173. if out, _, err = runCommandWithOutput(cmd); err != nil {
  1174. c.Fatal(err, out)
  1175. }
  1176. actualNameservers := resolvconf.GetNameservers([]byte(out))
  1177. if len(actualNameservers) != len(hostNamservers) {
  1178. c.Fatalf("expected %q nameserver(s), but it has: %q", len(hostNamservers), len(actualNameservers))
  1179. }
  1180. for i := range actualNameservers {
  1181. if actualNameservers[i] != hostNamservers[i] {
  1182. c.Fatalf("expected %q nameserver, but says: %q", actualNameservers[i], hostNamservers[i])
  1183. }
  1184. }
  1185. if actualSearch = resolvconf.GetSearchDomains([]byte(out)); string(actualSearch[0]) != "mydomain" {
  1186. c.Fatalf("expected 'mydomain', but says: %q", string(actualSearch[0]))
  1187. }
  1188. // test with file
  1189. tmpResolvConf := []byte("search example.com\nnameserver 12.34.56.78\nnameserver 127.0.0.1")
  1190. if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
  1191. c.Fatal(err)
  1192. }
  1193. // put the old resolvconf back
  1194. defer func() {
  1195. if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil {
  1196. c.Fatal(err)
  1197. }
  1198. }()
  1199. resolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  1200. if os.IsNotExist(err) {
  1201. c.Fatalf("/etc/resolv.conf does not exist")
  1202. }
  1203. hostNamservers = resolvconf.GetNameservers(resolvConf)
  1204. hostSearch = resolvconf.GetSearchDomains(resolvConf)
  1205. cmd = exec.Command(dockerBinary, "run", "busybox", "cat", "/etc/resolv.conf")
  1206. if out, _, err = runCommandWithOutput(cmd); err != nil {
  1207. c.Fatal(err, out)
  1208. }
  1209. if actualNameservers = resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "12.34.56.78" || len(actualNameservers) != 1 {
  1210. c.Fatalf("expected '12.34.56.78', but has: %v", actualNameservers)
  1211. }
  1212. actualSearch = resolvconf.GetSearchDomains([]byte(out))
  1213. if len(actualSearch) != len(hostSearch) {
  1214. c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch))
  1215. }
  1216. for i := range actualSearch {
  1217. if actualSearch[i] != hostSearch[i] {
  1218. c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i])
  1219. }
  1220. }
  1221. }
  1222. // Test the file watch notifier on docker host's /etc/resolv.conf
  1223. // A go-routine is responsible for auto-updating containers which are
  1224. // stopped and have an unmodified copy of resolv.conf, as well as
  1225. // marking running containers as requiring an update on next restart
  1226. func (s *DockerSuite) TestRunResolvconfUpdater(c *check.C) {
  1227. // Because overlay doesn't support inotify properly, we need to skip
  1228. // this test if the docker daemon has Storage Driver == overlay
  1229. testRequires(c, SameHostDaemon, NotOverlay)
  1230. tmpResolvConf := []byte("search pommesfrites.fr\nnameserver 12.34.56.78")
  1231. tmpLocalhostResolvConf := []byte("nameserver 127.0.0.1")
  1232. //take a copy of resolv.conf for restoring after test completes
  1233. resolvConfSystem, err := ioutil.ReadFile("/etc/resolv.conf")
  1234. if err != nil {
  1235. c.Fatal(err)
  1236. }
  1237. // This test case is meant to test monitoring resolv.conf when it is
  1238. // a regular file not a bind mounc. So we unmount resolv.conf and replace
  1239. // it with a file containing the original settings.
  1240. cmd := exec.Command("umount", "/etc/resolv.conf")
  1241. if _, err = runCommand(cmd); err != nil {
  1242. c.Fatal(err)
  1243. }
  1244. //cleanup
  1245. defer func() {
  1246. if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1247. c.Fatal(err)
  1248. }
  1249. }()
  1250. //1. test that a non-running container gets an updated resolv.conf
  1251. cmd = exec.Command(dockerBinary, "run", "--name='first'", "busybox", "true")
  1252. if _, err := runCommand(cmd); err != nil {
  1253. c.Fatal(err)
  1254. }
  1255. containerID1, err := getIDByName("first")
  1256. if err != nil {
  1257. c.Fatal(err)
  1258. }
  1259. // replace resolv.conf with our temporary copy
  1260. bytesResolvConf := []byte(tmpResolvConf)
  1261. if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  1262. c.Fatal(err)
  1263. }
  1264. time.Sleep(time.Second / 2)
  1265. // check for update in container
  1266. containerResolv, err := readContainerFile(containerID1, "resolv.conf")
  1267. if err != nil {
  1268. c.Fatal(err)
  1269. }
  1270. if !bytes.Equal(containerResolv, bytesResolvConf) {
  1271. c.Fatalf("Stopped container does not have updated resolv.conf; expected %q, got %q", tmpResolvConf, string(containerResolv))
  1272. }
  1273. //2. test that a non-running container does not receive resolv.conf updates
  1274. // if it modified the container copy of the starting point resolv.conf
  1275. cmd = exec.Command(dockerBinary, "run", "--name='second'", "busybox", "sh", "-c", "echo 'search mylittlepony.com' >>/etc/resolv.conf")
  1276. if _, err = runCommand(cmd); err != nil {
  1277. c.Fatal(err)
  1278. }
  1279. containerID2, err := getIDByName("second")
  1280. if err != nil {
  1281. c.Fatal(err)
  1282. }
  1283. containerResolvHashBefore, err := readContainerFile(containerID2, "resolv.conf.hash")
  1284. if err != nil {
  1285. c.Fatal(err)
  1286. }
  1287. //make a change to resolv.conf (in this case replacing our tmp copy with orig copy)
  1288. if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1289. c.Fatal(err)
  1290. }
  1291. time.Sleep(time.Second / 2)
  1292. containerResolvHashAfter, err := readContainerFile(containerID2, "resolv.conf.hash")
  1293. if err != nil {
  1294. c.Fatal(err)
  1295. }
  1296. if !bytes.Equal(containerResolvHashBefore, containerResolvHashAfter) {
  1297. c.Fatalf("Stopped container with modified resolv.conf should not have been updated; expected hash: %v, new hash: %v", containerResolvHashBefore, containerResolvHashAfter)
  1298. }
  1299. //3. test that a running container's resolv.conf is not modified while running
  1300. cmd = exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  1301. out, _, err := runCommandWithOutput(cmd)
  1302. if err != nil {
  1303. c.Fatal(err)
  1304. }
  1305. runningContainerID := strings.TrimSpace(out)
  1306. containerResolvHashBefore, err = readContainerFile(runningContainerID, "resolv.conf.hash")
  1307. if err != nil {
  1308. c.Fatal(err)
  1309. }
  1310. // replace resolv.conf
  1311. if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  1312. c.Fatal(err)
  1313. }
  1314. // make sure the updater has time to run to validate we really aren't
  1315. // getting updated
  1316. time.Sleep(time.Second / 2)
  1317. containerResolvHashAfter, err = readContainerFile(runningContainerID, "resolv.conf.hash")
  1318. if err != nil {
  1319. c.Fatal(err)
  1320. }
  1321. if !bytes.Equal(containerResolvHashBefore, containerResolvHashAfter) {
  1322. c.Fatalf("Running container's resolv.conf should not be updated; expected hash: %v, new hash: %v", containerResolvHashBefore, containerResolvHashAfter)
  1323. }
  1324. //4. test that a running container's resolv.conf is updated upon restart
  1325. // (the above container is still running..)
  1326. cmd = exec.Command(dockerBinary, "restart", runningContainerID)
  1327. if _, err = runCommand(cmd); err != nil {
  1328. c.Fatal(err)
  1329. }
  1330. // check for update in container
  1331. containerResolv, err = readContainerFile(runningContainerID, "resolv.conf")
  1332. if err != nil {
  1333. c.Fatal(err)
  1334. }
  1335. if !bytes.Equal(containerResolv, bytesResolvConf) {
  1336. c.Fatalf("Restarted container should have updated resolv.conf; expected %q, got %q", tmpResolvConf, string(containerResolv))
  1337. }
  1338. //5. test that additions of a localhost resolver are cleaned from
  1339. // host resolv.conf before updating container's resolv.conf copies
  1340. // replace resolv.conf with a localhost-only nameserver copy
  1341. bytesResolvConf = []byte(tmpLocalhostResolvConf)
  1342. if err = ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  1343. c.Fatal(err)
  1344. }
  1345. time.Sleep(time.Second / 2)
  1346. // our first exited container ID should have been updated, but with default DNS
  1347. // after the cleanup of resolv.conf found only a localhost nameserver:
  1348. containerResolv, err = readContainerFile(containerID1, "resolv.conf")
  1349. if err != nil {
  1350. c.Fatal(err)
  1351. }
  1352. expected := "\nnameserver 8.8.8.8\nnameserver 8.8.4.4"
  1353. if !bytes.Equal(containerResolv, []byte(expected)) {
  1354. c.Fatalf("Container does not have cleaned/replaced DNS in resolv.conf; expected %q, got %q", expected, string(containerResolv))
  1355. }
  1356. //6. Test that replacing (as opposed to modifying) resolv.conf triggers an update
  1357. // of containers' resolv.conf.
  1358. // Restore the original resolv.conf
  1359. if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1360. c.Fatal(err)
  1361. }
  1362. // Run the container so it picks up the old settings
  1363. cmd = exec.Command(dockerBinary, "run", "--name='third'", "busybox", "true")
  1364. if _, err := runCommand(cmd); err != nil {
  1365. c.Fatal(err)
  1366. }
  1367. containerID3, err := getIDByName("third")
  1368. if err != nil {
  1369. c.Fatal(err)
  1370. }
  1371. // Create a modified resolv.conf.aside and override resolv.conf with it
  1372. bytesResolvConf = []byte(tmpResolvConf)
  1373. if err := ioutil.WriteFile("/etc/resolv.conf.aside", bytesResolvConf, 0644); err != nil {
  1374. c.Fatal(err)
  1375. }
  1376. err = os.Rename("/etc/resolv.conf.aside", "/etc/resolv.conf")
  1377. if err != nil {
  1378. c.Fatal(err)
  1379. }
  1380. time.Sleep(time.Second / 2)
  1381. // check for update in container
  1382. containerResolv, err = readContainerFile(containerID3, "resolv.conf")
  1383. if err != nil {
  1384. c.Fatal(err)
  1385. }
  1386. if !bytes.Equal(containerResolv, bytesResolvConf) {
  1387. c.Fatalf("Stopped container does not have updated resolv.conf; expected\n%q\n got\n%q", tmpResolvConf, string(containerResolv))
  1388. }
  1389. //cleanup, restore original resolv.conf happens in defer func()
  1390. }
  1391. func (s *DockerSuite) TestRunAddHost(c *check.C) {
  1392. cmd := exec.Command(dockerBinary, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts")
  1393. out, _, err := runCommandWithOutput(cmd)
  1394. if err != nil {
  1395. c.Fatal(err, out)
  1396. }
  1397. actual := strings.Trim(out, "\r\n")
  1398. if actual != "86.75.30.9\textra" {
  1399. c.Fatalf("expected '86.75.30.9\textra', but says: %q", actual)
  1400. }
  1401. }
  1402. // Regression test for #6983
  1403. func (s *DockerSuite) TestRunAttachStdErrOnlyTTYMode(c *check.C) {
  1404. cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stderr", "busybox", "true")
  1405. exitCode, err := runCommand(cmd)
  1406. if err != nil {
  1407. c.Fatal(err)
  1408. } else if exitCode != 0 {
  1409. c.Fatalf("Container should have exited with error code 0")
  1410. }
  1411. }
  1412. // Regression test for #6983
  1413. func (s *DockerSuite) TestRunAttachStdOutOnlyTTYMode(c *check.C) {
  1414. cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stdout", "busybox", "true")
  1415. exitCode, err := runCommand(cmd)
  1416. if err != nil {
  1417. c.Fatal(err)
  1418. } else if exitCode != 0 {
  1419. c.Fatalf("Container should have exited with error code 0")
  1420. }
  1421. }
  1422. // Regression test for #6983
  1423. func (s *DockerSuite) TestRunAttachStdOutAndErrTTYMode(c *check.C) {
  1424. cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true")
  1425. exitCode, err := runCommand(cmd)
  1426. if err != nil {
  1427. c.Fatal(err)
  1428. } else if exitCode != 0 {
  1429. c.Fatalf("Container should have exited with error code 0")
  1430. }
  1431. }
  1432. // Test for #10388 - this will run the same test as TestRunAttachStdOutAndErrTTYMode
  1433. // but using --attach instead of -a to make sure we read the flag correctly
  1434. func (s *DockerSuite) TestRunAttachWithDettach(c *check.C) {
  1435. cmd := exec.Command(dockerBinary, "run", "-d", "--attach", "stdout", "busybox", "true")
  1436. _, stderr, _, err := runCommandWithStdoutStderr(cmd)
  1437. if err == nil {
  1438. c.Fatal("Container should have exited with error code different than 0")
  1439. } else if !strings.Contains(stderr, "Conflicting options: -a and -d") {
  1440. c.Fatal("Should have been returned an error with conflicting options -a and -d")
  1441. }
  1442. }
  1443. func (s *DockerSuite) TestRunState(c *check.C) {
  1444. cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  1445. out, _, err := runCommandWithOutput(cmd)
  1446. if err != nil {
  1447. c.Fatal(err, out)
  1448. }
  1449. id := strings.TrimSpace(out)
  1450. state, err := inspectField(id, "State.Running")
  1451. if err != nil {
  1452. c.Fatal(err)
  1453. }
  1454. if state != "true" {
  1455. c.Fatal("Container state is 'not running'")
  1456. }
  1457. pid1, err := inspectField(id, "State.Pid")
  1458. if err != nil {
  1459. c.Fatal(err)
  1460. }
  1461. if pid1 == "0" {
  1462. c.Fatal("Container state Pid 0")
  1463. }
  1464. cmd = exec.Command(dockerBinary, "stop", id)
  1465. out, _, err = runCommandWithOutput(cmd)
  1466. if err != nil {
  1467. c.Fatal(err, out)
  1468. }
  1469. state, err = inspectField(id, "State.Running")
  1470. if err != nil {
  1471. c.Fatal(err)
  1472. }
  1473. if state != "false" {
  1474. c.Fatal("Container state is 'running'")
  1475. }
  1476. pid2, err := inspectField(id, "State.Pid")
  1477. if err != nil {
  1478. c.Fatal(err)
  1479. }
  1480. if pid2 == pid1 {
  1481. c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1482. }
  1483. cmd = exec.Command(dockerBinary, "start", id)
  1484. out, _, err = runCommandWithOutput(cmd)
  1485. if err != nil {
  1486. c.Fatal(err, out)
  1487. }
  1488. state, err = inspectField(id, "State.Running")
  1489. if err != nil {
  1490. c.Fatal(err)
  1491. }
  1492. if state != "true" {
  1493. c.Fatal("Container state is 'not running'")
  1494. }
  1495. pid3, err := inspectField(id, "State.Pid")
  1496. if err != nil {
  1497. c.Fatal(err)
  1498. }
  1499. if pid3 == pid1 {
  1500. c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1501. }
  1502. }
  1503. // Test for #1737
  1504. func (s *DockerSuite) TestRunCopyVolumeUidGid(c *check.C) {
  1505. name := "testrunvolumesuidgid"
  1506. _, err := buildImage(name,
  1507. `FROM busybox
  1508. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1509. RUN echo 'dockerio:x:1001:' >> /etc/group
  1510. RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`,
  1511. true)
  1512. if err != nil {
  1513. c.Fatal(err)
  1514. }
  1515. // Test that the uid and gid is copied from the image to the volume
  1516. cmd := exec.Command(dockerBinary, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'")
  1517. out, _, err := runCommandWithOutput(cmd)
  1518. if err != nil {
  1519. c.Fatal(err, out)
  1520. }
  1521. out = strings.TrimSpace(out)
  1522. if out != "dockerio:dockerio" {
  1523. c.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out)
  1524. }
  1525. }
  1526. // Test for #1582
  1527. func (s *DockerSuite) TestRunCopyVolumeContent(c *check.C) {
  1528. name := "testruncopyvolumecontent"
  1529. _, err := buildImage(name,
  1530. `FROM busybox
  1531. RUN mkdir -p /hello/local && echo hello > /hello/local/world`,
  1532. true)
  1533. if err != nil {
  1534. c.Fatal(err)
  1535. }
  1536. // Test that the content is copied from the image to the volume
  1537. cmd := exec.Command(dockerBinary, "run", "--rm", "-v", "/hello", name, "find", "/hello")
  1538. out, _, err := runCommandWithOutput(cmd)
  1539. if err != nil {
  1540. c.Fatal(err, out)
  1541. }
  1542. if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) {
  1543. c.Fatal("Container failed to transfer content to volume")
  1544. }
  1545. }
  1546. func (s *DockerSuite) TestRunCleanupCmdOnEntrypoint(c *check.C) {
  1547. name := "testrunmdcleanuponentrypoint"
  1548. if _, err := buildImage(name,
  1549. `FROM busybox
  1550. ENTRYPOINT ["echo"]
  1551. CMD ["testingpoint"]`,
  1552. true); err != nil {
  1553. c.Fatal(err)
  1554. }
  1555. runCmd := exec.Command(dockerBinary, "run", "--entrypoint", "whoami", name)
  1556. out, exit, err := runCommandWithOutput(runCmd)
  1557. if err != nil {
  1558. c.Fatalf("Error: %v, out: %q", err, out)
  1559. }
  1560. if exit != 0 {
  1561. c.Fatalf("expected exit code 0 received %d, out: %q", exit, out)
  1562. }
  1563. out = strings.TrimSpace(out)
  1564. if out != "root" {
  1565. c.Fatalf("Expected output root, got %q", out)
  1566. }
  1567. }
  1568. // TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected
  1569. func (s *DockerSuite) TestRunWorkdirExistsAndIsFile(c *check.C) {
  1570. runCmd := exec.Command(dockerBinary, "run", "-w", "/bin/cat", "busybox")
  1571. out, exit, err := runCommandWithOutput(runCmd)
  1572. if !(err != nil && exit == 1 && strings.Contains(out, "Cannot mkdir: /bin/cat is not a directory")) {
  1573. c.Fatalf("Docker must complains about making dir, but we got out: %s, exit: %d, err: %s", out, exit, err)
  1574. }
  1575. }
  1576. func (s *DockerSuite) TestRunExitOnStdinClose(c *check.C) {
  1577. name := "testrunexitonstdinclose"
  1578. runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", "/bin/cat")
  1579. stdin, err := runCmd.StdinPipe()
  1580. if err != nil {
  1581. c.Fatal(err)
  1582. }
  1583. stdout, err := runCmd.StdoutPipe()
  1584. if err != nil {
  1585. c.Fatal(err)
  1586. }
  1587. if err := runCmd.Start(); err != nil {
  1588. c.Fatal(err)
  1589. }
  1590. if _, err := stdin.Write([]byte("hello\n")); err != nil {
  1591. c.Fatal(err)
  1592. }
  1593. r := bufio.NewReader(stdout)
  1594. line, err := r.ReadString('\n')
  1595. if err != nil {
  1596. c.Fatal(err)
  1597. }
  1598. line = strings.TrimSpace(line)
  1599. if line != "hello" {
  1600. c.Fatalf("Output should be 'hello', got '%q'", line)
  1601. }
  1602. if err := stdin.Close(); err != nil {
  1603. c.Fatal(err)
  1604. }
  1605. finish := make(chan error)
  1606. go func() {
  1607. finish <- runCmd.Wait()
  1608. close(finish)
  1609. }()
  1610. select {
  1611. case err := <-finish:
  1612. c.Assert(err, check.IsNil)
  1613. case <-time.After(1 * time.Second):
  1614. c.Fatal("docker run failed to exit on stdin close")
  1615. }
  1616. state, err := inspectField(name, "State.Running")
  1617. c.Assert(err, check.IsNil)
  1618. if state != "false" {
  1619. c.Fatal("Container must be stopped after stdin closing")
  1620. }
  1621. }
  1622. // Test for #2267
  1623. func (s *DockerSuite) TestRunWriteHostsFileAndNotCommit(c *check.C) {
  1624. name := "writehosts"
  1625. cmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hosts && cat /etc/hosts")
  1626. out, _, err := runCommandWithOutput(cmd)
  1627. if err != nil {
  1628. c.Fatal(err, out)
  1629. }
  1630. if !strings.Contains(out, "test2267") {
  1631. c.Fatal("/etc/hosts should contain 'test2267'")
  1632. }
  1633. cmd = exec.Command(dockerBinary, "diff", name)
  1634. if err != nil {
  1635. c.Fatal(err, out)
  1636. }
  1637. out, _, err = runCommandWithOutput(cmd)
  1638. if err != nil {
  1639. c.Fatal(err, out)
  1640. }
  1641. if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1642. c.Fatal("diff should be empty")
  1643. }
  1644. }
  1645. func eqToBaseDiff(out string, c *check.C) bool {
  1646. cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "echo", "hello")
  1647. out1, _, err := runCommandWithOutput(cmd)
  1648. cID := strings.TrimSpace(out1)
  1649. cmd = exec.Command(dockerBinary, "diff", cID)
  1650. baseDiff, _, err := runCommandWithOutput(cmd)
  1651. if err != nil {
  1652. c.Fatal(err, baseDiff)
  1653. }
  1654. baseArr := strings.Split(baseDiff, "\n")
  1655. sort.Strings(baseArr)
  1656. outArr := strings.Split(out, "\n")
  1657. sort.Strings(outArr)
  1658. return sliceEq(baseArr, outArr)
  1659. }
  1660. func sliceEq(a, b []string) bool {
  1661. if len(a) != len(b) {
  1662. return false
  1663. }
  1664. for i := range a {
  1665. if a[i] != b[i] {
  1666. return false
  1667. }
  1668. }
  1669. return true
  1670. }
  1671. // Test for #2267
  1672. func (s *DockerSuite) TestRunWriteHostnameFileAndNotCommit(c *check.C) {
  1673. name := "writehostname"
  1674. cmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hostname && cat /etc/hostname")
  1675. out, _, err := runCommandWithOutput(cmd)
  1676. if err != nil {
  1677. c.Fatal(err, out)
  1678. }
  1679. if !strings.Contains(out, "test2267") {
  1680. c.Fatal("/etc/hostname should contain 'test2267'")
  1681. }
  1682. cmd = exec.Command(dockerBinary, "diff", name)
  1683. if err != nil {
  1684. c.Fatal(err, out)
  1685. }
  1686. out, _, err = runCommandWithOutput(cmd)
  1687. if err != nil {
  1688. c.Fatal(err, out)
  1689. }
  1690. if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1691. c.Fatal("diff should be empty")
  1692. }
  1693. }
  1694. // Test for #2267
  1695. func (s *DockerSuite) TestRunWriteResolvFileAndNotCommit(c *check.C) {
  1696. name := "writeresolv"
  1697. cmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/resolv.conf && cat /etc/resolv.conf")
  1698. out, _, err := runCommandWithOutput(cmd)
  1699. if err != nil {
  1700. c.Fatal(err, out)
  1701. }
  1702. if !strings.Contains(out, "test2267") {
  1703. c.Fatal("/etc/resolv.conf should contain 'test2267'")
  1704. }
  1705. cmd = exec.Command(dockerBinary, "diff", name)
  1706. if err != nil {
  1707. c.Fatal(err, out)
  1708. }
  1709. out, _, err = runCommandWithOutput(cmd)
  1710. if err != nil {
  1711. c.Fatal(err, out)
  1712. }
  1713. if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1714. c.Fatal("diff should be empty")
  1715. }
  1716. }
  1717. func (s *DockerSuite) TestRunWithBadDevice(c *check.C) {
  1718. name := "baddevice"
  1719. cmd := exec.Command(dockerBinary, "run", "--name", name, "--device", "/etc", "busybox", "true")
  1720. out, _, err := runCommandWithOutput(cmd)
  1721. if err == nil {
  1722. c.Fatal("Run should fail with bad device")
  1723. }
  1724. expected := `\"/etc\": not a device node`
  1725. if !strings.Contains(out, expected) {
  1726. c.Fatalf("Output should contain %q, actual out: %q", expected, out)
  1727. }
  1728. }
  1729. func (s *DockerSuite) TestRunEntrypoint(c *check.C) {
  1730. name := "entrypoint"
  1731. cmd := exec.Command(dockerBinary, "run", "--name", name, "--entrypoint", "/bin/echo", "busybox", "-n", "foobar")
  1732. out, _, err := runCommandWithOutput(cmd)
  1733. if err != nil {
  1734. c.Fatal(err, out)
  1735. }
  1736. expected := "foobar"
  1737. if out != expected {
  1738. c.Fatalf("Output should be %q, actual out: %q", expected, out)
  1739. }
  1740. }
  1741. func (s *DockerSuite) TestRunBindMounts(c *check.C) {
  1742. testRequires(c, SameHostDaemon)
  1743. tmpDir, err := ioutil.TempDir("", "docker-test-container")
  1744. if err != nil {
  1745. c.Fatal(err)
  1746. }
  1747. defer os.RemoveAll(tmpDir)
  1748. writeFile(path.Join(tmpDir, "touch-me"), "", c)
  1749. // Test reading from a read-only bind mount
  1750. cmd := exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox", "ls", "/tmp")
  1751. out, _, err := runCommandWithOutput(cmd)
  1752. if err != nil {
  1753. c.Fatal(err, out)
  1754. }
  1755. if !strings.Contains(out, "touch-me") {
  1756. c.Fatal("Container failed to read from bind mount")
  1757. }
  1758. // test writing to bind mount
  1759. cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla")
  1760. out, _, err = runCommandWithOutput(cmd)
  1761. if err != nil {
  1762. c.Fatal(err, out)
  1763. }
  1764. readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist
  1765. // test mounting to an illegal destination directory
  1766. cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:.", tmpDir), "busybox", "ls", ".")
  1767. _, err = runCommand(cmd)
  1768. if err == nil {
  1769. c.Fatal("Container bind mounted illegal directory")
  1770. }
  1771. // test mount a file
  1772. cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla")
  1773. _, err = runCommand(cmd)
  1774. if err != nil {
  1775. c.Fatal(err, out)
  1776. }
  1777. content := readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist
  1778. expected := "yotta"
  1779. if content != expected {
  1780. c.Fatalf("Output should be %q, actual out: %q", expected, content)
  1781. }
  1782. }
  1783. // Ensure that CIDFile gets deleted if it's empty
  1784. // Perform this test by making `docker run` fail
  1785. func (s *DockerSuite) TestRunCidFileCleanupIfEmpty(c *check.C) {
  1786. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1787. if err != nil {
  1788. c.Fatal(err)
  1789. }
  1790. defer os.RemoveAll(tmpDir)
  1791. tmpCidFile := path.Join(tmpDir, "cid")
  1792. cmd := exec.Command(dockerBinary, "run", "--cidfile", tmpCidFile, "emptyfs")
  1793. out, _, err := runCommandWithOutput(cmd)
  1794. if err == nil {
  1795. c.Fatalf("Run without command must fail. out=%s", out)
  1796. } else if !strings.Contains(out, "No command specified") {
  1797. c.Fatalf("Run without command failed with wrong output. out=%s\nerr=%v", out, err)
  1798. }
  1799. if _, err := os.Stat(tmpCidFile); err == nil {
  1800. c.Fatalf("empty CIDFile %q should've been deleted", tmpCidFile)
  1801. }
  1802. }
  1803. // #2098 - Docker cidFiles only contain short version of the containerId
  1804. //sudo docker run --cidfile /tmp/docker_tesc.cid ubuntu echo "test"
  1805. // TestRunCidFile tests that run --cidfile returns the longid
  1806. func (s *DockerSuite) TestRunCidFileCheckIDLength(c *check.C) {
  1807. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1808. if err != nil {
  1809. c.Fatal(err)
  1810. }
  1811. tmpCidFile := path.Join(tmpDir, "cid")
  1812. defer os.RemoveAll(tmpDir)
  1813. cmd := exec.Command(dockerBinary, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true")
  1814. out, _, err := runCommandWithOutput(cmd)
  1815. if err != nil {
  1816. c.Fatal(err)
  1817. }
  1818. id := strings.TrimSpace(out)
  1819. buffer, err := ioutil.ReadFile(tmpCidFile)
  1820. if err != nil {
  1821. c.Fatal(err)
  1822. }
  1823. cid := string(buffer)
  1824. if len(cid) != 64 {
  1825. c.Fatalf("--cidfile should be a long id, not %q", id)
  1826. }
  1827. if cid != id {
  1828. c.Fatalf("cid must be equal to %s, got %s", id, cid)
  1829. }
  1830. }
  1831. func (s *DockerSuite) TestRunNetworkNotInitializedNoneMode(c *check.C) {
  1832. cmd := exec.Command(dockerBinary, "run", "-d", "--net=none", "busybox", "top")
  1833. out, _, err := runCommandWithOutput(cmd)
  1834. if err != nil {
  1835. c.Fatal(err)
  1836. }
  1837. id := strings.TrimSpace(out)
  1838. res, err := inspectField(id, "NetworkSettings.IPAddress")
  1839. if err != nil {
  1840. c.Fatal(err)
  1841. }
  1842. if res != "" {
  1843. c.Fatalf("For 'none' mode network must not be initialized, but container got IP: %s", res)
  1844. }
  1845. }
  1846. func (s *DockerSuite) TestRunSetMacAddress(c *check.C) {
  1847. mac := "12:34:56:78:9a:bc"
  1848. cmd := exec.Command(dockerBinary, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "/bin/sh", "-c", "ip link show eth0 | tail -1 | awk '{print $2}'")
  1849. out, ec, err := runCommandWithOutput(cmd)
  1850. if err != nil {
  1851. c.Fatalf("exec failed:\nexit code=%v\noutput=%s", ec, out)
  1852. }
  1853. actualMac := strings.TrimSpace(out)
  1854. if actualMac != mac {
  1855. c.Fatalf("Set MAC address with --mac-address failed. The container has an incorrect MAC address: %q, expected: %q", actualMac, mac)
  1856. }
  1857. }
  1858. func (s *DockerSuite) TestRunInspectMacAddress(c *check.C) {
  1859. mac := "12:34:56:78:9a:bc"
  1860. cmd := exec.Command(dockerBinary, "run", "-d", "--mac-address="+mac, "busybox", "top")
  1861. out, _, err := runCommandWithOutput(cmd)
  1862. if err != nil {
  1863. c.Fatal(err)
  1864. }
  1865. id := strings.TrimSpace(out)
  1866. inspectedMac, err := inspectField(id, "NetworkSettings.MacAddress")
  1867. if err != nil {
  1868. c.Fatal(err)
  1869. }
  1870. if inspectedMac != mac {
  1871. c.Fatalf("docker inspect outputs wrong MAC address: %q, should be: %q", inspectedMac, mac)
  1872. }
  1873. }
  1874. // test docker run use a invalid mac address
  1875. func (s *DockerSuite) TestRunWithInvalidMacAddress(c *check.C) {
  1876. runCmd := exec.Command(dockerBinary, "run", "--mac-address", "92:d0:c6:0a:29", "busybox")
  1877. out, _, err := runCommandWithOutput(runCmd)
  1878. //use a invalid mac address should with a error out
  1879. if err == nil || !strings.Contains(out, "is not a valid mac address") {
  1880. c.Fatalf("run with an invalid --mac-address should with error out")
  1881. }
  1882. }
  1883. func (s *DockerSuite) TestRunDeallocatePortOnMissingIptablesRule(c *check.C) {
  1884. testRequires(c, SameHostDaemon)
  1885. cmd := exec.Command(dockerBinary, "run", "-d", "-p", "23:23", "busybox", "top")
  1886. out, _, err := runCommandWithOutput(cmd)
  1887. if err != nil {
  1888. c.Fatal(err)
  1889. }
  1890. id := strings.TrimSpace(out)
  1891. ip, err := inspectField(id, "NetworkSettings.IPAddress")
  1892. if err != nil {
  1893. c.Fatal(err)
  1894. }
  1895. iptCmd := exec.Command("iptables", "-D", "DOCKER", "-d", fmt.Sprintf("%s/32", ip),
  1896. "!", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-m", "tcp", "--dport", "23", "-j", "ACCEPT")
  1897. out, _, err = runCommandWithOutput(iptCmd)
  1898. if err != nil {
  1899. c.Fatal(err, out)
  1900. }
  1901. if err := deleteContainer(id); err != nil {
  1902. c.Fatal(err)
  1903. }
  1904. cmd = exec.Command(dockerBinary, "run", "-d", "-p", "23:23", "busybox", "top")
  1905. out, _, err = runCommandWithOutput(cmd)
  1906. if err != nil {
  1907. c.Fatal(err, out)
  1908. }
  1909. }
  1910. func (s *DockerSuite) TestRunPortInUse(c *check.C) {
  1911. testRequires(c, SameHostDaemon)
  1912. port := "1234"
  1913. cmd := exec.Command(dockerBinary, "run", "-d", "-p", port+":80", "busybox", "top")
  1914. out, _, err := runCommandWithOutput(cmd)
  1915. if err != nil {
  1916. c.Fatalf("Fail to run listening container")
  1917. }
  1918. cmd = exec.Command(dockerBinary, "run", "-d", "-p", port+":80", "busybox", "top")
  1919. out, _, err = runCommandWithOutput(cmd)
  1920. if err == nil {
  1921. c.Fatalf("Binding on used port must fail")
  1922. }
  1923. if !strings.Contains(out, "port is already allocated") {
  1924. c.Fatalf("Out must be about \"port is already allocated\", got %s", out)
  1925. }
  1926. }
  1927. // Regression test for #7792
  1928. func (s *DockerSuite) TestRunMountOrdering(c *check.C) {
  1929. testRequires(c, SameHostDaemon)
  1930. tmpDir, err := ioutil.TempDir("", "docker_nested_mount_test")
  1931. if err != nil {
  1932. c.Fatal(err)
  1933. }
  1934. defer os.RemoveAll(tmpDir)
  1935. tmpDir2, err := ioutil.TempDir("", "docker_nested_mount_test2")
  1936. if err != nil {
  1937. c.Fatal(err)
  1938. }
  1939. defer os.RemoveAll(tmpDir2)
  1940. // Create a temporary tmpfs mounc.
  1941. fooDir := filepath.Join(tmpDir, "foo")
  1942. if err := os.MkdirAll(filepath.Join(tmpDir, "foo"), 0755); err != nil {
  1943. c.Fatalf("failed to mkdir at %s - %s", fooDir, err)
  1944. }
  1945. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", fooDir), []byte{}, 0644); err != nil {
  1946. c.Fatal(err)
  1947. }
  1948. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir), []byte{}, 0644); err != nil {
  1949. c.Fatal(err)
  1950. }
  1951. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir2), []byte{}, 0644); err != nil {
  1952. c.Fatal(err)
  1953. }
  1954. cmd := exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp", tmpDir), "-v", fmt.Sprintf("%s:/tmp/foo", fooDir), "-v", fmt.Sprintf("%s:/tmp/tmp2", tmpDir2), "-v", fmt.Sprintf("%s:/tmp/tmp2/foo", fooDir), "busybox:latest", "sh", "-c", "ls /tmp/touch-me && ls /tmp/foo/touch-me && ls /tmp/tmp2/touch-me && ls /tmp/tmp2/foo/touch-me")
  1955. out, _, err := runCommandWithOutput(cmd)
  1956. if err != nil {
  1957. c.Fatal(out, err)
  1958. }
  1959. }
  1960. // Regression test for https://github.com/docker/docker/issues/8259
  1961. func (s *DockerSuite) TestRunReuseBindVolumeThatIsSymlink(c *check.C) {
  1962. testRequires(c, SameHostDaemon)
  1963. tmpDir, err := ioutil.TempDir(os.TempDir(), "testlink")
  1964. if err != nil {
  1965. c.Fatal(err)
  1966. }
  1967. defer os.RemoveAll(tmpDir)
  1968. linkPath := os.TempDir() + "/testlink2"
  1969. if err := os.Symlink(tmpDir, linkPath); err != nil {
  1970. c.Fatal(err)
  1971. }
  1972. defer os.RemoveAll(linkPath)
  1973. // Create first container
  1974. cmd := exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
  1975. if _, err := runCommand(cmd); err != nil {
  1976. c.Fatal(err)
  1977. }
  1978. // Create second container with same symlinked path
  1979. // This will fail if the referenced issue is hit with a "Volume exists" error
  1980. cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
  1981. if out, _, err := runCommandWithOutput(cmd); err != nil {
  1982. c.Fatal(err, out)
  1983. }
  1984. }
  1985. //GH#10604: Test an "/etc" volume doesn't overlay special bind mounts in container
  1986. func (s *DockerSuite) TestRunCreateVolumeEtc(c *check.C) {
  1987. cmd := exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf")
  1988. out, _, err := runCommandWithOutput(cmd)
  1989. if err != nil {
  1990. c.Fatalf("failed to run container: %v, output: %q", err, out)
  1991. }
  1992. if !strings.Contains(out, "nameserver 127.0.0.1") {
  1993. c.Fatal("/etc volume mount hides /etc/resolv.conf")
  1994. }
  1995. cmd = exec.Command(dockerBinary, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname")
  1996. out, _, err = runCommandWithOutput(cmd)
  1997. if err != nil {
  1998. c.Fatalf("failed to run container: %v, output: %q", err, out)
  1999. }
  2000. if !strings.Contains(out, "test123") {
  2001. c.Fatal("/etc volume mount hides /etc/hostname")
  2002. }
  2003. cmd = exec.Command(dockerBinary, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts")
  2004. out, _, err = runCommandWithOutput(cmd)
  2005. if err != nil {
  2006. c.Fatalf("failed to run container: %v, output: %q", err, out)
  2007. }
  2008. out = strings.Replace(out, "\n", " ", -1)
  2009. if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") {
  2010. c.Fatal("/etc volume mount hides /etc/hosts")
  2011. }
  2012. }
  2013. func (s *DockerSuite) TestVolumesNoCopyData(c *check.C) {
  2014. if _, err := buildImage("dataimage",
  2015. `FROM busybox
  2016. RUN mkdir -p /foo
  2017. RUN touch /foo/bar`,
  2018. true); err != nil {
  2019. c.Fatal(err)
  2020. }
  2021. cmd := exec.Command(dockerBinary, "run", "--name", "test", "-v", "/foo", "busybox")
  2022. if _, err := runCommand(cmd); err != nil {
  2023. c.Fatal(err)
  2024. }
  2025. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "test", "dataimage", "ls", "-lh", "/foo/bar")
  2026. if out, _, err := runCommandWithOutput(cmd); err == nil || !strings.Contains(out, "No such file or directory") {
  2027. c.Fatalf("Data was copied on volumes-from but shouldn't be:\n%q", out)
  2028. }
  2029. tmpDir := randomUnixTmpDirPath("docker_test_bind_mount_copy_data")
  2030. cmd = exec.Command(dockerBinary, "run", "-v", tmpDir+":/foo", "dataimage", "ls", "-lh", "/foo/bar")
  2031. if out, _, err := runCommandWithOutput(cmd); err == nil || !strings.Contains(out, "No such file or directory") {
  2032. c.Fatalf("Data was copied on bind-mount but shouldn't be:\n%q", out)
  2033. }
  2034. }
  2035. func (s *DockerSuite) TestRunVolumesNotRecreatedOnStart(c *check.C) {
  2036. testRequires(c, SameHostDaemon)
  2037. // Clear out any remnants from other tests
  2038. info, err := ioutil.ReadDir(volumesConfigPath)
  2039. if err != nil {
  2040. c.Fatal(err)
  2041. }
  2042. if len(info) > 0 {
  2043. for _, f := range info {
  2044. if err := os.RemoveAll(volumesConfigPath + "/" + f.Name()); err != nil {
  2045. c.Fatal(err)
  2046. }
  2047. }
  2048. }
  2049. cmd := exec.Command(dockerBinary, "run", "-v", "/foo", "--name", "lone_starr", "busybox")
  2050. if _, err := runCommand(cmd); err != nil {
  2051. c.Fatal(err)
  2052. }
  2053. cmd = exec.Command(dockerBinary, "start", "lone_starr")
  2054. if _, err := runCommand(cmd); err != nil {
  2055. c.Fatal(err)
  2056. }
  2057. info, err = ioutil.ReadDir(volumesConfigPath)
  2058. if err != nil {
  2059. c.Fatal(err)
  2060. }
  2061. if len(info) != 1 {
  2062. c.Fatalf("Expected only 1 volume have %v", len(info))
  2063. }
  2064. }
  2065. func (s *DockerSuite) TestRunNoOutputFromPullInStdout(c *check.C) {
  2066. // just run with unknown image
  2067. cmd := exec.Command(dockerBinary, "run", "asdfsg")
  2068. stdout := bytes.NewBuffer(nil)
  2069. cmd.Stdout = stdout
  2070. if err := cmd.Run(); err == nil {
  2071. c.Fatal("Run with unknown image should fail")
  2072. }
  2073. if stdout.Len() != 0 {
  2074. c.Fatalf("Stdout contains output from pull: %s", stdout)
  2075. }
  2076. }
  2077. func (s *DockerSuite) TestRunVolumesCleanPaths(c *check.C) {
  2078. if _, err := buildImage("run_volumes_clean_paths",
  2079. `FROM busybox
  2080. VOLUME /foo/`,
  2081. true); err != nil {
  2082. c.Fatal(err)
  2083. }
  2084. cmd := exec.Command(dockerBinary, "run", "-v", "/foo", "-v", "/bar/", "--name", "dark_helmet", "run_volumes_clean_paths")
  2085. if out, _, err := runCommandWithOutput(cmd); err != nil {
  2086. c.Fatal(err, out)
  2087. }
  2088. out, err := inspectFieldMap("dark_helmet", "Volumes", "/foo/")
  2089. if err != nil {
  2090. c.Fatal(err)
  2091. }
  2092. if out != "" {
  2093. c.Fatalf("Found unexpected volume entry for '/foo/' in volumes\n%q", out)
  2094. }
  2095. out, err = inspectFieldMap("dark_helmet", "Volumes", "/foo")
  2096. if err != nil {
  2097. c.Fatal(err)
  2098. }
  2099. if !strings.Contains(out, volumesStoragePath) {
  2100. c.Fatalf("Volume was not defined for /foo\n%q", out)
  2101. }
  2102. out, err = inspectFieldMap("dark_helmet", "Volumes", "/bar/")
  2103. if err != nil {
  2104. c.Fatal(err)
  2105. }
  2106. if out != "" {
  2107. c.Fatalf("Found unexpected volume entry for '/bar/' in volumes\n%q", out)
  2108. }
  2109. out, err = inspectFieldMap("dark_helmet", "Volumes", "/bar")
  2110. if err != nil {
  2111. c.Fatal(err)
  2112. }
  2113. if !strings.Contains(out, volumesStoragePath) {
  2114. c.Fatalf("Volume was not defined for /bar\n%q", out)
  2115. }
  2116. }
  2117. // Regression test for #3631
  2118. func (s *DockerSuite) TestRunSlowStdoutConsumer(c *check.C) {
  2119. cont := exec.Command(dockerBinary, "run", "--rm", "busybox", "/bin/sh", "-c", "dd if=/dev/zero of=/dev/stdout bs=1024 count=2000 | catv")
  2120. stdout, err := cont.StdoutPipe()
  2121. if err != nil {
  2122. c.Fatal(err)
  2123. }
  2124. if err := cont.Start(); err != nil {
  2125. c.Fatal(err)
  2126. }
  2127. n, err := consumeWithSpeed(stdout, 10000, 5*time.Millisecond, nil)
  2128. if err != nil {
  2129. c.Fatal(err)
  2130. }
  2131. expected := 2 * 1024 * 2000
  2132. if n != expected {
  2133. c.Fatalf("Expected %d, got %d", expected, n)
  2134. }
  2135. }
  2136. func (s *DockerSuite) TestRunAllowPortRangeThroughExpose(c *check.C) {
  2137. cmd := exec.Command(dockerBinary, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top")
  2138. out, _, err := runCommandWithOutput(cmd)
  2139. if err != nil {
  2140. c.Fatal(err)
  2141. }
  2142. id := strings.TrimSpace(out)
  2143. portstr, err := inspectFieldJSON(id, "NetworkSettings.Ports")
  2144. if err != nil {
  2145. c.Fatal(err)
  2146. }
  2147. var ports nat.PortMap
  2148. if err = unmarshalJSON([]byte(portstr), &ports); err != nil {
  2149. c.Fatal(err)
  2150. }
  2151. for port, binding := range ports {
  2152. portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  2153. if portnum < 3000 || portnum > 3003 {
  2154. c.Fatalf("Port %d is out of range ", portnum)
  2155. }
  2156. if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  2157. c.Fatalf("Port is not mapped for the port %d", port)
  2158. }
  2159. }
  2160. if err := deleteContainer(id); err != nil {
  2161. c.Fatal(err)
  2162. }
  2163. }
  2164. // test docker run expose a invalid port
  2165. func (s *DockerSuite) TestRunExposePort(c *check.C) {
  2166. runCmd := exec.Command(dockerBinary, "run", "--expose", "80000", "busybox")
  2167. out, _, err := runCommandWithOutput(runCmd)
  2168. //expose a invalid port should with a error out
  2169. if err == nil || !strings.Contains(out, "Invalid range format for --expose") {
  2170. c.Fatalf("run --expose a invalid port should with error out")
  2171. }
  2172. }
  2173. func (s *DockerSuite) TestRunUnknownCommand(c *check.C) {
  2174. testRequires(c, NativeExecDriver)
  2175. runCmd := exec.Command(dockerBinary, "create", "busybox", "/bin/nada")
  2176. cID, _, _, err := runCommandWithStdoutStderr(runCmd)
  2177. if err != nil {
  2178. c.Fatalf("Failed to create container: %v, output: %q", err, cID)
  2179. }
  2180. cID = strings.TrimSpace(cID)
  2181. runCmd = exec.Command(dockerBinary, "start", cID)
  2182. _, _, _, _ = runCommandWithStdoutStderr(runCmd)
  2183. runCmd = exec.Command(dockerBinary, "inspect", "--format={{.State.ExitCode}}", cID)
  2184. rc, _, _, err2 := runCommandWithStdoutStderr(runCmd)
  2185. rc = strings.TrimSpace(rc)
  2186. if err2 != nil {
  2187. c.Fatalf("Error getting status of container: %v", err2)
  2188. }
  2189. if rc == "0" {
  2190. c.Fatalf("ExitCode(%v) cannot be 0", rc)
  2191. }
  2192. }
  2193. func (s *DockerSuite) TestRunModeIpcHost(c *check.C) {
  2194. testRequires(c, SameHostDaemon)
  2195. hostIpc, err := os.Readlink("/proc/1/ns/ipc")
  2196. if err != nil {
  2197. c.Fatal(err)
  2198. }
  2199. cmd := exec.Command(dockerBinary, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc")
  2200. out2, _, err := runCommandWithOutput(cmd)
  2201. if err != nil {
  2202. c.Fatal(err, out2)
  2203. }
  2204. out2 = strings.Trim(out2, "\n")
  2205. if hostIpc != out2 {
  2206. c.Fatalf("IPC different with --ipc=host %s != %s\n", hostIpc, out2)
  2207. }
  2208. cmd = exec.Command(dockerBinary, "run", "busybox", "readlink", "/proc/self/ns/ipc")
  2209. out2, _, err = runCommandWithOutput(cmd)
  2210. if err != nil {
  2211. c.Fatal(err, out2)
  2212. }
  2213. out2 = strings.Trim(out2, "\n")
  2214. if hostIpc == out2 {
  2215. c.Fatalf("IPC should be different without --ipc=host %s == %s\n", hostIpc, out2)
  2216. }
  2217. }
  2218. func (s *DockerSuite) TestRunModeIpcContainer(c *check.C) {
  2219. testRequires(c, SameHostDaemon)
  2220. cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  2221. out, _, err := runCommandWithOutput(cmd)
  2222. if err != nil {
  2223. c.Fatal(err, out)
  2224. }
  2225. id := strings.TrimSpace(out)
  2226. state, err := inspectField(id, "State.Running")
  2227. if err != nil {
  2228. c.Fatal(err)
  2229. }
  2230. if state != "true" {
  2231. c.Fatal("Container state is 'not running'")
  2232. }
  2233. pid1, err := inspectField(id, "State.Pid")
  2234. if err != nil {
  2235. c.Fatal(err)
  2236. }
  2237. parentContainerIpc, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/ipc", pid1))
  2238. if err != nil {
  2239. c.Fatal(err)
  2240. }
  2241. cmd = exec.Command(dockerBinary, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "readlink", "/proc/self/ns/ipc")
  2242. out2, _, err := runCommandWithOutput(cmd)
  2243. if err != nil {
  2244. c.Fatal(err, out2)
  2245. }
  2246. out2 = strings.Trim(out2, "\n")
  2247. if parentContainerIpc != out2 {
  2248. c.Fatalf("IPC different with --ipc=container:%s %s != %s\n", id, parentContainerIpc, out2)
  2249. }
  2250. }
  2251. func (s *DockerSuite) TestRunModeIpcContainerNotExists(c *check.C) {
  2252. cmd := exec.Command(dockerBinary, "run", "-d", "--ipc", "container:abcd1234", "busybox", "top")
  2253. out, _, err := runCommandWithOutput(cmd)
  2254. if !strings.Contains(out, "abcd1234") || err == nil {
  2255. c.Fatalf("run IPC from a non exists container should with correct error out")
  2256. }
  2257. }
  2258. func (s *DockerSuite) TestContainerNetworkMode(c *check.C) {
  2259. testRequires(c, SameHostDaemon)
  2260. cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  2261. out, _, err := runCommandWithOutput(cmd)
  2262. if err != nil {
  2263. c.Fatal(err, out)
  2264. }
  2265. id := strings.TrimSpace(out)
  2266. if err := waitRun(id); err != nil {
  2267. c.Fatal(err)
  2268. }
  2269. pid1, err := inspectField(id, "State.Pid")
  2270. if err != nil {
  2271. c.Fatal(err)
  2272. }
  2273. parentContainerNet, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
  2274. if err != nil {
  2275. c.Fatal(err)
  2276. }
  2277. cmd = exec.Command(dockerBinary, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net")
  2278. out2, _, err := runCommandWithOutput(cmd)
  2279. if err != nil {
  2280. c.Fatal(err, out2)
  2281. }
  2282. out2 = strings.Trim(out2, "\n")
  2283. if parentContainerNet != out2 {
  2284. c.Fatalf("NET different with --net=container:%s %s != %s\n", id, parentContainerNet, out2)
  2285. }
  2286. }
  2287. func (s *DockerSuite) TestContainerNetworkModeToSelf(c *check.C) {
  2288. cmd := exec.Command(dockerBinary, "run", "--name=me", "--net=container:me", "busybox", "true")
  2289. out, _, err := runCommandWithOutput(cmd)
  2290. if err == nil || !strings.Contains(out, "cannot join own network") {
  2291. c.Fatalf("using container net mode to self should result in an error")
  2292. }
  2293. }
  2294. func (s *DockerSuite) TestRunModePidHost(c *check.C) {
  2295. testRequires(c, NativeExecDriver, SameHostDaemon)
  2296. hostPid, err := os.Readlink("/proc/1/ns/pid")
  2297. if err != nil {
  2298. c.Fatal(err)
  2299. }
  2300. cmd := exec.Command(dockerBinary, "run", "--pid=host", "busybox", "readlink", "/proc/self/ns/pid")
  2301. out2, _, err := runCommandWithOutput(cmd)
  2302. if err != nil {
  2303. c.Fatal(err, out2)
  2304. }
  2305. out2 = strings.Trim(out2, "\n")
  2306. if hostPid != out2 {
  2307. c.Fatalf("PID different with --pid=host %s != %s\n", hostPid, out2)
  2308. }
  2309. cmd = exec.Command(dockerBinary, "run", "busybox", "readlink", "/proc/self/ns/pid")
  2310. out2, _, err = runCommandWithOutput(cmd)
  2311. if err != nil {
  2312. c.Fatal(err, out2)
  2313. }
  2314. out2 = strings.Trim(out2, "\n")
  2315. if hostPid == out2 {
  2316. c.Fatalf("PID should be different without --pid=host %s == %s\n", hostPid, out2)
  2317. }
  2318. }
  2319. func (s *DockerSuite) TestRunTLSverify(c *check.C) {
  2320. cmd := exec.Command(dockerBinary, "ps")
  2321. out, ec, err := runCommandWithOutput(cmd)
  2322. if err != nil || ec != 0 {
  2323. c.Fatalf("Should have worked: %v:\n%v", err, out)
  2324. }
  2325. // Regardless of whether we specify true or false we need to
  2326. // test to make sure tls is turned on if --tlsverify is specified at all
  2327. cmd = exec.Command(dockerBinary, "--tlsverify=false", "ps")
  2328. out, ec, err = runCommandWithOutput(cmd)
  2329. if err == nil || ec == 0 || !strings.Contains(out, "trying to connect") {
  2330. c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", ec, out, err)
  2331. }
  2332. cmd = exec.Command(dockerBinary, "--tlsverify=true", "ps")
  2333. out, ec, err = runCommandWithOutput(cmd)
  2334. if err == nil || ec == 0 || !strings.Contains(out, "cert") {
  2335. c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", ec, out, err)
  2336. }
  2337. }
  2338. func (s *DockerSuite) TestRunPortFromDockerRangeInUse(c *check.C) {
  2339. // first find allocator current position
  2340. cmd := exec.Command(dockerBinary, "run", "-d", "-p", ":80", "busybox", "top")
  2341. out, _, err := runCommandWithOutput(cmd)
  2342. if err != nil {
  2343. c.Fatal(out, err)
  2344. }
  2345. id := strings.TrimSpace(out)
  2346. cmd = exec.Command(dockerBinary, "port", id)
  2347. out, _, err = runCommandWithOutput(cmd)
  2348. if err != nil {
  2349. c.Fatal(out, err)
  2350. }
  2351. out = strings.TrimSpace(out)
  2352. if out == "" {
  2353. c.Fatal("docker port command output is empty")
  2354. }
  2355. out = strings.Split(out, ":")[1]
  2356. lastPort, err := strconv.Atoi(out)
  2357. if err != nil {
  2358. c.Fatal(err)
  2359. }
  2360. port := lastPort + 1
  2361. l, err := net.Listen("tcp", ":"+strconv.Itoa(port))
  2362. if err != nil {
  2363. c.Fatal(err)
  2364. }
  2365. defer l.Close()
  2366. cmd = exec.Command(dockerBinary, "run", "-d", "-p", ":80", "busybox", "top")
  2367. out, _, err = runCommandWithOutput(cmd)
  2368. if err != nil {
  2369. c.Fatalf(out, err)
  2370. }
  2371. id = strings.TrimSpace(out)
  2372. cmd = exec.Command(dockerBinary, "port", id)
  2373. out, _, err = runCommandWithOutput(cmd)
  2374. if err != nil {
  2375. c.Fatal(out, err)
  2376. }
  2377. }
  2378. func (s *DockerSuite) TestRunTtyWithPipe(c *check.C) {
  2379. errChan := make(chan error)
  2380. go func() {
  2381. defer close(errChan)
  2382. cmd := exec.Command(dockerBinary, "run", "-ti", "busybox", "true")
  2383. if _, err := cmd.StdinPipe(); err != nil {
  2384. errChan <- err
  2385. return
  2386. }
  2387. expected := "cannot enable tty mode"
  2388. if out, _, err := runCommandWithOutput(cmd); err == nil {
  2389. errChan <- fmt.Errorf("run should have failed")
  2390. return
  2391. } else if !strings.Contains(out, expected) {
  2392. errChan <- fmt.Errorf("run failed with error %q: expected %q", out, expected)
  2393. return
  2394. }
  2395. }()
  2396. select {
  2397. case err := <-errChan:
  2398. c.Assert(err, check.IsNil)
  2399. case <-time.After(3 * time.Second):
  2400. c.Fatal("container is running but should have failed")
  2401. }
  2402. }
  2403. func (s *DockerSuite) TestRunNonLocalMacAddress(c *check.C) {
  2404. addr := "00:16:3E:08:00:50"
  2405. cmd := exec.Command(dockerBinary, "run", "--mac-address", addr, "busybox", "ifconfig")
  2406. if out, _, err := runCommandWithOutput(cmd); err != nil || !strings.Contains(out, addr) {
  2407. c.Fatalf("Output should have contained %q: %s, %v", addr, out, err)
  2408. }
  2409. }
  2410. func (s *DockerSuite) TestRunNetHost(c *check.C) {
  2411. testRequires(c, SameHostDaemon)
  2412. hostNet, err := os.Readlink("/proc/1/ns/net")
  2413. if err != nil {
  2414. c.Fatal(err)
  2415. }
  2416. cmd := exec.Command(dockerBinary, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net")
  2417. out2, _, err := runCommandWithOutput(cmd)
  2418. if err != nil {
  2419. c.Fatal(err, out2)
  2420. }
  2421. out2 = strings.Trim(out2, "\n")
  2422. if hostNet != out2 {
  2423. c.Fatalf("Net namespace different with --net=host %s != %s\n", hostNet, out2)
  2424. }
  2425. cmd = exec.Command(dockerBinary, "run", "busybox", "readlink", "/proc/self/ns/net")
  2426. out2, _, err = runCommandWithOutput(cmd)
  2427. if err != nil {
  2428. c.Fatal(err, out2)
  2429. }
  2430. out2 = strings.Trim(out2, "\n")
  2431. if hostNet == out2 {
  2432. c.Fatalf("Net namespace should be different without --net=host %s == %s\n", hostNet, out2)
  2433. }
  2434. }
  2435. func (s *DockerSuite) TestRunNetContainerWhichHost(c *check.C) {
  2436. testRequires(c, SameHostDaemon)
  2437. hostNet, err := os.Readlink("/proc/1/ns/net")
  2438. if err != nil {
  2439. c.Fatal(err)
  2440. }
  2441. cmd := exec.Command(dockerBinary, "run", "-d", "--net=host", "--name=test", "busybox", "top")
  2442. out, _, err := runCommandWithOutput(cmd)
  2443. if err != nil {
  2444. c.Fatal(err, out)
  2445. }
  2446. cmd = exec.Command(dockerBinary, "run", "--net=container:test", "busybox", "readlink", "/proc/self/ns/net")
  2447. out, _, err = runCommandWithOutput(cmd)
  2448. if err != nil {
  2449. c.Fatal(err, out)
  2450. }
  2451. out = strings.Trim(out, "\n")
  2452. if hostNet != out {
  2453. c.Fatalf("Container should have host network namespace")
  2454. }
  2455. }
  2456. func (s *DockerSuite) TestRunAllowPortRangeThroughPublish(c *check.C) {
  2457. cmd := exec.Command(dockerBinary, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top")
  2458. out, _, err := runCommandWithOutput(cmd)
  2459. id := strings.TrimSpace(out)
  2460. portstr, err := inspectFieldJSON(id, "NetworkSettings.Ports")
  2461. if err != nil {
  2462. c.Fatal(err)
  2463. }
  2464. var ports nat.PortMap
  2465. err = unmarshalJSON([]byte(portstr), &ports)
  2466. for port, binding := range ports {
  2467. portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  2468. if portnum < 3000 || portnum > 3003 {
  2469. c.Fatalf("Port %d is out of range ", portnum)
  2470. }
  2471. if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  2472. c.Fatal("Port is not mapped for the port "+port, out)
  2473. }
  2474. }
  2475. }
  2476. func (s *DockerSuite) TestRunOOMExitCode(c *check.C) {
  2477. errChan := make(chan error)
  2478. go func() {
  2479. defer close(errChan)
  2480. runCmd := exec.Command(dockerBinary, "run", "-m", "4MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done")
  2481. out, exitCode, _ := runCommandWithOutput(runCmd)
  2482. if expected := 137; exitCode != expected {
  2483. errChan <- fmt.Errorf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out)
  2484. }
  2485. }()
  2486. select {
  2487. case err := <-errChan:
  2488. c.Assert(err, check.IsNil)
  2489. case <-time.After(30 * time.Second):
  2490. c.Fatal("Timeout waiting for container to die on OOM")
  2491. }
  2492. }
  2493. func (s *DockerSuite) TestRunSetDefaultRestartPolicy(c *check.C) {
  2494. runCmd := exec.Command(dockerBinary, "run", "-d", "--name", "test", "busybox", "top")
  2495. if out, _, err := runCommandWithOutput(runCmd); err != nil {
  2496. c.Fatalf("failed to run container: %v, output: %q", err, out)
  2497. }
  2498. cmd := exec.Command(dockerBinary, "inspect", "-f", "{{.HostConfig.RestartPolicy.Name}}", "test")
  2499. out, _, err := runCommandWithOutput(cmd)
  2500. if err != nil {
  2501. c.Fatalf("failed to inspect container: %v, output: %q", err, out)
  2502. }
  2503. out = strings.Trim(out, "\r\n")
  2504. if out != "no" {
  2505. c.Fatalf("Set default restart policy failed")
  2506. }
  2507. }
  2508. func (s *DockerSuite) TestRunRestartMaxRetries(c *check.C) {
  2509. out, err := exec.Command(dockerBinary, "run", "-d", "--restart=on-failure:3", "busybox", "false").CombinedOutput()
  2510. if err != nil {
  2511. c.Fatal(string(out), err)
  2512. }
  2513. id := strings.TrimSpace(string(out))
  2514. if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", 10); err != nil {
  2515. c.Fatal(err)
  2516. }
  2517. count, err := inspectField(id, "RestartCount")
  2518. if err != nil {
  2519. c.Fatal(err)
  2520. }
  2521. if count != "3" {
  2522. c.Fatalf("Container was restarted %s times, expected %d", count, 3)
  2523. }
  2524. MaximumRetryCount, err := inspectField(id, "HostConfig.RestartPolicy.MaximumRetryCount")
  2525. if err != nil {
  2526. c.Fatal(err)
  2527. }
  2528. if MaximumRetryCount != "3" {
  2529. c.Fatalf("Container Maximum Retry Count is %s, expected %s", MaximumRetryCount, "3")
  2530. }
  2531. }
  2532. func (s *DockerSuite) TestRunContainerWithWritableRootfs(c *check.C) {
  2533. out, err := exec.Command(dockerBinary, "run", "--rm", "busybox", "touch", "/file").CombinedOutput()
  2534. if err != nil {
  2535. c.Fatal(string(out), err)
  2536. }
  2537. }
  2538. func (s *DockerSuite) TestRunContainerWithReadonlyRootfs(c *check.C) {
  2539. testRequires(c, NativeExecDriver)
  2540. out, err := exec.Command(dockerBinary, "run", "--read-only", "--rm", "busybox", "touch", "/file").CombinedOutput()
  2541. if err == nil {
  2542. c.Fatal("expected container to error on run with read only error")
  2543. }
  2544. expected := "Read-only file system"
  2545. if !strings.Contains(string(out), expected) {
  2546. c.Fatalf("expected output from failure to contain %s but contains %s", expected, out)
  2547. }
  2548. }
  2549. func (s *DockerSuite) TestRunVolumesFromRestartAfterRemoved(c *check.C) {
  2550. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", "voltest", "-v", "/foo", "busybox"))
  2551. if err != nil {
  2552. c.Fatal(out, err)
  2553. }
  2554. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", "restarter", "--volumes-from", "voltest", "busybox", "top"))
  2555. if err != nil {
  2556. c.Fatal(out, err)
  2557. }
  2558. // Remove the main volume container and restart the consuming container
  2559. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "rm", "-f", "voltest"))
  2560. if err != nil {
  2561. c.Fatal(out, err)
  2562. }
  2563. // This should not fail since the volumes-from were already applied
  2564. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "restart", "restarter"))
  2565. if err != nil {
  2566. c.Fatalf("expected container to restart successfully: %v\n%s", err, out)
  2567. }
  2568. }
  2569. // run container with --rm should remove container if exit code != 0
  2570. func (s *DockerSuite) TestRunContainerWithRmFlagExitCodeNotEqualToZero(c *check.C) {
  2571. name := "flowers"
  2572. runCmd := exec.Command(dockerBinary, "run", "--name", name, "--rm", "busybox", "ls", "/notexists")
  2573. out, _, err := runCommandWithOutput(runCmd)
  2574. if err == nil {
  2575. c.Fatal("Expected docker run to fail", out, err)
  2576. }
  2577. out, err = getAllContainers()
  2578. if err != nil {
  2579. c.Fatal(out, err)
  2580. }
  2581. if out != "" {
  2582. c.Fatal("Expected not to have containers", out)
  2583. }
  2584. }
  2585. func (s *DockerSuite) TestRunContainerWithRmFlagCannotStartContainer(c *check.C) {
  2586. name := "sparkles"
  2587. runCmd := exec.Command(dockerBinary, "run", "--name", name, "--rm", "busybox", "commandNotFound")
  2588. out, _, err := runCommandWithOutput(runCmd)
  2589. if err == nil {
  2590. c.Fatal("Expected docker run to fail", out, err)
  2591. }
  2592. out, err = getAllContainers()
  2593. if err != nil {
  2594. c.Fatal(out, err)
  2595. }
  2596. if out != "" {
  2597. c.Fatal("Expected not to have containers", out)
  2598. }
  2599. }
  2600. func (s *DockerSuite) TestRunPidHostWithChildIsKillable(c *check.C) {
  2601. name := "ibuildthecloud"
  2602. if out, err := exec.Command(dockerBinary, "run", "-d", "--pid=host", "--name", name, "busybox", "sh", "-c", "sleep 30; echo hi").CombinedOutput(); err != nil {
  2603. c.Fatal(err, out)
  2604. }
  2605. time.Sleep(1 * time.Second)
  2606. errchan := make(chan error)
  2607. go func() {
  2608. if out, err := exec.Command(dockerBinary, "kill", name).CombinedOutput(); err != nil {
  2609. errchan <- fmt.Errorf("%v:\n%s", err, out)
  2610. }
  2611. close(errchan)
  2612. }()
  2613. select {
  2614. case err := <-errchan:
  2615. c.Assert(err, check.IsNil)
  2616. case <-time.After(5 * time.Second):
  2617. c.Fatal("Kill container timed out")
  2618. }
  2619. }