docker_cli_run_test.go 85 KB

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