docker_cli_run_test.go 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984
  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 && top", 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", "top"))
  1639. if err != nil {
  1640. t.Fatal(err)
  1641. }
  1642. contID := strings.TrimSpace(out)
  1643. netFilePath := containerStorageFile(contID, fn)
  1644. f, err := os.OpenFile(netFilePath, 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. res, err := exec.Command(dockerBinary, "exec", contID, "cat", "/etc/"+fn).CombinedOutput()
  1662. if err != nil {
  1663. t.Fatalf("Output: %s, error: %s", res, err)
  1664. }
  1665. if string(res) != "success2\n" {
  1666. t.Fatalf("Expected content of %s: %q, got: %q", fn, "success2\n", res)
  1667. }
  1668. }
  1669. logDone("run - mutable network files")
  1670. }
  1671. // Ensure that CIDFile gets deleted if it's empty
  1672. // Perform this test by making `docker run` fail
  1673. func TestRunCidFileCleanupIfEmpty(t *testing.T) {
  1674. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1675. if err != nil {
  1676. t.Fatal(err)
  1677. }
  1678. defer os.RemoveAll(tmpDir)
  1679. tmpCidFile := path.Join(tmpDir, "cid")
  1680. cmd := exec.Command(dockerBinary, "run", "--cidfile", tmpCidFile, "scratch")
  1681. out, _, err := runCommandWithOutput(cmd)
  1682. t.Log(out)
  1683. if err == nil {
  1684. t.Fatal("Run without command must fail")
  1685. }
  1686. if _, err := os.Stat(tmpCidFile); err == nil {
  1687. t.Fatalf("empty CIDFile %q should've been deleted", tmpCidFile)
  1688. }
  1689. deleteAllContainers()
  1690. logDone("run - cleanup empty cidfile on fail")
  1691. }
  1692. // #2098 - Docker cidFiles only contain short version of the containerId
  1693. //sudo docker run --cidfile /tmp/docker_test.cid ubuntu echo "test"
  1694. // TestRunCidFile tests that run --cidfile returns the longid
  1695. func TestRunCidFileCheckIDLength(t *testing.T) {
  1696. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1697. if err != nil {
  1698. t.Fatal(err)
  1699. }
  1700. tmpCidFile := path.Join(tmpDir, "cid")
  1701. defer os.RemoveAll(tmpDir)
  1702. cmd := exec.Command(dockerBinary, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true")
  1703. out, _, err := runCommandWithOutput(cmd)
  1704. if err != nil {
  1705. t.Fatal(err)
  1706. }
  1707. id := strings.TrimSpace(out)
  1708. buffer, err := ioutil.ReadFile(tmpCidFile)
  1709. if err != nil {
  1710. t.Fatal(err)
  1711. }
  1712. cid := string(buffer)
  1713. if len(cid) != 64 {
  1714. t.Fatalf("--cidfile should be a long id, not %q", id)
  1715. }
  1716. if cid != id {
  1717. t.Fatalf("cid must be equal to %s, got %s", id, cid)
  1718. }
  1719. deleteAllContainers()
  1720. logDone("run - cidfile contains long id")
  1721. }
  1722. func TestRunNetworkNotInitializedNoneMode(t *testing.T) {
  1723. cmd := exec.Command(dockerBinary, "run", "-d", "--net=none", "busybox", "top")
  1724. out, _, err := runCommandWithOutput(cmd)
  1725. if err != nil {
  1726. t.Fatal(err)
  1727. }
  1728. id := strings.TrimSpace(out)
  1729. res, err := inspectField(id, "NetworkSettings.IPAddress")
  1730. if err != nil {
  1731. t.Fatal(err)
  1732. }
  1733. if res != "" {
  1734. t.Fatalf("For 'none' mode network must not be initialized, but container got IP: %s", res)
  1735. }
  1736. deleteAllContainers()
  1737. logDone("run - network must not be initialized in 'none' mode")
  1738. }
  1739. func TestRunSetMacAddress(t *testing.T) {
  1740. mac := "12:34:56:78:9a:bc"
  1741. 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 }'"`)
  1742. out, _, err := runCommandWithOutput(cmd)
  1743. if err != nil {
  1744. t.Fatal(err)
  1745. }
  1746. actualMac := strings.TrimSpace(out)
  1747. if actualMac != mac {
  1748. t.Fatalf("Set MAC address with --mac-address failed. The container has an incorrect MAC address: %q, expected: %q", actualMac, mac)
  1749. }
  1750. deleteAllContainers()
  1751. logDone("run - setting MAC address with --mac-address")
  1752. }
  1753. func TestRunInspectMacAddress(t *testing.T) {
  1754. mac := "12:34:56:78:9a:bc"
  1755. cmd := exec.Command(dockerBinary, "run", "-d", "--mac-address="+mac, "busybox", "top")
  1756. out, _, err := runCommandWithOutput(cmd)
  1757. if err != nil {
  1758. t.Fatal(err)
  1759. }
  1760. id := strings.TrimSpace(out)
  1761. inspectedMac, err := inspectField(id, "NetworkSettings.MacAddress")
  1762. if err != nil {
  1763. t.Fatal(err)
  1764. }
  1765. if inspectedMac != mac {
  1766. t.Fatalf("docker inspect outputs wrong MAC address: %q, should be: %q", inspectedMac, mac)
  1767. }
  1768. deleteAllContainers()
  1769. logDone("run - inspecting MAC address")
  1770. }
  1771. func TestRunDeallocatePortOnMissingIptablesRule(t *testing.T) {
  1772. cmd := exec.Command(dockerBinary, "run", "-d", "-p", "23:23", "busybox", "top")
  1773. out, _, err := runCommandWithOutput(cmd)
  1774. if err != nil {
  1775. t.Fatal(err)
  1776. }
  1777. id := strings.TrimSpace(out)
  1778. ip, err := inspectField(id, "NetworkSettings.IPAddress")
  1779. if err != nil {
  1780. t.Fatal(err)
  1781. }
  1782. iptCmd := exec.Command("iptables", "-D", "DOCKER", "-d", fmt.Sprintf("%s/32", ip),
  1783. "!", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-m", "tcp", "--dport", "23", "-j", "ACCEPT")
  1784. out, _, err = runCommandWithOutput(iptCmd)
  1785. if err != nil {
  1786. t.Fatal(err, out)
  1787. }
  1788. if err := deleteContainer(id); err != nil {
  1789. t.Fatal(err)
  1790. }
  1791. cmd = exec.Command(dockerBinary, "run", "-d", "-p", "23:23", "busybox", "top")
  1792. out, _, err = runCommandWithOutput(cmd)
  1793. if err != nil {
  1794. t.Fatal(err, out)
  1795. }
  1796. deleteAllContainers()
  1797. logDone("run - port should be deallocated even on iptables error")
  1798. }
  1799. func TestRunPortInUse(t *testing.T) {
  1800. port := "1234"
  1801. l, err := net.Listen("tcp", ":"+port)
  1802. if err != nil {
  1803. t.Fatal(err)
  1804. }
  1805. defer l.Close()
  1806. cmd := exec.Command(dockerBinary, "run", "-d", "-p", port+":80", "busybox", "top")
  1807. out, _, err := runCommandWithOutput(cmd)
  1808. if err == nil {
  1809. t.Fatalf("Binding on used port must fail")
  1810. }
  1811. if !strings.Contains(out, "address already in use") {
  1812. t.Fatalf("Out must be about \"address already in use\", got %s", out)
  1813. }
  1814. deleteAllContainers()
  1815. logDone("run - fail if port already in use")
  1816. }
  1817. // https://github.com/docker/docker/issues/8428
  1818. func TestRunPortProxy(t *testing.T) {
  1819. defer deleteAllContainers()
  1820. port := "12345"
  1821. cmd := exec.Command(dockerBinary, "run", "-d", "-p", port+":80", "busybox", "top")
  1822. out, _, err := runCommandWithOutput(cmd)
  1823. if err != nil {
  1824. t.Fatalf("Failed to run and bind port %s, output: %s, error: %s", port, out, err)
  1825. }
  1826. // connect for 10 times here. This will trigger 10 EPIPES in the child
  1827. // process and kill it when it writes to a closed stdout/stderr
  1828. for i := 0; i < 10; i++ {
  1829. net.Dial("tcp", fmt.Sprintf("0.0.0.0:%s", port))
  1830. }
  1831. listPs := exec.Command("sh", "-c", "ps ax | grep docker")
  1832. out, _, err = runCommandWithOutput(listPs)
  1833. if err != nil {
  1834. t.Errorf("list docker process failed with output %s, error %s", out, err)
  1835. }
  1836. if strings.Contains(out, "docker <defunct>") {
  1837. t.Errorf("Unexpected defunct docker process")
  1838. }
  1839. if !strings.Contains(out, "docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 12345") {
  1840. t.Errorf("Failed to find docker-proxy process, got %s", out)
  1841. }
  1842. logDone("run - proxy should work with unavailable port")
  1843. }
  1844. // Regression test for #7792
  1845. func TestRunMountOrdering(t *testing.T) {
  1846. tmpDir, err := ioutil.TempDir("", "docker_nested_mount_test")
  1847. if err != nil {
  1848. t.Fatal(err)
  1849. }
  1850. defer os.RemoveAll(tmpDir)
  1851. tmpDir2, err := ioutil.TempDir("", "docker_nested_mount_test2")
  1852. if err != nil {
  1853. t.Fatal(err)
  1854. }
  1855. defer os.RemoveAll(tmpDir2)
  1856. // Create a temporary tmpfs mount.
  1857. fooDir := filepath.Join(tmpDir, "foo")
  1858. if err := os.MkdirAll(filepath.Join(tmpDir, "foo"), 0755); err != nil {
  1859. t.Fatalf("failed to mkdir at %s - %s", fooDir, err)
  1860. }
  1861. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", fooDir), []byte{}, 0644); err != nil {
  1862. t.Fatal(err)
  1863. }
  1864. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir), []byte{}, 0644); err != nil {
  1865. t.Fatal(err)
  1866. }
  1867. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir2), []byte{}, 0644); err != nil {
  1868. t.Fatal(err)
  1869. }
  1870. 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")
  1871. out, _, err := runCommandWithOutput(cmd)
  1872. if err != nil {
  1873. t.Fatal(out, err)
  1874. }
  1875. deleteAllContainers()
  1876. logDone("run - volumes are mounted in the correct order")
  1877. }
  1878. func TestRunExecDir(t *testing.T) {
  1879. cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  1880. out, _, err := runCommandWithOutput(cmd)
  1881. if err != nil {
  1882. t.Fatal(err, out)
  1883. }
  1884. id := strings.TrimSpace(out)
  1885. execDir := filepath.Join(execDriverPath, id)
  1886. stateFile := filepath.Join(execDir, "state.json")
  1887. contFile := filepath.Join(execDir, "container.json")
  1888. {
  1889. fi, err := os.Stat(execDir)
  1890. if err != nil {
  1891. t.Fatal(err)
  1892. }
  1893. if !fi.IsDir() {
  1894. t.Fatalf("%q must be a directory", execDir)
  1895. }
  1896. fi, err = os.Stat(stateFile)
  1897. if err != nil {
  1898. t.Fatal(err)
  1899. }
  1900. fi, err = os.Stat(contFile)
  1901. if err != nil {
  1902. t.Fatal(err)
  1903. }
  1904. }
  1905. stopCmd := exec.Command(dockerBinary, "stop", id)
  1906. out, _, err = runCommandWithOutput(stopCmd)
  1907. if err != nil {
  1908. t.Fatal(err, out)
  1909. }
  1910. {
  1911. fi, err := os.Stat(execDir)
  1912. if err != nil {
  1913. t.Fatal(err)
  1914. }
  1915. if !fi.IsDir() {
  1916. t.Fatalf("%q must be a directory", execDir)
  1917. }
  1918. fi, err = os.Stat(stateFile)
  1919. if err == nil {
  1920. t.Fatalf("Statefile %q is exists for stopped container!", stateFile)
  1921. }
  1922. if !os.IsNotExist(err) {
  1923. t.Fatalf("Error should be about non-existing, got %s", err)
  1924. }
  1925. fi, err = os.Stat(contFile)
  1926. if err == nil {
  1927. t.Fatalf("Container file %q is exists for stopped container!", contFile)
  1928. }
  1929. if !os.IsNotExist(err) {
  1930. t.Fatalf("Error should be about non-existing, got %s", err)
  1931. }
  1932. }
  1933. startCmd := exec.Command(dockerBinary, "start", id)
  1934. out, _, err = runCommandWithOutput(startCmd)
  1935. if err != nil {
  1936. t.Fatal(err, out)
  1937. }
  1938. {
  1939. fi, err := os.Stat(execDir)
  1940. if err != nil {
  1941. t.Fatal(err)
  1942. }
  1943. if !fi.IsDir() {
  1944. t.Fatalf("%q must be a directory", execDir)
  1945. }
  1946. fi, err = os.Stat(stateFile)
  1947. if err != nil {
  1948. t.Fatal(err)
  1949. }
  1950. fi, err = os.Stat(contFile)
  1951. if err != nil {
  1952. t.Fatal(err)
  1953. }
  1954. }
  1955. rmCmd := exec.Command(dockerBinary, "rm", "-f", id)
  1956. out, _, err = runCommandWithOutput(rmCmd)
  1957. if err != nil {
  1958. t.Fatal(err, out)
  1959. }
  1960. {
  1961. _, err := os.Stat(execDir)
  1962. if err == nil {
  1963. t.Fatal(err)
  1964. }
  1965. if err == nil {
  1966. t.Fatalf("Exec directory %q is exists for removed container!", execDir)
  1967. }
  1968. if !os.IsNotExist(err) {
  1969. t.Fatalf("Error should be about non-existing, got %s", err)
  1970. }
  1971. }
  1972. logDone("run - check execdriver dir behavior")
  1973. }
  1974. // Regression test for https://github.com/docker/docker/issues/8259
  1975. func TestRunReuseBindVolumeThatIsSymlink(t *testing.T) {
  1976. tmpDir, err := ioutil.TempDir(os.TempDir(), "testlink")
  1977. if err != nil {
  1978. t.Fatal(err)
  1979. }
  1980. defer os.RemoveAll(tmpDir)
  1981. linkPath := os.TempDir() + "/testlink2"
  1982. if err := os.Symlink(tmpDir, linkPath); err != nil {
  1983. t.Fatal(err)
  1984. }
  1985. defer os.RemoveAll(linkPath)
  1986. // Create first container
  1987. cmd := exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
  1988. if _, err := runCommand(cmd); err != nil {
  1989. t.Fatal(err)
  1990. }
  1991. // Create second container with same symlinked path
  1992. // This will fail if the referenced issue is hit with a "Volume exists" error
  1993. cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
  1994. if out, _, err := runCommandWithOutput(cmd); err != nil {
  1995. t.Fatal(err, out)
  1996. }
  1997. deleteAllContainers()
  1998. logDone("run - can remount old bindmount volume")
  1999. }
  2000. func TestVolumesNoCopyData(t *testing.T) {
  2001. defer deleteImages("dataimage")
  2002. defer deleteAllContainers()
  2003. if _, err := buildImage("dataimage",
  2004. `FROM busybox
  2005. RUN mkdir -p /foo
  2006. RUN touch /foo/bar`,
  2007. true); err != nil {
  2008. t.Fatal(err)
  2009. }
  2010. cmd := exec.Command(dockerBinary, "run", "--name", "test", "-v", "/foo", "busybox")
  2011. if _, err := runCommand(cmd); err != nil {
  2012. t.Fatal(err)
  2013. }
  2014. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "test", "dataimage", "ls", "-lh", "/foo/bar")
  2015. if out, _, err := runCommandWithOutput(cmd); err == nil || !strings.Contains(out, "No such file or directory") {
  2016. t.Fatalf("Data was copied on volumes-from but shouldn't be:\n%q", out)
  2017. }
  2018. tmpDir, err := ioutil.TempDir("", "docker_test_bind_mount_copy_data")
  2019. if err != nil {
  2020. t.Fatal(err)
  2021. }
  2022. defer os.RemoveAll(tmpDir)
  2023. cmd = exec.Command(dockerBinary, "run", "-v", tmpDir+":/foo", "dataimage", "ls", "-lh", "/foo/bar")
  2024. if out, _, err := runCommandWithOutput(cmd); err == nil || !strings.Contains(out, "No such file or directory") {
  2025. t.Fatalf("Data was copied on bind-mount but shouldn't be:\n%q", out)
  2026. }
  2027. logDone("run - volumes do not copy data for volumes-from and bindmounts")
  2028. }
  2029. func TestRunVolumesNotRecreatedOnStart(t *testing.T) {
  2030. // Clear out any remnants from other tests
  2031. deleteAllContainers()
  2032. info, err := ioutil.ReadDir(volumesConfigPath)
  2033. if err != nil {
  2034. t.Fatal(err)
  2035. }
  2036. if len(info) > 0 {
  2037. for _, f := range info {
  2038. if err := os.RemoveAll(volumesConfigPath + "/" + f.Name()); err != nil {
  2039. t.Fatal(err)
  2040. }
  2041. }
  2042. }
  2043. defer deleteAllContainers()
  2044. cmd := exec.Command(dockerBinary, "run", "-v", "/foo", "--name", "lone_starr", "busybox")
  2045. if _, err := runCommand(cmd); err != nil {
  2046. t.Fatal(err)
  2047. }
  2048. cmd = exec.Command(dockerBinary, "start", "lone_starr")
  2049. if _, err := runCommand(cmd); err != nil {
  2050. t.Fatal(err)
  2051. }
  2052. info, err = ioutil.ReadDir(volumesConfigPath)
  2053. if err != nil {
  2054. t.Fatal(err)
  2055. }
  2056. if len(info) != 1 {
  2057. t.Fatalf("Expected only 1 volume have %v", len(info))
  2058. }
  2059. logDone("run - volumes not recreated on start")
  2060. }
  2061. func TestRunNoOutputFromPullInStdout(t *testing.T) {
  2062. defer deleteAllContainers()
  2063. // just run with unknown image
  2064. cmd := exec.Command(dockerBinary, "run", "asdfsg")
  2065. stdout := bytes.NewBuffer(nil)
  2066. cmd.Stdout = stdout
  2067. if err := cmd.Run(); err == nil {
  2068. t.Fatal("Run with unknown image should fail")
  2069. }
  2070. if stdout.Len() != 0 {
  2071. t.Fatalf("Stdout contains output from pull: %s", stdout)
  2072. }
  2073. logDone("run - no output from pull in stdout")
  2074. }
  2075. func TestRunVolumesCleanPaths(t *testing.T) {
  2076. if _, err := buildImage("run_volumes_clean_paths",
  2077. `FROM busybox
  2078. VOLUME /foo/`,
  2079. true); err != nil {
  2080. t.Fatal(err)
  2081. }
  2082. defer deleteImages("run_volumes_clean_paths")
  2083. defer deleteAllContainers()
  2084. cmd := exec.Command(dockerBinary, "run", "-v", "/foo", "-v", "/bar/", "--name", "dark_helmet", "run_volumes_clean_paths")
  2085. if out, _, err := runCommandWithOutput(cmd); err != nil {
  2086. t.Fatal(err, out)
  2087. }
  2088. out, err := inspectFieldMap("dark_helmet", "Volumes", "/foo/")
  2089. if err != nil {
  2090. t.Fatal(err)
  2091. }
  2092. if out != "<no value>" {
  2093. t.Fatalf("Found unexpected volume entry for '/foo/' in volumes\n%q", out)
  2094. }
  2095. out, err = inspectFieldMap("dark_helmet", "Volumes", "/foo")
  2096. if err != nil {
  2097. t.Fatal(err)
  2098. }
  2099. if !strings.Contains(out, volumesStoragePath) {
  2100. t.Fatalf("Volume was not defined for /foo\n%q", out)
  2101. }
  2102. out, err = inspectFieldMap("dark_helmet", "Volumes", "/bar/")
  2103. if err != nil {
  2104. t.Fatal(err)
  2105. }
  2106. if out != "<no value>" {
  2107. t.Fatalf("Found unexpected volume entry for '/bar/' in volumes\n%q", out)
  2108. }
  2109. out, err = inspectFieldMap("dark_helmet", "Volumes", "/bar")
  2110. if err != nil {
  2111. t.Fatal(err)
  2112. }
  2113. if !strings.Contains(out, volumesStoragePath) {
  2114. t.Fatalf("Volume was not defined for /bar\n%q", out)
  2115. }
  2116. logDone("run - volume paths are cleaned")
  2117. }
  2118. // Regression test for #3631
  2119. func TestRunSlowStdoutConsumer(t *testing.T) {
  2120. defer deleteAllContainers()
  2121. 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"`)
  2122. stdout, err := c.StdoutPipe()
  2123. if err != nil {
  2124. t.Fatal(err)
  2125. }
  2126. if err := c.Start(); err != nil {
  2127. t.Fatal(err)
  2128. }
  2129. n, err := consumeWithSpeed(stdout, 10000, 5*time.Millisecond, nil)
  2130. if err != nil {
  2131. t.Fatal(err)
  2132. }
  2133. expected := 2 * 1024 * 2000
  2134. if n != expected {
  2135. t.Fatalf("Expected %d, got %d", expected, n)
  2136. }
  2137. logDone("run - slow consumer")
  2138. }
  2139. func TestRunAllowPortRangeThroughExpose(t *testing.T) {
  2140. cmd := exec.Command(dockerBinary, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top")
  2141. out, _, err := runCommandWithOutput(cmd)
  2142. if err != nil {
  2143. t.Fatal(err)
  2144. }
  2145. id := strings.TrimSpace(out)
  2146. portstr, err := inspectFieldJSON(id, "NetworkSettings.Ports")
  2147. if err != nil {
  2148. t.Fatal(err)
  2149. }
  2150. var ports nat.PortMap
  2151. err = unmarshalJSON([]byte(portstr), &ports)
  2152. for port, binding := range ports {
  2153. portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  2154. if portnum < 3000 || portnum > 3003 {
  2155. t.Fatalf("Port is out of range ", portnum, binding, out)
  2156. }
  2157. if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  2158. t.Fatal("Port is not mapped for the port "+port, out)
  2159. }
  2160. }
  2161. if err := deleteContainer(id); err != nil {
  2162. t.Fatal(err)
  2163. }
  2164. logDone("run - allow port range through --expose flag")
  2165. }
  2166. func TestRunUnknownCommand(t *testing.T) {
  2167. defer deleteAllContainers()
  2168. runCmd := exec.Command(dockerBinary, "create", "busybox", "/bin/nada")
  2169. cID, _, _, err := runCommandWithStdoutStderr(runCmd)
  2170. if err != nil {
  2171. t.Fatalf("Failed to create container: %v, output: %q", err, cID)
  2172. }
  2173. cID = strings.TrimSpace(cID)
  2174. runCmd = exec.Command(dockerBinary, "start", cID)
  2175. _, _, _, err = runCommandWithStdoutStderr(runCmd)
  2176. if err == nil {
  2177. t.Fatalf("Container should not have been able to start!")
  2178. }
  2179. runCmd = exec.Command(dockerBinary, "inspect", "--format={{.State.ExitCode}}", cID)
  2180. rc, _, _, err2 := runCommandWithStdoutStderr(runCmd)
  2181. rc = strings.TrimSpace(rc)
  2182. if err2 != nil {
  2183. t.Fatalf("Error getting status of container: %v", err2)
  2184. }
  2185. if rc != "-1" {
  2186. t.Fatalf("ExitCode(%v) was supposed to be -1", rc)
  2187. }
  2188. logDone("run - Unknown Command")
  2189. }
  2190. func TestRunModeIpcHost(t *testing.T) {
  2191. hostIpc, err := os.Readlink("/proc/1/ns/ipc")
  2192. if err != nil {
  2193. t.Fatal(err)
  2194. }
  2195. cmd := exec.Command(dockerBinary, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc")
  2196. out2, _, err := runCommandWithOutput(cmd)
  2197. if err != nil {
  2198. t.Fatal(err, out2)
  2199. }
  2200. out2 = strings.Trim(out2, "\n")
  2201. if hostIpc != out2 {
  2202. t.Fatalf("IPC different with --ipc=host %s != %s\n", hostIpc, out2)
  2203. }
  2204. cmd = exec.Command(dockerBinary, "run", "busybox", "readlink", "/proc/self/ns/ipc")
  2205. out2, _, err = runCommandWithOutput(cmd)
  2206. if err != nil {
  2207. t.Fatal(err, out2)
  2208. }
  2209. out2 = strings.Trim(out2, "\n")
  2210. if hostIpc == out2 {
  2211. t.Fatalf("IPC should be different without --ipc=host %s == %s\n", hostIpc, out2)
  2212. }
  2213. deleteAllContainers()
  2214. logDone("run - ipc host mode")
  2215. }
  2216. func TestRunModeIpcContainer(t *testing.T) {
  2217. cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  2218. out, _, err := runCommandWithOutput(cmd)
  2219. if err != nil {
  2220. t.Fatal(err, out)
  2221. }
  2222. id := strings.TrimSpace(out)
  2223. state, err := inspectField(id, "State.Running")
  2224. if err != nil {
  2225. t.Fatal(err)
  2226. }
  2227. if state != "true" {
  2228. t.Fatal("Container state is 'not running'")
  2229. }
  2230. pid1, err := inspectField(id, "State.Pid")
  2231. if err != nil {
  2232. t.Fatal(err)
  2233. }
  2234. parentContainerIpc, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/ipc", pid1))
  2235. if err != nil {
  2236. t.Fatal(err)
  2237. }
  2238. cmd = exec.Command(dockerBinary, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "readlink", "/proc/self/ns/ipc")
  2239. out2, _, err := runCommandWithOutput(cmd)
  2240. if err != nil {
  2241. t.Fatal(err, out2)
  2242. }
  2243. out2 = strings.Trim(out2, "\n")
  2244. if parentContainerIpc != out2 {
  2245. t.Fatalf("IPC different with --ipc=container:%s %s != %s\n", id, parentContainerIpc, out2)
  2246. }
  2247. deleteAllContainers()
  2248. logDone("run - ipc container mode")
  2249. }
  2250. func TestContainerNetworkMode(t *testing.T) {
  2251. cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  2252. out, _, err := runCommandWithOutput(cmd)
  2253. if err != nil {
  2254. t.Fatal(err, out)
  2255. }
  2256. id := strings.TrimSpace(out)
  2257. if err := waitRun(id); err != nil {
  2258. t.Fatal(err)
  2259. }
  2260. pid1, err := inspectField(id, "State.Pid")
  2261. if err != nil {
  2262. t.Fatal(err)
  2263. }
  2264. parentContainerNet, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
  2265. if err != nil {
  2266. t.Fatal(err)
  2267. }
  2268. cmd = exec.Command(dockerBinary, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net")
  2269. out2, _, err := runCommandWithOutput(cmd)
  2270. if err != nil {
  2271. t.Fatal(err, out2)
  2272. }
  2273. out2 = strings.Trim(out2, "\n")
  2274. if parentContainerNet != out2 {
  2275. t.Fatalf("NET different with --net=container:%s %s != %s\n", id, parentContainerNet, out2)
  2276. }
  2277. deleteAllContainers()
  2278. logDone("run - container shared network namespace")
  2279. }
  2280. func TestRunModePidHost(t *testing.T) {
  2281. hostPid, err := os.Readlink("/proc/1/ns/pid")
  2282. if err != nil {
  2283. t.Fatal(err)
  2284. }
  2285. cmd := exec.Command(dockerBinary, "run", "--pid=host", "busybox", "readlink", "/proc/self/ns/pid")
  2286. out2, _, err := runCommandWithOutput(cmd)
  2287. if err != nil {
  2288. t.Fatal(err, out2)
  2289. }
  2290. out2 = strings.Trim(out2, "\n")
  2291. if hostPid != out2 {
  2292. t.Fatalf("PID different with --pid=host %s != %s\n", hostPid, out2)
  2293. }
  2294. cmd = exec.Command(dockerBinary, "run", "busybox", "readlink", "/proc/self/ns/pid")
  2295. out2, _, err = runCommandWithOutput(cmd)
  2296. if err != nil {
  2297. t.Fatal(err, out2)
  2298. }
  2299. out2 = strings.Trim(out2, "\n")
  2300. if hostPid == out2 {
  2301. t.Fatalf("PID should be different without --pid=host %s == %s\n", hostPid, out2)
  2302. }
  2303. deleteAllContainers()
  2304. logDone("run - pid host mode")
  2305. }
  2306. func TestRunTLSverify(t *testing.T) {
  2307. cmd := exec.Command(dockerBinary, "ps")
  2308. out, ec, err := runCommandWithOutput(cmd)
  2309. if err != nil || ec != 0 {
  2310. t.Fatalf("Should have worked: %v:\n%v", err, out)
  2311. }
  2312. // Regardless of whether we specify true or false we need to
  2313. // test to make sure tls is turned on if --tlsverify is specified at all
  2314. cmd = exec.Command(dockerBinary, "--tlsverify=false", "ps")
  2315. out, ec, err = runCommandWithOutput(cmd)
  2316. if err == nil || ec == 0 || !strings.Contains(out, "trying to connect") {
  2317. t.Fatalf("Should have failed: \nec:%v\nout:%v\nerr:%v", ec, out, err)
  2318. }
  2319. cmd = exec.Command(dockerBinary, "--tlsverify=true", "ps")
  2320. out, ec, err = runCommandWithOutput(cmd)
  2321. if err == nil || ec == 0 || !strings.Contains(out, "cert") {
  2322. t.Fatalf("Should have failed: \nec:%v\nout:%v\nerr:%v", ec, out, err)
  2323. }
  2324. logDone("run - verify tls is set for --tlsverify")
  2325. }
  2326. func TestRunPortFromDockerRangeInUse(t *testing.T) {
  2327. defer deleteAllContainers()
  2328. // first find allocator current position
  2329. cmd := exec.Command(dockerBinary, "run", "-d", "-p", ":80", "busybox", "top")
  2330. out, _, err := runCommandWithOutput(cmd)
  2331. if err != nil {
  2332. t.Fatal(out, err)
  2333. }
  2334. id := strings.TrimSpace(out)
  2335. cmd = exec.Command(dockerBinary, "port", id)
  2336. out, _, err = runCommandWithOutput(cmd)
  2337. if err != nil {
  2338. t.Fatal(out, err)
  2339. }
  2340. out = strings.TrimSpace(out)
  2341. out = strings.Split(out, ":")[1]
  2342. lastPort, err := strconv.Atoi(out)
  2343. if err != nil {
  2344. t.Fatal(err)
  2345. }
  2346. port := lastPort + 1
  2347. l, err := net.Listen("tcp", ":"+strconv.Itoa(port))
  2348. if err != nil {
  2349. t.Fatal(err)
  2350. }
  2351. defer l.Close()
  2352. cmd = exec.Command(dockerBinary, "run", "-d", "-p", ":80", "busybox", "top")
  2353. out, _, err = runCommandWithOutput(cmd)
  2354. if err != nil {
  2355. t.Fatalf(out, err)
  2356. }
  2357. id = strings.TrimSpace(out)
  2358. cmd = exec.Command(dockerBinary, "port", id)
  2359. out, _, err = runCommandWithOutput(cmd)
  2360. if err != nil {
  2361. t.Fatal(out, err)
  2362. }
  2363. logDone("run - find another port if port from autorange already bound")
  2364. }
  2365. func TestRunTtyWithPipe(t *testing.T) {
  2366. defer deleteAllContainers()
  2367. done := make(chan struct{})
  2368. go func() {
  2369. defer close(done)
  2370. cmd := exec.Command(dockerBinary, "run", "-ti", "busybox", "true")
  2371. if _, err := cmd.StdinPipe(); err != nil {
  2372. t.Fatal(err)
  2373. }
  2374. expected := "cannot enable tty mode"
  2375. if out, _, err := runCommandWithOutput(cmd); err == nil {
  2376. t.Fatal("run should have failed")
  2377. } else if !strings.Contains(out, expected) {
  2378. t.Fatalf("run failed with error %q: expected %q", out, expected)
  2379. }
  2380. }()
  2381. select {
  2382. case <-done:
  2383. case <-time.After(3 * time.Second):
  2384. t.Fatal("container is running but should have failed")
  2385. }
  2386. logDone("run - forbid piped stdin with tty")
  2387. }
  2388. func TestRunNonLocalMacAddress(t *testing.T) {
  2389. defer deleteAllContainers()
  2390. addr := "00:16:3E:08:00:50"
  2391. cmd := exec.Command(dockerBinary, "run", "--mac-address", addr, "busybox", "ifconfig")
  2392. if out, _, err := runCommandWithOutput(cmd); err != nil || !strings.Contains(out, addr) {
  2393. t.Fatalf("Output should have contained %q: %s, %v", addr, out, err)
  2394. }
  2395. logDone("run - use non-local mac-address")
  2396. }
  2397. func TestRunNetHost(t *testing.T) {
  2398. defer deleteAllContainers()
  2399. hostNet, err := os.Readlink("/proc/1/ns/net")
  2400. if err != nil {
  2401. t.Fatal(err)
  2402. }
  2403. cmd := exec.Command(dockerBinary, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net")
  2404. out2, _, err := runCommandWithOutput(cmd)
  2405. if err != nil {
  2406. t.Fatal(err, out2)
  2407. }
  2408. out2 = strings.Trim(out2, "\n")
  2409. if hostNet != out2 {
  2410. t.Fatalf("Net namespace different with --net=host %s != %s\n", hostNet, out2)
  2411. }
  2412. cmd = exec.Command(dockerBinary, "run", "busybox", "readlink", "/proc/self/ns/net")
  2413. out2, _, err = runCommandWithOutput(cmd)
  2414. if err != nil {
  2415. t.Fatal(err, out2)
  2416. }
  2417. out2 = strings.Trim(out2, "\n")
  2418. if hostNet == out2 {
  2419. t.Fatalf("Net namespace should be different without --net=host %s == %s\n", hostNet, out2)
  2420. }
  2421. logDone("run - net host mode")
  2422. }
  2423. func TestRunAllowPortRangeThroughPublish(t *testing.T) {
  2424. cmd := exec.Command(dockerBinary, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top")
  2425. out, _, err := runCommandWithOutput(cmd)
  2426. defer deleteAllContainers()
  2427. id := strings.TrimSpace(out)
  2428. portstr, err := inspectFieldJSON(id, "NetworkSettings.Ports")
  2429. if err != nil {
  2430. t.Fatal(err)
  2431. }
  2432. var ports nat.PortMap
  2433. err = unmarshalJSON([]byte(portstr), &ports)
  2434. for port, binding := range ports {
  2435. portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  2436. if portnum < 3000 || portnum > 3003 {
  2437. t.Fatalf("Port is out of range ", portnum, binding, out)
  2438. }
  2439. if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  2440. t.Fatal("Port is not mapped for the port "+port, out)
  2441. }
  2442. }
  2443. logDone("run - allow port range through --expose flag")
  2444. }
  2445. func TestRunOOMExitCode(t *testing.T) {
  2446. defer deleteAllContainers()
  2447. done := make(chan struct{})
  2448. go func() {
  2449. defer close(done)
  2450. runCmd := exec.Command(dockerBinary, "run", "-m", "4MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x; done")
  2451. out, exitCode, _ := runCommandWithOutput(runCmd)
  2452. if expected := 137; exitCode != expected {
  2453. t.Fatalf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out)
  2454. }
  2455. }()
  2456. select {
  2457. case <-done:
  2458. case <-time.After(3 * time.Second):
  2459. t.Fatal("Timeout waiting for container to die on OOM")
  2460. }
  2461. logDone("run - exit code on oom")
  2462. }
  2463. func TestRunRestartMaxRetries(t *testing.T) {
  2464. defer deleteAllContainers()
  2465. out, err := exec.Command(dockerBinary, "run", "-d", "--restart=on-failure:3", "busybox", "false").CombinedOutput()
  2466. if err != nil {
  2467. t.Fatal(string(out), err)
  2468. }
  2469. id := strings.TrimSpace(string(out))
  2470. if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", 5); err != nil {
  2471. t.Fatal(err)
  2472. }
  2473. count, err := inspectField(id, "RestartCount")
  2474. if err != nil {
  2475. t.Fatal(err)
  2476. }
  2477. if count != "3" {
  2478. t.Fatalf("Container was restarted %s times, expected %d", count, 3)
  2479. }
  2480. logDone("run - test max-retries for --restart")
  2481. }