docker_cli_run_test.go 89 KB

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