docker_cli_run_test.go 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492
  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "net"
  9. "os"
  10. "os/exec"
  11. "path"
  12. "path/filepath"
  13. "reflect"
  14. "regexp"
  15. "sort"
  16. "strings"
  17. "sync"
  18. "testing"
  19. "time"
  20. "github.com/docker/docker/pkg/mount"
  21. "github.com/docker/docker/pkg/networkfs/resolvconf"
  22. "github.com/kr/pty"
  23. )
  24. // "test123" should be printed by docker run
  25. func TestRunEchoStdout(t *testing.T) {
  26. runCmd := exec.Command(dockerBinary, "run", "busybox", "echo", "test123")
  27. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  28. if err != nil {
  29. t.Fatalf("failed to run container: %v, output: %q", err, out)
  30. }
  31. if out != "test123\n" {
  32. t.Errorf("container should've printed 'test123'")
  33. }
  34. deleteAllContainers()
  35. logDone("run - echo test123")
  36. }
  37. // "test" should be printed
  38. func TestRunEchoStdoutWithMemoryLimit(t *testing.T) {
  39. runCmd := exec.Command(dockerBinary, "run", "-m", "4m", "busybox", "echo", "test")
  40. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  41. if err != nil {
  42. t.Fatalf("failed to run container: %v, output: %q", err, out)
  43. }
  44. out = strings.Trim(out, "\r\n")
  45. if expected := "test"; out != expected {
  46. t.Errorf("container should've printed %q but printed %q", expected, out)
  47. }
  48. deleteAllContainers()
  49. logDone("run - echo with memory limit")
  50. }
  51. // "test" should be printed
  52. func TestRunEchoStdoutWitCPULimit(t *testing.T) {
  53. runCmd := exec.Command(dockerBinary, "run", "-c", "1000", "busybox", "echo", "test")
  54. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  55. if err != nil {
  56. t.Fatalf("failed to run container: %v, output: %q", err, out)
  57. }
  58. if out != "test\n" {
  59. t.Errorf("container should've printed 'test'")
  60. }
  61. deleteAllContainers()
  62. logDone("run - echo with CPU limit")
  63. }
  64. // "test" should be printed
  65. func TestRunEchoStdoutWithCPUAndMemoryLimit(t *testing.T) {
  66. runCmd := exec.Command(dockerBinary, "run", "-c", "1000", "-m", "4m", "busybox", "echo", "test")
  67. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  68. if err != nil {
  69. t.Fatalf("failed to run container: %v, output: %q", err, out)
  70. }
  71. if out != "test\n" {
  72. t.Errorf("container should've printed 'test', got %q instead", out)
  73. }
  74. deleteAllContainers()
  75. logDone("run - echo with CPU and memory limit")
  76. }
  77. // "test" should be printed
  78. func TestRunEchoNamedContainer(t *testing.T) {
  79. runCmd := exec.Command(dockerBinary, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test")
  80. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  81. if err != nil {
  82. t.Fatalf("failed to run container: %v, output: %q", err, out)
  83. }
  84. if out != "test\n" {
  85. t.Errorf("container should've printed 'test'")
  86. }
  87. if err := deleteContainer("testfoonamedcontainer"); err != nil {
  88. t.Errorf("failed to remove the named container: %v", err)
  89. }
  90. deleteAllContainers()
  91. logDone("run - echo with named container")
  92. }
  93. // docker run should not leak file descriptors
  94. func TestRunLeakyFileDescriptors(t *testing.T) {
  95. runCmd := exec.Command(dockerBinary, "run", "busybox", "ls", "-C", "/proc/self/fd")
  96. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  97. if err != nil {
  98. t.Fatalf("failed to run container: %v, output: %q", err, out)
  99. }
  100. // normally, we should only get 0, 1, and 2, but 3 gets created by "ls" when it does "opendir" on the "fd" directory
  101. if out != "0 1 2 3\n" {
  102. t.Errorf("container should've printed '0 1 2 3', not: %s", out)
  103. }
  104. deleteAllContainers()
  105. logDone("run - check file descriptor leakage")
  106. }
  107. // it should be possible to ping Google DNS resolver
  108. // this will fail when Internet access is unavailable
  109. func TestRunPingGoogle(t *testing.T) {
  110. runCmd := exec.Command(dockerBinary, "run", "busybox", "ping", "-c", "1", "8.8.8.8")
  111. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  112. if err != nil {
  113. t.Fatalf("failed to run container: %v, output: %q", err, out)
  114. }
  115. deleteAllContainers()
  116. logDone("run - ping 8.8.8.8")
  117. }
  118. // the exit code should be 0
  119. // some versions of lxc might make this test fail
  120. func TestRunExitCodeZero(t *testing.T) {
  121. runCmd := exec.Command(dockerBinary, "run", "busybox", "true")
  122. if out, _, err := runCommandWithOutput(runCmd); err != nil {
  123. t.Errorf("container should've exited with exit code 0: %s, %v", out, err)
  124. }
  125. deleteAllContainers()
  126. logDone("run - exit with 0")
  127. }
  128. // the exit code should be 1
  129. // some versions of lxc might make this test fail
  130. func TestRunExitCodeOne(t *testing.T) {
  131. runCmd := exec.Command(dockerBinary, "run", "busybox", "false")
  132. exitCode, err := runCommand(runCmd)
  133. if err != nil && !strings.Contains("exit status 1", fmt.Sprintf("%s", err)) {
  134. t.Fatal(err)
  135. }
  136. if exitCode != 1 {
  137. t.Errorf("container should've exited with exit code 1")
  138. }
  139. deleteAllContainers()
  140. logDone("run - exit with 1")
  141. }
  142. // it should be possible to pipe in data via stdin to a process running in a container
  143. // some versions of lxc might make this test fail
  144. func TestRunStdinPipe(t *testing.T) {
  145. runCmd := exec.Command("bash", "-c", `echo "blahblah" | docker run -i -a stdin busybox cat`)
  146. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  147. if err != nil {
  148. t.Fatalf("failed to run container: %v, output: %q", err, out)
  149. }
  150. out = stripTrailingCharacters(out)
  151. inspectCmd := exec.Command(dockerBinary, "inspect", out)
  152. if out, _, err := runCommandWithOutput(inspectCmd); err != nil {
  153. t.Fatalf("out should've been a container id: %s %v", out, err)
  154. }
  155. waitCmd := exec.Command(dockerBinary, "wait", out)
  156. if waitOut, _, err := runCommandWithOutput(waitCmd); err != nil {
  157. t.Fatalf("error thrown while waiting for container: %s, %v", waitOut, err)
  158. }
  159. logsCmd := exec.Command(dockerBinary, "logs", out)
  160. logsOut, _, err := runCommandWithOutput(logsCmd)
  161. if err != nil {
  162. t.Fatalf("error thrown while trying to get container logs: %s, %v", logsOut, err)
  163. }
  164. containerLogs := stripTrailingCharacters(logsOut)
  165. if containerLogs != "blahblah" {
  166. t.Errorf("logs didn't print the container's logs %s", containerLogs)
  167. }
  168. rmCmd := exec.Command(dockerBinary, "rm", out)
  169. if out, _, err = runCommandWithOutput(rmCmd); err != nil {
  170. t.Fatalf("rm failed to remove container: %s, %v", out, err)
  171. }
  172. deleteAllContainers()
  173. logDone("run - pipe in with -i -a stdin")
  174. }
  175. // the container's ID should be printed when starting a container in detached mode
  176. func TestRunDetachedContainerIDPrinting(t *testing.T) {
  177. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "true")
  178. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  179. if err != nil {
  180. t.Fatalf("failed to run container: %v, output: %q", err, out)
  181. }
  182. out = stripTrailingCharacters(out)
  183. inspectCmd := exec.Command(dockerBinary, "inspect", out)
  184. if inspectOut, _, err := runCommandWithOutput(inspectCmd); err != nil {
  185. t.Fatalf("out should've been a container id: %s %v", inspectOut, err)
  186. }
  187. waitCmd := exec.Command(dockerBinary, "wait", out)
  188. if waitOut, _, err := runCommandWithOutput(waitCmd); err != nil {
  189. t.Fatalf("error thrown while waiting for container: %s, %v", waitOut, err)
  190. }
  191. rmCmd := exec.Command(dockerBinary, "rm", out)
  192. rmOut, _, err := runCommandWithOutput(rmCmd)
  193. if err != nil {
  194. t.Fatalf("rm failed to remove container: %s, %v", rmOut, err)
  195. }
  196. rmOut = stripTrailingCharacters(rmOut)
  197. if rmOut != out {
  198. t.Errorf("rm didn't print the container ID %s %s", out, rmOut)
  199. }
  200. deleteAllContainers()
  201. logDone("run - print container ID in detached mode")
  202. }
  203. // the working directory should be set correctly
  204. func TestRunWorkingDirectory(t *testing.T) {
  205. runCmd := exec.Command(dockerBinary, "run", "-w", "/root", "busybox", "pwd")
  206. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  207. if err != nil {
  208. t.Fatalf("failed to run container: %v, output: %q", err, out)
  209. }
  210. out = stripTrailingCharacters(out)
  211. if out != "/root" {
  212. t.Errorf("-w failed to set working directory")
  213. }
  214. runCmd = exec.Command(dockerBinary, "run", "--workdir", "/root", "busybox", "pwd")
  215. out, _, _, err = runCommandWithStdoutStderr(runCmd)
  216. if err != nil {
  217. t.Fatal(out, err)
  218. }
  219. out = stripTrailingCharacters(out)
  220. if out != "/root" {
  221. t.Errorf("--workdir failed to set working directory")
  222. }
  223. deleteAllContainers()
  224. logDone("run - run with working directory set by -w")
  225. logDone("run - run with working directory set by --workdir")
  226. }
  227. // pinging Google's DNS resolver should fail when we disable the networking
  228. func TestRunWithoutNetworking(t *testing.T) {
  229. runCmd := exec.Command(dockerBinary, "run", "--net=none", "busybox", "ping", "-c", "1", "8.8.8.8")
  230. out, _, exitCode, err := runCommandWithStdoutStderr(runCmd)
  231. if err != nil && exitCode != 1 {
  232. t.Fatal(out, err)
  233. }
  234. if exitCode != 1 {
  235. t.Errorf("--net=none should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
  236. }
  237. runCmd = exec.Command(dockerBinary, "run", "-n=false", "busybox", "ping", "-c", "1", "8.8.8.8")
  238. out, _, exitCode, err = runCommandWithStdoutStderr(runCmd)
  239. if err != nil && exitCode != 1 {
  240. t.Fatal(out, err)
  241. }
  242. if exitCode != 1 {
  243. t.Errorf("-n=false should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
  244. }
  245. deleteAllContainers()
  246. logDone("run - disable networking with --net=none")
  247. logDone("run - disable networking with -n=false")
  248. }
  249. // Regression test for #4741
  250. func TestRunWithVolumesAsFiles(t *testing.T) {
  251. runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", "/etc/hosts:/target-file", "busybox", "true")
  252. out, stderr, exitCode, err := runCommandWithStdoutStderr(runCmd)
  253. if err != nil && exitCode != 0 {
  254. t.Fatal("1", out, stderr, err)
  255. }
  256. runCmd = exec.Command(dockerBinary, "run", "--volumes-from", "test-data", "busybox", "cat", "/target-file")
  257. out, stderr, exitCode, err = runCommandWithStdoutStderr(runCmd)
  258. if err != nil && exitCode != 0 {
  259. t.Fatal("2", out, stderr, err)
  260. }
  261. deleteAllContainers()
  262. logDone("run - regression test for #4741 - volumes from as files")
  263. }
  264. // Regression test for #4979
  265. func TestRunWithVolumesFromExited(t *testing.T) {
  266. runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file")
  267. out, stderr, exitCode, err := runCommandWithStdoutStderr(runCmd)
  268. if err != nil && exitCode != 0 {
  269. t.Fatal("1", out, stderr, err)
  270. }
  271. runCmd = exec.Command(dockerBinary, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file")
  272. out, stderr, exitCode, err = runCommandWithStdoutStderr(runCmd)
  273. if err != nil && exitCode != 0 {
  274. t.Fatal("2", out, stderr, err)
  275. }
  276. deleteAllContainers()
  277. logDone("run - regression test for #4979 - volumes-from on exited container")
  278. }
  279. // Regression test for #4830
  280. func TestRunWithRelativePath(t *testing.T) {
  281. runCmd := exec.Command(dockerBinary, "run", "-v", "tmp:/other-tmp", "busybox", "true")
  282. if _, _, _, err := runCommandWithStdoutStderr(runCmd); err == nil {
  283. t.Fatalf("relative path should result in an error")
  284. }
  285. deleteAllContainers()
  286. logDone("run - volume with relative path")
  287. }
  288. func TestRunVolumesMountedAsReadonly(t *testing.T) {
  289. cmd := exec.Command(dockerBinary, "run", "-v", "/test:/test:ro", "busybox", "touch", "/test/somefile")
  290. if code, err := runCommand(cmd); err == nil || code == 0 {
  291. t.Fatalf("run should fail because volume is ro: exit code %d", code)
  292. }
  293. deleteAllContainers()
  294. logDone("run - volumes as readonly mount")
  295. }
  296. func TestRunVolumesFromInReadonlyMode(t *testing.T) {
  297. cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test", "busybox", "true")
  298. if _, err := runCommand(cmd); err != nil {
  299. t.Fatal(err)
  300. }
  301. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent:ro", "busybox", "touch", "/test/file")
  302. if code, err := runCommand(cmd); err == nil || code == 0 {
  303. t.Fatalf("run should fail because volume is ro: exit code %d", code)
  304. }
  305. deleteAllContainers()
  306. logDone("run - volumes from as readonly mount")
  307. }
  308. // Regression test for #1201
  309. func TestRunVolumesFromInReadWriteMode(t *testing.T) {
  310. cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test", "busybox", "true")
  311. if _, err := runCommand(cmd); err != nil {
  312. t.Fatal(err)
  313. }
  314. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file")
  315. if out, _, err := runCommandWithOutput(cmd); err != nil {
  316. t.Fatalf("running --volumes-from parent:rw failed with output: %q\nerror: %v", out, err)
  317. }
  318. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent:bar", "busybox", "touch", "/test/file")
  319. if out, _, err := runCommandWithOutput(cmd); err == nil || !strings.Contains(out, "Invalid mode for volumes-from: bar") {
  320. t.Fatalf("running --volumes-from foo:bar should have failed with invalid mount mode: %q", out)
  321. }
  322. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent", "busybox", "touch", "/test/file")
  323. if out, _, err := runCommandWithOutput(cmd); err != nil {
  324. t.Fatalf("running --volumes-from parent failed with output: %q\nerror: %v", out, err)
  325. }
  326. deleteAllContainers()
  327. logDone("run - volumes from as read write mount")
  328. }
  329. func TestVolumesFromGetsProperMode(t *testing.T) {
  330. cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test:/test:ro", "busybox", "true")
  331. if _, err := runCommand(cmd); err != nil {
  332. t.Fatal(err)
  333. }
  334. // Expect this "rw" mode to be be ignored since the inheritted volume is "ro"
  335. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file")
  336. if _, err := runCommand(cmd); err == nil {
  337. t.Fatal("Expected volumes-from to inherit read-only volume even when passing in `rw`")
  338. }
  339. cmd = exec.Command(dockerBinary, "run", "--name", "parent2", "-v", "/test:/test:ro", "busybox", "true")
  340. if _, err := runCommand(cmd); err != nil {
  341. t.Fatal(err)
  342. }
  343. // Expect this to be read-only since both are "ro"
  344. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent2:ro", "busybox", "touch", "/test/file")
  345. if _, err := runCommand(cmd); err == nil {
  346. t.Fatal("Expected volumes-from to inherit read-only volume even when passing in `ro`")
  347. }
  348. deleteAllContainers()
  349. logDone("run - volumes from ignores `rw` if inherrited volume is `ro`")
  350. }
  351. // Test for #1351
  352. func TestRunApplyVolumesFromBeforeVolumes(t *testing.T) {
  353. cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test", "busybox", "touch", "/test/foo")
  354. if _, err := runCommand(cmd); err != nil {
  355. t.Fatal(err)
  356. }
  357. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent", "-v", "/test", "busybox", "cat", "/test/foo")
  358. if out, _, err := runCommandWithOutput(cmd); err != nil {
  359. t.Fatal(out, err)
  360. }
  361. deleteAllContainers()
  362. logDone("run - volumes from mounted first")
  363. }
  364. func TestRunMultipleVolumesFrom(t *testing.T) {
  365. cmd := exec.Command(dockerBinary, "run", "--name", "parent1", "-v", "/test", "busybox", "touch", "/test/foo")
  366. if _, err := runCommand(cmd); err != nil {
  367. t.Fatal(err)
  368. }
  369. cmd = exec.Command(dockerBinary, "run", "--name", "parent2", "-v", "/other", "busybox", "touch", "/other/bar")
  370. if _, err := runCommand(cmd); err != nil {
  371. t.Fatal(err)
  372. }
  373. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent1", "--volumes-from", "parent2",
  374. "busybox", "sh", "-c", "cat /test/foo && cat /other/bar")
  375. if _, err := runCommand(cmd); err != nil {
  376. t.Fatal(err)
  377. }
  378. deleteAllContainers()
  379. logDone("run - multiple volumes from")
  380. }
  381. // this tests verifies the ID format for the container
  382. func TestRunVerifyContainerID(t *testing.T) {
  383. cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "true")
  384. out, exit, err := runCommandWithOutput(cmd)
  385. if err != nil {
  386. t.Fatal(err)
  387. }
  388. if exit != 0 {
  389. t.Fatalf("expected exit code 0 received %d", exit)
  390. }
  391. match, err := regexp.MatchString("^[0-9a-f]{64}$", strings.TrimSuffix(out, "\n"))
  392. if err != nil {
  393. t.Fatal(err)
  394. }
  395. if !match {
  396. t.Fatalf("Invalid container ID: %s", out)
  397. }
  398. deleteAllContainers()
  399. logDone("run - verify container ID")
  400. }
  401. // Test that creating a container with a volume doesn't crash. Regression test for #995.
  402. func TestRunCreateVolume(t *testing.T) {
  403. cmd := exec.Command(dockerBinary, "run", "-v", "/var/lib/data", "busybox", "true")
  404. if _, err := runCommand(cmd); err != nil {
  405. t.Fatal(err)
  406. }
  407. deleteAllContainers()
  408. logDone("run - create docker managed volume")
  409. }
  410. // Test that creating a volume with a symlink in its path works correctly. Test for #5152.
  411. // Note that this bug happens only with symlinks with a target that starts with '/'.
  412. func TestRunCreateVolumeWithSymlink(t *testing.T) {
  413. buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-createvolumewithsymlink", "-")
  414. buildCmd.Stdin = strings.NewReader(`FROM busybox
  415. RUN mkdir /foo && ln -s /foo /bar`)
  416. buildCmd.Dir = workingDirectory
  417. err := buildCmd.Run()
  418. if err != nil {
  419. t.Fatalf("could not build 'docker-test-createvolumewithsymlink': %v", err)
  420. }
  421. cmd := exec.Command(dockerBinary, "run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", "docker-test-createvolumewithsymlink", "sh", "-c", "mount | grep -q /foo/foo")
  422. exitCode, err := runCommand(cmd)
  423. if err != nil || exitCode != 0 {
  424. t.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
  425. }
  426. var volPath string
  427. cmd = exec.Command(dockerBinary, "inspect", "-f", "{{range .Volumes}}{{.}}{{end}}", "test-createvolumewithsymlink")
  428. volPath, exitCode, err = runCommandWithOutput(cmd)
  429. if err != nil || exitCode != 0 {
  430. t.Fatalf("[inspect] err: %v, exitcode: %d", err, exitCode)
  431. }
  432. cmd = exec.Command(dockerBinary, "rm", "-v", "test-createvolumewithsymlink")
  433. exitCode, err = runCommand(cmd)
  434. if err != nil || exitCode != 0 {
  435. t.Fatalf("[rm] err: %v, exitcode: %d", err, exitCode)
  436. }
  437. f, err := os.Open(volPath)
  438. defer f.Close()
  439. if !os.IsNotExist(err) {
  440. t.Fatalf("[open] (expecting 'file does not exist' error) err: %v, volPath: %s", err, volPath)
  441. }
  442. deleteImages("docker-test-createvolumewithsymlink")
  443. deleteAllContainers()
  444. logDone("run - create volume with symlink")
  445. }
  446. // Tests that a volume path that has a symlink exists in a container mounting it with `--volumes-from`.
  447. func TestRunVolumesFromSymlinkPath(t *testing.T) {
  448. buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-volumesfromsymlinkpath", "-")
  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", "docker-test-volumesfromsymlinkpath")
  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. deleteImages("docker-test-volumesfromsymlinkpath")
  468. deleteAllContainers()
  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 := cmd(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. cmd := exec.Command(dockerBinary, "run", "--cap-drop=CHPASS", "busybox", "ls")
  711. out, _, err := runCommandWithOutput(cmd)
  712. if err == nil {
  713. t.Fatal(err, out)
  714. }
  715. logDone("run - test --cap-drop=CHPASS invalid")
  716. }
  717. func TestRunCapDropCannotMknod(t *testing.T) {
  718. cmd := exec.Command(dockerBinary, "run", "--cap-drop=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  719. out, _, err := runCommandWithOutput(cmd)
  720. if err == nil {
  721. t.Fatal(err, out)
  722. }
  723. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  724. t.Fatalf("expected output not ok received %s", actual)
  725. }
  726. deleteAllContainers()
  727. logDone("run - test --cap-drop=MKNOD cannot mknod")
  728. }
  729. func TestRunCapDropCannotMknodLowerCase(t *testing.T) {
  730. cmd := exec.Command(dockerBinary, "run", "--cap-drop=mknod", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  731. out, _, err := runCommandWithOutput(cmd)
  732. if err == nil {
  733. t.Fatal(err, out)
  734. }
  735. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  736. t.Fatalf("expected output not ok received %s", actual)
  737. }
  738. deleteAllContainers()
  739. logDone("run - test --cap-drop=mknod cannot mknod lowercase")
  740. }
  741. func TestRunCapDropALLCannotMknod(t *testing.T) {
  742. cmd := exec.Command(dockerBinary, "run", "--cap-drop=ALL", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  743. out, _, err := runCommandWithOutput(cmd)
  744. if err == nil {
  745. t.Fatal(err, out)
  746. }
  747. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  748. t.Fatalf("expected output not ok received %s", actual)
  749. }
  750. deleteAllContainers()
  751. logDone("run - test --cap-drop=ALL cannot mknod")
  752. }
  753. func TestRunCapDropALLAddMknodCannotMknod(t *testing.T) {
  754. cmd := exec.Command(dockerBinary, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  755. out, _, err := runCommandWithOutput(cmd)
  756. if err != nil {
  757. t.Fatal(err, out)
  758. }
  759. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  760. t.Fatalf("expected output ok received %s", actual)
  761. }
  762. deleteAllContainers()
  763. logDone("run - test --cap-drop=ALL --cap-add=MKNOD can mknod")
  764. }
  765. func TestRunCapAddInvalid(t *testing.T) {
  766. cmd := exec.Command(dockerBinary, "run", "--cap-add=CHPASS", "busybox", "ls")
  767. out, _, err := runCommandWithOutput(cmd)
  768. if err == nil {
  769. t.Fatal(err, out)
  770. }
  771. logDone("run - test --cap-add=CHPASS invalid")
  772. }
  773. func TestRunCapAddCanDownInterface(t *testing.T) {
  774. cmd := exec.Command(dockerBinary, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  775. out, _, err := runCommandWithOutput(cmd)
  776. if err != nil {
  777. t.Fatal(err, out)
  778. }
  779. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  780. t.Fatalf("expected output ok received %s", actual)
  781. }
  782. deleteAllContainers()
  783. logDone("run - test --cap-add=NET_ADMIN can set eth0 down")
  784. }
  785. func TestRunCapAddALLCanDownInterface(t *testing.T) {
  786. cmd := exec.Command(dockerBinary, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  787. out, _, err := runCommandWithOutput(cmd)
  788. if err != nil {
  789. t.Fatal(err, out)
  790. }
  791. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  792. t.Fatalf("expected output ok received %s", actual)
  793. }
  794. deleteAllContainers()
  795. logDone("run - test --cap-add=ALL can set eth0 down")
  796. }
  797. func TestRunCapAddALLDropNetAdminCanDownInterface(t *testing.T) {
  798. cmd := exec.Command(dockerBinary, "run", "--cap-add=ALL", "--cap-drop=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  799. out, _, err := runCommandWithOutput(cmd)
  800. if err == nil {
  801. t.Fatal(err, out)
  802. }
  803. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  804. t.Fatalf("expected output not ok received %s", actual)
  805. }
  806. deleteAllContainers()
  807. logDone("run - test --cap-add=ALL --cap-drop=NET_ADMIN cannot set eth0 down")
  808. }
  809. func TestRunPrivilegedCanMount(t *testing.T) {
  810. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
  811. out, _, err := runCommandWithOutput(cmd)
  812. if err != nil {
  813. t.Fatal(err)
  814. }
  815. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  816. t.Fatalf("expected output ok received %s", actual)
  817. }
  818. deleteAllContainers()
  819. logDone("run - test privileged can mount")
  820. }
  821. func TestRunUnPrivilegedCannotMount(t *testing.T) {
  822. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
  823. out, _, err := runCommandWithOutput(cmd)
  824. if err == nil {
  825. t.Fatal(err, out)
  826. }
  827. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  828. t.Fatalf("expected output not ok received %s", actual)
  829. }
  830. deleteAllContainers()
  831. logDone("run - test un-privileged cannot mount")
  832. }
  833. func TestRunSysNotWritableInNonPrivilegedContainers(t *testing.T) {
  834. cmd := exec.Command(dockerBinary, "run", "busybox", "touch", "/sys/kernel/profiling")
  835. if code, err := runCommand(cmd); err == nil || code == 0 {
  836. t.Fatal("sys should not be writable in a non privileged container")
  837. }
  838. deleteAllContainers()
  839. logDone("run - sys not writable in non privileged container")
  840. }
  841. func TestRunSysWritableInPrivilegedContainers(t *testing.T) {
  842. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "touch", "/sys/kernel/profiling")
  843. if code, err := runCommand(cmd); err != nil || code != 0 {
  844. t.Fatalf("sys should be writable in privileged container")
  845. }
  846. deleteAllContainers()
  847. logDone("run - sys writable in privileged container")
  848. }
  849. func TestRunProcNotWritableInNonPrivilegedContainers(t *testing.T) {
  850. cmd := exec.Command(dockerBinary, "run", "busybox", "touch", "/proc/sysrq-trigger")
  851. if code, err := runCommand(cmd); err == nil || code == 0 {
  852. t.Fatal("proc should not be writable in a non privileged container")
  853. }
  854. deleteAllContainers()
  855. logDone("run - proc not writable in non privileged container")
  856. }
  857. func TestRunProcWritableInPrivilegedContainers(t *testing.T) {
  858. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "touch", "/proc/sysrq-trigger")
  859. if code, err := runCommand(cmd); err != nil || code != 0 {
  860. t.Fatalf("proc should be writable in privileged container")
  861. }
  862. deleteAllContainers()
  863. logDone("run - proc writable in privileged container")
  864. }
  865. func TestRunWithCpuset(t *testing.T) {
  866. cmd := exec.Command(dockerBinary, "run", "--cpuset", "0", "busybox", "true")
  867. if code, err := runCommand(cmd); err != nil || code != 0 {
  868. t.Fatalf("container should run successfuly with cpuset of 0: %s", err)
  869. }
  870. deleteAllContainers()
  871. logDone("run - cpuset 0")
  872. }
  873. func TestRunDeviceNumbers(t *testing.T) {
  874. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "ls -l /dev/null")
  875. out, _, err := runCommandWithOutput(cmd)
  876. if err != nil {
  877. t.Fatal(err, out)
  878. }
  879. deviceLineFields := strings.Fields(out)
  880. deviceLineFields[6] = ""
  881. deviceLineFields[7] = ""
  882. deviceLineFields[8] = ""
  883. expected := []string{"crw-rw-rw-", "1", "root", "root", "1,", "3", "", "", "", "/dev/null"}
  884. if !(reflect.DeepEqual(deviceLineFields, expected)) {
  885. t.Fatalf("expected output\ncrw-rw-rw- 1 root root 1, 3 May 24 13:29 /dev/null\n received\n %s\n", out)
  886. }
  887. deleteAllContainers()
  888. logDone("run - test device numbers")
  889. }
  890. func TestRunThatCharacterDevicesActLikeCharacterDevices(t *testing.T) {
  891. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero")
  892. out, _, err := runCommandWithOutput(cmd)
  893. if err != nil {
  894. t.Fatal(err, out)
  895. }
  896. if actual := strings.Trim(out, "\r\n"); actual[0] == '0' {
  897. t.Fatalf("expected a new file called /zero to be create that is greater than 0 bytes long, but du says: %s", actual)
  898. }
  899. deleteAllContainers()
  900. logDone("run - test that character devices work.")
  901. }
  902. func TestRunUnprivilegedWithChroot(t *testing.T) {
  903. cmd := exec.Command(dockerBinary, "run", "busybox", "chroot", "/", "true")
  904. if _, err := runCommand(cmd); err != nil {
  905. t.Fatal(err)
  906. }
  907. deleteAllContainers()
  908. logDone("run - unprivileged with chroot")
  909. }
  910. func TestRunAddingOptionalDevices(t *testing.T) {
  911. cmd := exec.Command(dockerBinary, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo")
  912. out, _, err := runCommandWithOutput(cmd)
  913. if err != nil {
  914. t.Fatal(err, out)
  915. }
  916. if actual := strings.Trim(out, "\r\n"); actual != "/dev/nulo" {
  917. t.Fatalf("expected output /dev/nulo, received %s", actual)
  918. }
  919. deleteAllContainers()
  920. logDone("run - test --device argument")
  921. }
  922. func TestRunModeHostname(t *testing.T) {
  923. cmd := exec.Command(dockerBinary, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname")
  924. out, _, err := runCommandWithOutput(cmd)
  925. if err != nil {
  926. t.Fatal(err, out)
  927. }
  928. if actual := strings.Trim(out, "\r\n"); actual != "testhostname" {
  929. t.Fatalf("expected 'testhostname', but says: %q", actual)
  930. }
  931. cmd = exec.Command(dockerBinary, "run", "--net=host", "busybox", "cat", "/etc/hostname")
  932. out, _, err = runCommandWithOutput(cmd)
  933. if err != nil {
  934. t.Fatal(err, out)
  935. }
  936. hostname, err := os.Hostname()
  937. if err != nil {
  938. t.Fatal(err)
  939. }
  940. if actual := strings.Trim(out, "\r\n"); actual != hostname {
  941. t.Fatalf("expected %q, but says: %q", hostname, actual)
  942. }
  943. deleteAllContainers()
  944. logDone("run - hostname and several network modes")
  945. }
  946. func TestRunRootWorkdir(t *testing.T) {
  947. s, _, err := cmd(t, "run", "--workdir", "/", "busybox", "pwd")
  948. if err != nil {
  949. t.Fatal(s, err)
  950. }
  951. if s != "/\n" {
  952. t.Fatalf("pwd returned %q (expected /\\n)", s)
  953. }
  954. deleteAllContainers()
  955. logDone("run - workdir /")
  956. }
  957. func TestRunAllowBindMountingRoot(t *testing.T) {
  958. s, _, err := cmd(t, "run", "-v", "/:/host", "busybox", "ls", "/host")
  959. if err != nil {
  960. t.Fatal(s, err)
  961. }
  962. deleteAllContainers()
  963. logDone("run - bind mount / as volume")
  964. }
  965. func TestRunDisallowBindMountingRootToRoot(t *testing.T) {
  966. cmd := exec.Command(dockerBinary, "run", "-v", "/:/", "busybox", "ls", "/host")
  967. out, _, err := runCommandWithOutput(cmd)
  968. if err == nil {
  969. t.Fatal(out, err)
  970. }
  971. deleteAllContainers()
  972. logDone("run - bind mount /:/ as volume should fail")
  973. }
  974. // Test recursive bind mount works by default
  975. func TestRunWithVolumesIsRecursive(t *testing.T) {
  976. tmpDir, err := ioutil.TempDir("", "docker_recursive_mount_test")
  977. if err != nil {
  978. t.Fatal(err)
  979. }
  980. defer os.RemoveAll(tmpDir)
  981. // Create a temporary tmpfs mount.
  982. tmpfsDir := filepath.Join(tmpDir, "tmpfs")
  983. if err := os.MkdirAll(tmpfsDir, 0777); err != nil {
  984. t.Fatalf("failed to mkdir at %s - %s", tmpfsDir, err)
  985. }
  986. if err := mount.Mount("tmpfs", tmpfsDir, "tmpfs", ""); err != nil {
  987. t.Fatalf("failed to create a tmpfs mount at %s - %s", tmpfsDir, err)
  988. }
  989. f, err := ioutil.TempFile(tmpfsDir, "touch-me")
  990. if err != nil {
  991. t.Fatal(err)
  992. }
  993. defer f.Close()
  994. runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox:latest", "ls", "/tmp/tmpfs")
  995. out, stderr, exitCode, err := runCommandWithStdoutStderr(runCmd)
  996. if err != nil && exitCode != 0 {
  997. t.Fatal(out, stderr, err)
  998. }
  999. if !strings.Contains(out, filepath.Base(f.Name())) {
  1000. t.Fatal("Recursive bind mount test failed. Expected file not found")
  1001. }
  1002. deleteAllContainers()
  1003. logDone("run - volumes are bind mounted recursively")
  1004. }
  1005. func TestRunDnsDefaultOptions(t *testing.T) {
  1006. // ci server has default resolv.conf
  1007. // so rewrite it for the test
  1008. origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  1009. if os.IsNotExist(err) {
  1010. t.Fatalf("/etc/resolv.conf does not exist")
  1011. }
  1012. // test with file
  1013. tmpResolvConf := []byte("nameserver 127.0.0.1")
  1014. if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
  1015. t.Fatal(err)
  1016. }
  1017. // put the old resolvconf back
  1018. defer func() {
  1019. if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil {
  1020. t.Fatal(err)
  1021. }
  1022. }()
  1023. cmd := exec.Command(dockerBinary, "run", "busybox", "cat", "/etc/resolv.conf")
  1024. actual, _, err := runCommandWithOutput(cmd)
  1025. if err != nil {
  1026. t.Error(err, actual)
  1027. return
  1028. }
  1029. // check that the actual defaults are there
  1030. // if we ever change the defaults from google dns, this will break
  1031. expected := "\nnameserver 8.8.8.8\nnameserver 8.8.4.4"
  1032. if actual != expected {
  1033. t.Errorf("expected resolv.conf be: %q, but was: %q", expected, actual)
  1034. return
  1035. }
  1036. deleteAllContainers()
  1037. logDone("run - dns default options")
  1038. }
  1039. func TestRunDnsOptions(t *testing.T) {
  1040. cmd := exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
  1041. out, _, err := runCommandWithOutput(cmd)
  1042. if err != nil {
  1043. t.Fatal(err, out)
  1044. }
  1045. actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1)
  1046. if actual != "nameserver 127.0.0.1 search mydomain" {
  1047. t.Fatalf("expected 'nameserver 127.0.0.1 search mydomain', but says: %q", actual)
  1048. }
  1049. cmd = exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "--dns-search=.", "busybox", "cat", "/etc/resolv.conf")
  1050. out, _, err = runCommandWithOutput(cmd)
  1051. if err != nil {
  1052. t.Fatal(err, out)
  1053. }
  1054. actual = strings.Replace(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ", -1)
  1055. if actual != "nameserver 127.0.0.1" {
  1056. t.Fatalf("expected 'nameserver 127.0.0.1', but says: %q", actual)
  1057. }
  1058. logDone("run - dns options")
  1059. }
  1060. func TestRunDnsOptionsBasedOnHostResolvConf(t *testing.T) {
  1061. var out string
  1062. origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  1063. if os.IsNotExist(err) {
  1064. t.Fatalf("/etc/resolv.conf does not exist")
  1065. }
  1066. hostNamservers := resolvconf.GetNameservers(origResolvConf)
  1067. hostSearch := resolvconf.GetSearchDomains(origResolvConf)
  1068. cmd := exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf")
  1069. if out, _, err = runCommandWithOutput(cmd); err != nil {
  1070. t.Fatal(err, out)
  1071. }
  1072. if actualNameservers := resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "127.0.0.1" {
  1073. t.Fatalf("expected '127.0.0.1', but says: %q", string(actualNameservers[0]))
  1074. }
  1075. actualSearch := resolvconf.GetSearchDomains([]byte(out))
  1076. if len(actualSearch) != len(hostSearch) {
  1077. t.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch))
  1078. }
  1079. for i := range actualSearch {
  1080. if actualSearch[i] != hostSearch[i] {
  1081. t.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i])
  1082. }
  1083. }
  1084. cmd = exec.Command(dockerBinary, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
  1085. if out, _, err = runCommandWithOutput(cmd); err != nil {
  1086. t.Fatal(err, out)
  1087. }
  1088. actualNameservers := resolvconf.GetNameservers([]byte(out))
  1089. if len(actualNameservers) != len(hostNamservers) {
  1090. t.Fatalf("expected %q nameserver(s), but it has: %q", len(hostNamservers), len(actualNameservers))
  1091. }
  1092. for i := range actualNameservers {
  1093. if actualNameservers[i] != hostNamservers[i] {
  1094. t.Fatalf("expected %q nameserver, but says: %q", actualNameservers[i], hostNamservers[i])
  1095. }
  1096. }
  1097. if actualSearch = resolvconf.GetSearchDomains([]byte(out)); string(actualSearch[0]) != "mydomain" {
  1098. t.Fatalf("expected 'mydomain', but says: %q", string(actualSearch[0]))
  1099. }
  1100. // test with file
  1101. tmpResolvConf := []byte("search example.com\nnameserver 12.34.56.78\nnameserver 127.0.0.1")
  1102. if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
  1103. t.Fatal(err)
  1104. }
  1105. // put the old resolvconf back
  1106. defer func() {
  1107. if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil {
  1108. t.Fatal(err)
  1109. }
  1110. }()
  1111. resolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  1112. if os.IsNotExist(err) {
  1113. t.Fatalf("/etc/resolv.conf does not exist")
  1114. }
  1115. hostNamservers = resolvconf.GetNameservers(resolvConf)
  1116. hostSearch = resolvconf.GetSearchDomains(resolvConf)
  1117. cmd = exec.Command(dockerBinary, "run", "busybox", "cat", "/etc/resolv.conf")
  1118. if out, _, err = runCommandWithOutput(cmd); err != nil {
  1119. t.Fatal(err, out)
  1120. }
  1121. if actualNameservers = resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "12.34.56.78" || len(actualNameservers) != 1 {
  1122. t.Fatalf("expected '12.34.56.78', but has: %v", actualNameservers)
  1123. }
  1124. actualSearch = resolvconf.GetSearchDomains([]byte(out))
  1125. if len(actualSearch) != len(hostSearch) {
  1126. t.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch))
  1127. }
  1128. for i := range actualSearch {
  1129. if actualSearch[i] != hostSearch[i] {
  1130. t.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i])
  1131. }
  1132. }
  1133. deleteAllContainers()
  1134. logDone("run - dns options based on host resolv.conf")
  1135. }
  1136. func TestRunAddHost(t *testing.T) {
  1137. defer deleteAllContainers()
  1138. cmd := exec.Command(dockerBinary, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts")
  1139. out, _, err := runCommandWithOutput(cmd)
  1140. if err != nil {
  1141. t.Fatal(err, out)
  1142. }
  1143. actual := strings.Trim(out, "\r\n")
  1144. if actual != "86.75.30.9\textra" {
  1145. t.Fatalf("expected '86.75.30.9\textra', but says: %q", actual)
  1146. }
  1147. logDone("run - add-host option")
  1148. }
  1149. // Regression test for #6983
  1150. func TestRunAttachStdErrOnlyTTYMode(t *testing.T) {
  1151. cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stderr", "busybox", "true")
  1152. exitCode, err := runCommand(cmd)
  1153. if err != nil {
  1154. t.Fatal(err)
  1155. } else if exitCode != 0 {
  1156. t.Fatalf("Container should have exited with error code 0")
  1157. }
  1158. deleteAllContainers()
  1159. logDone("run - Attach stderr only with -t")
  1160. }
  1161. // Regression test for #6983
  1162. func TestRunAttachStdOutOnlyTTYMode(t *testing.T) {
  1163. cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stdout", "busybox", "true")
  1164. exitCode, err := runCommand(cmd)
  1165. if err != nil {
  1166. t.Fatal(err)
  1167. } else if exitCode != 0 {
  1168. t.Fatalf("Container should have exited with error code 0")
  1169. }
  1170. deleteAllContainers()
  1171. logDone("run - Attach stdout only with -t")
  1172. }
  1173. // Regression test for #6983
  1174. func TestRunAttachStdOutAndErrTTYMode(t *testing.T) {
  1175. cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true")
  1176. exitCode, err := runCommand(cmd)
  1177. if err != nil {
  1178. t.Fatal(err)
  1179. } else if exitCode != 0 {
  1180. t.Fatalf("Container should have exited with error code 0")
  1181. }
  1182. deleteAllContainers()
  1183. logDone("run - Attach stderr and stdout with -t")
  1184. }
  1185. func TestRunState(t *testing.T) {
  1186. defer deleteAllContainers()
  1187. cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  1188. out, _, err := runCommandWithOutput(cmd)
  1189. if err != nil {
  1190. t.Fatal(err, out)
  1191. }
  1192. id := strings.TrimSpace(out)
  1193. state, err := inspectField(id, "State.Running")
  1194. if err != nil {
  1195. t.Fatal(err)
  1196. }
  1197. if state != "true" {
  1198. t.Fatal("Container state is 'not running'")
  1199. }
  1200. pid1, err := inspectField(id, "State.Pid")
  1201. if err != nil {
  1202. t.Fatal(err)
  1203. }
  1204. if pid1 == "0" {
  1205. t.Fatal("Container state Pid 0")
  1206. }
  1207. cmd = exec.Command(dockerBinary, "stop", id)
  1208. out, _, err = runCommandWithOutput(cmd)
  1209. if err != nil {
  1210. t.Fatal(err, out)
  1211. }
  1212. state, err = inspectField(id, "State.Running")
  1213. if err != nil {
  1214. t.Fatal(err)
  1215. }
  1216. if state != "false" {
  1217. t.Fatal("Container state is 'running'")
  1218. }
  1219. pid2, err := inspectField(id, "State.Pid")
  1220. if err != nil {
  1221. t.Fatal(err)
  1222. }
  1223. if pid2 == pid1 {
  1224. t.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1225. }
  1226. cmd = exec.Command(dockerBinary, "start", id)
  1227. out, _, err = runCommandWithOutput(cmd)
  1228. if err != nil {
  1229. t.Fatal(err, out)
  1230. }
  1231. state, err = inspectField(id, "State.Running")
  1232. if err != nil {
  1233. t.Fatal(err)
  1234. }
  1235. if state != "true" {
  1236. t.Fatal("Container state is 'not running'")
  1237. }
  1238. pid3, err := inspectField(id, "State.Pid")
  1239. if err != nil {
  1240. t.Fatal(err)
  1241. }
  1242. if pid3 == pid1 {
  1243. t.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1244. }
  1245. logDone("run - test container state.")
  1246. }
  1247. // Test for #1737
  1248. func TestRunCopyVolumeUidGid(t *testing.T) {
  1249. name := "testrunvolumesuidgid"
  1250. defer deleteImages(name)
  1251. defer deleteAllContainers()
  1252. _, err := buildImage(name,
  1253. `FROM busybox
  1254. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1255. RUN echo 'dockerio:x:1001:' >> /etc/group
  1256. RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`,
  1257. true)
  1258. if err != nil {
  1259. t.Fatal(err)
  1260. }
  1261. // Test that the uid and gid is copied from the image to the volume
  1262. cmd := exec.Command(dockerBinary, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'")
  1263. out, _, err := runCommandWithOutput(cmd)
  1264. if err != nil {
  1265. t.Fatal(err, out)
  1266. }
  1267. out = strings.TrimSpace(out)
  1268. if out != "dockerio:dockerio" {
  1269. t.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out)
  1270. }
  1271. logDone("run - copy uid/gid for volume")
  1272. }
  1273. // Test for #1582
  1274. func TestRunCopyVolumeContent(t *testing.T) {
  1275. name := "testruncopyvolumecontent"
  1276. defer deleteImages(name)
  1277. defer deleteAllContainers()
  1278. _, err := buildImage(name,
  1279. `FROM busybox
  1280. RUN mkdir -p /hello/local && echo hello > /hello/local/world`,
  1281. true)
  1282. if err != nil {
  1283. t.Fatal(err)
  1284. }
  1285. // Test that the content is copied from the image to the volume
  1286. cmd := exec.Command(dockerBinary, "run", "--rm", "-v", "/hello", name, "find", "/hello")
  1287. out, _, err := runCommandWithOutput(cmd)
  1288. if err != nil {
  1289. t.Fatal(err, out)
  1290. }
  1291. if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) {
  1292. t.Fatal("Container failed to transfer content to volume")
  1293. }
  1294. logDone("run - copy volume content")
  1295. }
  1296. func TestRunCleanupCmdOnEntrypoint(t *testing.T) {
  1297. name := "testrunmdcleanuponentrypoint"
  1298. defer deleteImages(name)
  1299. defer deleteAllContainers()
  1300. if _, err := buildImage(name,
  1301. `FROM busybox
  1302. ENTRYPOINT ["echo"]
  1303. CMD ["testingpoint"]`,
  1304. true); err != nil {
  1305. t.Fatal(err)
  1306. }
  1307. runCmd := exec.Command(dockerBinary, "run", "--entrypoint", "whoami", name)
  1308. out, exit, err := runCommandWithOutput(runCmd)
  1309. if err != nil {
  1310. t.Fatalf("Error: %v, out: %q", err, out)
  1311. }
  1312. if exit != 0 {
  1313. t.Fatalf("expected exit code 0 received %d, out: %q", exit, out)
  1314. }
  1315. out = strings.TrimSpace(out)
  1316. if out != "root" {
  1317. t.Fatalf("Expected output root, got %q", out)
  1318. }
  1319. logDone("run - cleanup cmd on --entrypoint")
  1320. }
  1321. // TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected
  1322. func TestRunWorkdirExistsAndIsFile(t *testing.T) {
  1323. defer deleteAllContainers()
  1324. runCmd := exec.Command(dockerBinary, "run", "-w", "/bin/cat", "busybox")
  1325. out, exit, err := runCommandWithOutput(runCmd)
  1326. if !(err != nil && exit == 1 && strings.Contains(out, "Cannot mkdir: /bin/cat is not a directory")) {
  1327. t.Fatalf("Docker must complains about making dir, but we got out: %s, exit: %d, err: %s", out, exit, err)
  1328. }
  1329. logDone("run - error on existing file for workdir")
  1330. }
  1331. func TestRunExitOnStdinClose(t *testing.T) {
  1332. name := "testrunexitonstdinclose"
  1333. defer deleteAllContainers()
  1334. runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", "/bin/cat")
  1335. stdin, err := runCmd.StdinPipe()
  1336. if err != nil {
  1337. t.Fatal(err)
  1338. }
  1339. stdout, err := runCmd.StdoutPipe()
  1340. if err != nil {
  1341. t.Fatal(err)
  1342. }
  1343. if err := runCmd.Start(); err != nil {
  1344. t.Fatal(err)
  1345. }
  1346. if _, err := stdin.Write([]byte("hello\n")); err != nil {
  1347. t.Fatal(err)
  1348. }
  1349. r := bufio.NewReader(stdout)
  1350. line, err := r.ReadString('\n')
  1351. if err != nil {
  1352. t.Fatal(err)
  1353. }
  1354. line = strings.TrimSpace(line)
  1355. if line != "hello" {
  1356. t.Fatalf("Output should be 'hello', got '%q'", line)
  1357. }
  1358. if err := stdin.Close(); err != nil {
  1359. t.Fatal(err)
  1360. }
  1361. finish := make(chan struct{})
  1362. go func() {
  1363. if err := runCmd.Wait(); err != nil {
  1364. t.Fatal(err)
  1365. }
  1366. close(finish)
  1367. }()
  1368. select {
  1369. case <-finish:
  1370. case <-time.After(1 * time.Second):
  1371. t.Fatal("docker run failed to exit on stdin close")
  1372. }
  1373. state, err := inspectField(name, "State.Running")
  1374. if err != nil {
  1375. t.Fatal(err)
  1376. }
  1377. if state != "false" {
  1378. t.Fatal("Container must be stopped after stdin closing")
  1379. }
  1380. logDone("run - exit on stdin closing")
  1381. }
  1382. // Test for #2267
  1383. func TestRunWriteHostsFileAndNotCommit(t *testing.T) {
  1384. name := "writehosts"
  1385. cmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hosts && cat /etc/hosts")
  1386. out, _, err := runCommandWithOutput(cmd)
  1387. if err != nil {
  1388. t.Fatal(err, out)
  1389. }
  1390. if !strings.Contains(out, "test2267") {
  1391. t.Fatal("/etc/hosts should contain 'test2267'")
  1392. }
  1393. cmd = exec.Command(dockerBinary, "diff", name)
  1394. if err != nil {
  1395. t.Fatal(err, out)
  1396. }
  1397. out, _, err = runCommandWithOutput(cmd)
  1398. if err != nil {
  1399. t.Fatal(err, out)
  1400. }
  1401. if len(strings.Trim(out, "\r\n")) != 0 {
  1402. t.Fatal("diff should be empty")
  1403. }
  1404. logDone("run - write to /etc/hosts and not commited")
  1405. }
  1406. // Test for #2267
  1407. func TestRunWriteHostnameFileAndNotCommit(t *testing.T) {
  1408. name := "writehostname"
  1409. cmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hostname && cat /etc/hostname")
  1410. out, _, err := runCommandWithOutput(cmd)
  1411. if err != nil {
  1412. t.Fatal(err, out)
  1413. }
  1414. if !strings.Contains(out, "test2267") {
  1415. t.Fatal("/etc/hostname should contain 'test2267'")
  1416. }
  1417. cmd = exec.Command(dockerBinary, "diff", name)
  1418. if err != nil {
  1419. t.Fatal(err, out)
  1420. }
  1421. out, _, err = runCommandWithOutput(cmd)
  1422. if err != nil {
  1423. t.Fatal(err, out)
  1424. }
  1425. if len(strings.Trim(out, "\r\n")) != 0 {
  1426. t.Fatal("diff should be empty")
  1427. }
  1428. logDone("run - write to /etc/hostname and not commited")
  1429. }
  1430. // Test for #2267
  1431. func TestRunWriteResolvFileAndNotCommit(t *testing.T) {
  1432. name := "writeresolv"
  1433. cmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/resolv.conf && cat /etc/resolv.conf")
  1434. out, _, err := runCommandWithOutput(cmd)
  1435. if err != nil {
  1436. t.Fatal(err, out)
  1437. }
  1438. if !strings.Contains(out, "test2267") {
  1439. t.Fatal("/etc/resolv.conf should contain 'test2267'")
  1440. }
  1441. cmd = exec.Command(dockerBinary, "diff", name)
  1442. if err != nil {
  1443. t.Fatal(err, out)
  1444. }
  1445. out, _, err = runCommandWithOutput(cmd)
  1446. if err != nil {
  1447. t.Fatal(err, out)
  1448. }
  1449. if len(strings.Trim(out, "\r\n")) != 0 {
  1450. t.Fatal("diff should be empty")
  1451. }
  1452. logDone("run - write to /etc/resolv.conf and not commited")
  1453. }
  1454. func TestRunWithBadDevice(t *testing.T) {
  1455. name := "baddevice"
  1456. cmd := exec.Command(dockerBinary, "run", "--name", name, "--device", "/etc", "busybox", "true")
  1457. out, _, err := runCommandWithOutput(cmd)
  1458. if err == nil {
  1459. t.Fatal("Run should fail with bad device")
  1460. }
  1461. expected := `"/etc": not a device node`
  1462. if !strings.Contains(out, expected) {
  1463. t.Fatalf("Output should contain %q, actual out: %q", expected, out)
  1464. }
  1465. logDone("run - error with bad device")
  1466. }
  1467. func TestRunEntrypoint(t *testing.T) {
  1468. name := "entrypoint"
  1469. cmd := exec.Command(dockerBinary, "run", "--name", name, "--entrypoint", "/bin/echo", "busybox", "-n", "foobar")
  1470. out, _, err := runCommandWithOutput(cmd)
  1471. if err != nil {
  1472. t.Fatal(err, out)
  1473. }
  1474. expected := "foobar"
  1475. if out != expected {
  1476. t.Fatalf("Output should be %q, actual out: %q", expected, out)
  1477. }
  1478. logDone("run - entrypoint")
  1479. }
  1480. func TestRunBindMounts(t *testing.T) {
  1481. tmpDir, err := ioutil.TempDir("", "docker-test-container")
  1482. if err != nil {
  1483. t.Fatal(err)
  1484. }
  1485. defer os.RemoveAll(tmpDir)
  1486. writeFile(path.Join(tmpDir, "touch-me"), "", t)
  1487. // Test reading from a read-only bind mount
  1488. cmd := exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox", "ls", "/tmp")
  1489. out, _, err := runCommandWithOutput(cmd)
  1490. if err != nil {
  1491. t.Fatal(err, out)
  1492. }
  1493. if !strings.Contains(out, "touch-me") {
  1494. t.Fatal("Container failed to read from bind mount")
  1495. }
  1496. // test writing to bind mount
  1497. cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla")
  1498. out, _, err = runCommandWithOutput(cmd)
  1499. if err != nil {
  1500. t.Fatal(err, out)
  1501. }
  1502. readFile(path.Join(tmpDir, "holla"), t) // Will fail if the file doesn't exist
  1503. // test mounting to an illegal destination directory
  1504. cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:.", tmpDir), "busybox", "ls", ".")
  1505. _, err = runCommand(cmd)
  1506. if err == nil {
  1507. t.Fatal("Container bind mounted illegal directory")
  1508. }
  1509. // test mount a file
  1510. cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla")
  1511. _, err = runCommand(cmd)
  1512. if err != nil {
  1513. t.Fatal(err, out)
  1514. }
  1515. content := readFile(path.Join(tmpDir, "holla"), t) // Will fail if the file doesn't exist
  1516. expected := "yotta"
  1517. if content != expected {
  1518. t.Fatalf("Output should be %q, actual out: %q", expected, content)
  1519. }
  1520. logDone("run - bind mounts")
  1521. }
  1522. func TestRunMutableNetworkFiles(t *testing.T) {
  1523. defer deleteAllContainers()
  1524. for _, fn := range []string{"resolv.conf", "hosts"} {
  1525. deleteAllContainers()
  1526. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", "c1", "busybox", "sh", "-c", fmt.Sprintf("echo success >/etc/%s; while true; do sleep 1; done", fn)))
  1527. if err != nil {
  1528. t.Fatal(err, out)
  1529. }
  1530. time.Sleep(1 * time.Second)
  1531. contID := strings.TrimSpace(out)
  1532. f, err := os.Open(filepath.Join("/var/lib/docker/containers", contID, fn))
  1533. if err != nil {
  1534. t.Fatal(err)
  1535. }
  1536. content, err := ioutil.ReadAll(f)
  1537. f.Close()
  1538. if strings.TrimSpace(string(content)) != "success" {
  1539. t.Fatal("Content was not what was modified in the container", string(content))
  1540. }
  1541. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", "c2", "busybox", "sh", "-c", fmt.Sprintf("while true; do cat /etc/%s; sleep 1; done", fn)))
  1542. if err != nil {
  1543. t.Fatal(err)
  1544. }
  1545. contID = strings.TrimSpace(out)
  1546. resolvConfPath := filepath.Join("/var/lib/docker/containers", contID, fn)
  1547. f, err = os.OpenFile(resolvConfPath, os.O_WRONLY|os.O_SYNC|os.O_APPEND, 0644)
  1548. if err != nil {
  1549. t.Fatal(err)
  1550. }
  1551. if _, err := f.Seek(0, 0); err != nil {
  1552. f.Close()
  1553. t.Fatal(err)
  1554. }
  1555. if err := f.Truncate(0); err != nil {
  1556. f.Close()
  1557. t.Fatal(err)
  1558. }
  1559. if _, err := f.Write([]byte("success2\n")); err != nil {
  1560. f.Close()
  1561. t.Fatal(err)
  1562. }
  1563. f.Close()
  1564. time.Sleep(2 * time.Second) // don't race sleep
  1565. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "logs", "c2"))
  1566. if err != nil {
  1567. t.Fatal(err)
  1568. }
  1569. lines := strings.Split(out, "\n")
  1570. if strings.TrimSpace(lines[len(lines)-2]) != "success2" {
  1571. t.Fatalf("Did not find the correct output in /etc/%s: %s %#v", fn, out, lines)
  1572. }
  1573. }
  1574. }
  1575. // Ensure that CIDFile gets deleted if it's empty
  1576. // Perform this test by making `docker run` fail
  1577. func TestRunCidFileCleanupIfEmpty(t *testing.T) {
  1578. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1579. if err != nil {
  1580. t.Fatal(err)
  1581. }
  1582. defer os.RemoveAll(tmpDir)
  1583. tmpCidFile := path.Join(tmpDir, "cid")
  1584. cmd := exec.Command(dockerBinary, "run", "--cidfile", tmpCidFile, "scratch")
  1585. out, _, err := runCommandWithOutput(cmd)
  1586. t.Log(out)
  1587. if err == nil {
  1588. t.Fatal("Run without command must fail")
  1589. }
  1590. if _, err := os.Stat(tmpCidFile); err == nil {
  1591. t.Fatalf("empty CIDFile %q should've been deleted", tmpCidFile)
  1592. }
  1593. deleteAllContainers()
  1594. logDone("run - cleanup empty cidfile on fail")
  1595. }
  1596. // #2098 - Docker cidFiles only contain short version of the containerId
  1597. //sudo docker run --cidfile /tmp/docker_test.cid ubuntu echo "test"
  1598. // TestRunCidFile tests that run --cidfile returns the longid
  1599. func TestRunCidFileCheckIDLength(t *testing.T) {
  1600. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1601. if err != nil {
  1602. t.Fatal(err)
  1603. }
  1604. tmpCidFile := path.Join(tmpDir, "cid")
  1605. defer os.RemoveAll(tmpDir)
  1606. cmd := exec.Command(dockerBinary, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true")
  1607. out, _, err := runCommandWithOutput(cmd)
  1608. if err != nil {
  1609. t.Fatal(err)
  1610. }
  1611. id := strings.TrimSpace(out)
  1612. buffer, err := ioutil.ReadFile(tmpCidFile)
  1613. if err != nil {
  1614. t.Fatal(err)
  1615. }
  1616. cid := string(buffer)
  1617. if len(cid) != 64 {
  1618. t.Fatalf("--cidfile should be a long id, not %q", id)
  1619. }
  1620. if cid != id {
  1621. t.Fatalf("cid must be equal to %s, got %s", id, cid)
  1622. }
  1623. deleteAllContainers()
  1624. logDone("run - cidfile contains long id")
  1625. }
  1626. func TestRunNetworkNotInitializedNoneMode(t *testing.T) {
  1627. cmd := exec.Command(dockerBinary, "run", "-d", "--net=none", "busybox", "top")
  1628. out, _, err := runCommandWithOutput(cmd)
  1629. if err != nil {
  1630. t.Fatal(err)
  1631. }
  1632. id := strings.TrimSpace(out)
  1633. res, err := inspectField(id, "NetworkSettings.IPAddress")
  1634. if err != nil {
  1635. t.Fatal(err)
  1636. }
  1637. if res != "" {
  1638. t.Fatalf("For 'none' mode network must not be initialized, but container got IP: %s", res)
  1639. }
  1640. deleteAllContainers()
  1641. logDone("run - network must not be initialized in 'none' mode")
  1642. }
  1643. func TestRunDeallocatePortOnMissingIptablesRule(t *testing.T) {
  1644. cmd := exec.Command(dockerBinary, "run", "-d", "-p", "23:23", "busybox", "top")
  1645. out, _, err := runCommandWithOutput(cmd)
  1646. if err != nil {
  1647. t.Fatal(err)
  1648. }
  1649. id := strings.TrimSpace(out)
  1650. ip, err := inspectField(id, "NetworkSettings.IPAddress")
  1651. if err != nil {
  1652. t.Fatal(err)
  1653. }
  1654. iptCmd := exec.Command("iptables", "-D", "FORWARD", "-d", fmt.Sprintf("%s/32", ip),
  1655. "!", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-m", "tcp", "--dport", "23", "-j", "ACCEPT")
  1656. out, _, err = runCommandWithOutput(iptCmd)
  1657. if err != nil {
  1658. t.Fatal(err, out)
  1659. }
  1660. if err := deleteContainer(id); err != nil {
  1661. t.Fatal(err)
  1662. }
  1663. cmd = exec.Command(dockerBinary, "run", "-d", "-p", "23:23", "busybox", "top")
  1664. out, _, err = runCommandWithOutput(cmd)
  1665. if err != nil {
  1666. t.Fatal(err, out)
  1667. }
  1668. deleteAllContainers()
  1669. logDone("run - port should be deallocated even on iptables error")
  1670. }
  1671. func TestRunPortInUse(t *testing.T) {
  1672. port := "1234"
  1673. l, err := net.Listen("tcp", ":"+port)
  1674. if err != nil {
  1675. t.Fatal(err)
  1676. }
  1677. defer l.Close()
  1678. cmd := exec.Command(dockerBinary, "run", "-d", "-p", port+":80", "busybox", "top")
  1679. out, _, err := runCommandWithOutput(cmd)
  1680. if err == nil {
  1681. t.Fatalf("Binding on used port must fail")
  1682. }
  1683. if !strings.Contains(out, "address already in use") {
  1684. t.Fatalf("Out must be about \"address already in use\", got %s", out)
  1685. }
  1686. deleteAllContainers()
  1687. logDone("run - fail if port already in use")
  1688. }
  1689. // https://github.com/docker/docker/issues/8428
  1690. func TestRunPortProxy(t *testing.T) {
  1691. defer deleteAllContainers()
  1692. port := "12345"
  1693. cmd := exec.Command(dockerBinary, "run", "-d", "-p", port+":80", "busybox", "top")
  1694. out, _, err := runCommandWithOutput(cmd)
  1695. if err != nil {
  1696. t.Fatalf("Failed to run and bind port %s, output: %s, error: %s", port, out, err)
  1697. }
  1698. // connect for 10 times here. This will trigger 10 EPIPES in the child
  1699. // process and kill it when it writes to a closed stdout/stderr
  1700. for i := 0; i < 10; i++ {
  1701. net.Dial("tcp", fmt.Sprintf("0.0.0.0:%s", port))
  1702. }
  1703. listPs := exec.Command("sh", "-c", "ps ax | grep docker")
  1704. out, _, err = runCommandWithOutput(listPs)
  1705. if err != nil {
  1706. t.Errorf("list docker process failed with output %s, error %s", out, err)
  1707. }
  1708. if strings.Contains(out, "docker <defunct>") {
  1709. t.Errorf("Unexpected defunct docker process")
  1710. }
  1711. if !strings.Contains(out, "docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 12345") {
  1712. t.Errorf("Failed to find docker-proxy process, got %s", out)
  1713. }
  1714. logDone("run - proxy should work with unavailable port")
  1715. }
  1716. // Regression test for #7792
  1717. func TestRunMountOrdering(t *testing.T) {
  1718. tmpDir, err := ioutil.TempDir("", "docker_nested_mount_test")
  1719. if err != nil {
  1720. t.Fatal(err)
  1721. }
  1722. defer os.RemoveAll(tmpDir)
  1723. tmpDir2, err := ioutil.TempDir("", "docker_nested_mount_test2")
  1724. if err != nil {
  1725. t.Fatal(err)
  1726. }
  1727. defer os.RemoveAll(tmpDir2)
  1728. // Create a temporary tmpfs mount.
  1729. fooDir := filepath.Join(tmpDir, "foo")
  1730. if err := os.MkdirAll(filepath.Join(tmpDir, "foo"), 0755); err != nil {
  1731. t.Fatalf("failed to mkdir at %s - %s", fooDir, err)
  1732. }
  1733. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", fooDir), []byte{}, 0644); err != nil {
  1734. t.Fatal(err)
  1735. }
  1736. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir), []byte{}, 0644); err != nil {
  1737. t.Fatal(err)
  1738. }
  1739. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir2), []byte{}, 0644); err != nil {
  1740. t.Fatal(err)
  1741. }
  1742. 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")
  1743. out, _, err := runCommandWithOutput(cmd)
  1744. if err != nil {
  1745. t.Fatal(out, err)
  1746. }
  1747. deleteAllContainers()
  1748. logDone("run - volumes are mounted in the correct order")
  1749. }
  1750. func TestRunExecDir(t *testing.T) {
  1751. cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  1752. out, _, err := runCommandWithOutput(cmd)
  1753. if err != nil {
  1754. t.Fatal(err, out)
  1755. }
  1756. id := strings.TrimSpace(out)
  1757. execDir := filepath.Join(execDriverPath, id)
  1758. stateFile := filepath.Join(execDir, "state.json")
  1759. contFile := filepath.Join(execDir, "container.json")
  1760. {
  1761. fi, err := os.Stat(execDir)
  1762. if err != nil {
  1763. t.Fatal(err)
  1764. }
  1765. if !fi.IsDir() {
  1766. t.Fatalf("%q must be a directory", execDir)
  1767. }
  1768. fi, err = os.Stat(stateFile)
  1769. if err != nil {
  1770. t.Fatal(err)
  1771. }
  1772. fi, err = os.Stat(contFile)
  1773. if err != nil {
  1774. t.Fatal(err)
  1775. }
  1776. }
  1777. stopCmd := exec.Command(dockerBinary, "stop", id)
  1778. out, _, err = runCommandWithOutput(stopCmd)
  1779. if err != nil {
  1780. t.Fatal(err, out)
  1781. }
  1782. {
  1783. fi, err := os.Stat(execDir)
  1784. if err != nil {
  1785. t.Fatal(err)
  1786. }
  1787. if !fi.IsDir() {
  1788. t.Fatalf("%q must be a directory", execDir)
  1789. }
  1790. fi, err = os.Stat(stateFile)
  1791. if err == nil {
  1792. t.Fatalf("Statefile %q is exists for stopped container!", stateFile)
  1793. }
  1794. if !os.IsNotExist(err) {
  1795. t.Fatalf("Error should be about non-existing, got %s", err)
  1796. }
  1797. fi, err = os.Stat(contFile)
  1798. if err == nil {
  1799. t.Fatalf("Container file %q is exists for stopped container!", contFile)
  1800. }
  1801. if !os.IsNotExist(err) {
  1802. t.Fatalf("Error should be about non-existing, got %s", err)
  1803. }
  1804. }
  1805. startCmd := exec.Command(dockerBinary, "start", id)
  1806. out, _, err = runCommandWithOutput(startCmd)
  1807. if err != nil {
  1808. t.Fatal(err, out)
  1809. }
  1810. {
  1811. fi, err := os.Stat(execDir)
  1812. if err != nil {
  1813. t.Fatal(err)
  1814. }
  1815. if !fi.IsDir() {
  1816. t.Fatalf("%q must be a directory", execDir)
  1817. }
  1818. fi, err = os.Stat(stateFile)
  1819. if err != nil {
  1820. t.Fatal(err)
  1821. }
  1822. fi, err = os.Stat(contFile)
  1823. if err != nil {
  1824. t.Fatal(err)
  1825. }
  1826. }
  1827. rmCmd := exec.Command(dockerBinary, "rm", "-f", id)
  1828. out, _, err = runCommandWithOutput(rmCmd)
  1829. if err != nil {
  1830. t.Fatal(err, out)
  1831. }
  1832. {
  1833. _, err := os.Stat(execDir)
  1834. if err == nil {
  1835. t.Fatal(err)
  1836. }
  1837. if err == nil {
  1838. t.Fatalf("Exec directory %q is exists for removed container!", execDir)
  1839. }
  1840. if !os.IsNotExist(err) {
  1841. t.Fatalf("Error should be about non-existing, got %s", err)
  1842. }
  1843. }
  1844. logDone("run - check execdriver dir behavior")
  1845. }
  1846. // #6509
  1847. func TestRunRedirectStdout(t *testing.T) {
  1848. defer deleteAllContainers()
  1849. checkRedirect := func(command string) {
  1850. _, tty, err := pty.Open()
  1851. if err != nil {
  1852. t.Fatalf("Could not open pty: %v", err)
  1853. }
  1854. cmd := exec.Command("sh", "-c", command)
  1855. cmd.Stdin = tty
  1856. cmd.Stdout = tty
  1857. cmd.Stderr = tty
  1858. ch := make(chan struct{})
  1859. if err := cmd.Start(); err != nil {
  1860. t.Fatalf("start err: %v", err)
  1861. }
  1862. go func() {
  1863. if err := cmd.Wait(); err != nil {
  1864. t.Fatalf("wait err=%v", err)
  1865. }
  1866. close(ch)
  1867. }()
  1868. select {
  1869. case <-time.After(10 * time.Second):
  1870. t.Fatal("command timeout")
  1871. case <-ch:
  1872. }
  1873. }
  1874. checkRedirect(dockerBinary + " run -i busybox cat /etc/passwd | grep -q root")
  1875. checkRedirect(dockerBinary + " run busybox cat /etc/passwd | grep -q root")
  1876. logDone("run - redirect stdout")
  1877. }
  1878. // Regression test for https://github.com/docker/docker/issues/8259
  1879. func TestRunReuseBindVolumeThatIsSymlink(t *testing.T) {
  1880. tmpDir, err := ioutil.TempDir(os.TempDir(), "testlink")
  1881. if err != nil {
  1882. t.Fatal(err)
  1883. }
  1884. defer os.RemoveAll(tmpDir)
  1885. linkPath := os.TempDir() + "/testlink2"
  1886. if err := os.Symlink(tmpDir, linkPath); err != nil {
  1887. t.Fatal(err)
  1888. }
  1889. defer os.RemoveAll(linkPath)
  1890. // Create first container
  1891. cmd := exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
  1892. if _, err := runCommand(cmd); err != nil {
  1893. t.Fatal(err)
  1894. }
  1895. // Create second container with same symlinked path
  1896. // This will fail if the referenced issue is hit with a "Volume exists" error
  1897. cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
  1898. if out, _, err := runCommandWithOutput(cmd); err != nil {
  1899. t.Fatal(err, out)
  1900. }
  1901. deleteAllContainers()
  1902. logDone("run - can remount old bindmount volume")
  1903. }
  1904. func TestVolumesNoCopyData(t *testing.T) {
  1905. defer deleteImages("dataimage")
  1906. defer deleteAllContainers()
  1907. if _, err := buildImage("dataimage",
  1908. `FROM busybox
  1909. RUN mkdir -p /foo
  1910. RUN touch /foo/bar`,
  1911. true); err != nil {
  1912. t.Fatal(err)
  1913. }
  1914. cmd := exec.Command(dockerBinary, "run", "--name", "test", "-v", "/foo", "busybox")
  1915. if _, err := runCommand(cmd); err != nil {
  1916. t.Fatal(err)
  1917. }
  1918. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "test", "dataimage", "ls", "-lh", "/foo/bar")
  1919. if out, _, err := runCommandWithOutput(cmd); err == nil || !strings.Contains(out, "No such file or directory") {
  1920. t.Fatalf("Data was copied on volumes-from but shouldn't be:\n%q", out)
  1921. }
  1922. tmpDir, err := ioutil.TempDir("", "docker_test_bind_mount_copy_data")
  1923. if err != nil {
  1924. t.Fatal(err)
  1925. }
  1926. defer os.RemoveAll(tmpDir)
  1927. cmd = exec.Command(dockerBinary, "run", "-v", tmpDir+":/foo", "dataimage", "ls", "-lh", "/foo/bar")
  1928. if out, _, err := runCommandWithOutput(cmd); err == nil || !strings.Contains(out, "No such file or directory") {
  1929. t.Fatalf("Data was copied on bind-mount but shouldn't be:\n%q", out)
  1930. }
  1931. logDone("run - volumes do not copy data for volumes-from and bindmounts")
  1932. }
  1933. func TestRunVolumesNotRecreatedOnStart(t *testing.T) {
  1934. // Clear out any remnants from other tests
  1935. deleteAllContainers()
  1936. info, err := ioutil.ReadDir(volumesConfigPath)
  1937. if err != nil {
  1938. t.Fatal(err)
  1939. }
  1940. if len(info) > 0 {
  1941. for _, f := range info {
  1942. if err := os.RemoveAll(volumesConfigPath + "/" + f.Name()); err != nil {
  1943. t.Fatal(err)
  1944. }
  1945. }
  1946. }
  1947. defer deleteAllContainers()
  1948. cmd := exec.Command(dockerBinary, "run", "-v", "/foo", "--name", "lone_starr", "busybox")
  1949. if _, err := runCommand(cmd); err != nil {
  1950. t.Fatal(err)
  1951. }
  1952. cmd = exec.Command(dockerBinary, "start", "lone_starr")
  1953. if _, err := runCommand(cmd); err != nil {
  1954. t.Fatal(err)
  1955. }
  1956. info, err = ioutil.ReadDir(volumesConfigPath)
  1957. if err != nil {
  1958. t.Fatal(err)
  1959. }
  1960. if len(info) != 1 {
  1961. t.Fatalf("Expected only 1 volume have %v", len(info))
  1962. }
  1963. logDone("run - volumes not recreated on start")
  1964. }
  1965. func TestRunNoOutputFromPullInStdout(t *testing.T) {
  1966. defer deleteAllContainers()
  1967. // just run with unknown image
  1968. cmd := exec.Command(dockerBinary, "run", "asdfsg")
  1969. stdout := bytes.NewBuffer(nil)
  1970. cmd.Stdout = stdout
  1971. if err := cmd.Run(); err == nil {
  1972. t.Fatal("Run with unknown image should fail")
  1973. }
  1974. if stdout.Len() != 0 {
  1975. t.Fatalf("Stdout contains output from pull: %s", stdout)
  1976. }
  1977. logDone("run - no output from pull in stdout")
  1978. }
  1979. func TestRunVolumesCleanPaths(t *testing.T) {
  1980. defer deleteAllContainers()
  1981. if _, err := buildImage("run_volumes_clean_paths",
  1982. `FROM busybox
  1983. VOLUME /foo/`,
  1984. true); err != nil {
  1985. t.Fatal(err)
  1986. }
  1987. defer deleteImages("run_volumes_clean_paths")
  1988. cmd := exec.Command(dockerBinary, "run", "-v", "/foo", "-v", "/bar/", "--name", "dark_helmet", "run_volumes_clean_paths")
  1989. if out, _, err := runCommandWithOutput(cmd); err != nil {
  1990. t.Fatal(err, out)
  1991. }
  1992. out, err := inspectFieldMap("dark_helmet", "Volumes", "/foo/")
  1993. if err != nil {
  1994. t.Fatal(err)
  1995. }
  1996. if out != "<no value>" {
  1997. t.Fatalf("Found unexpected volume entry for '/foo/' in volumes\n%q", out)
  1998. }
  1999. out, err = inspectFieldMap("dark_helmet", "Volumes", "/foo")
  2000. if err != nil {
  2001. t.Fatal(err)
  2002. }
  2003. if !strings.Contains(out, volumesStoragePath) {
  2004. t.Fatalf("Volume was not defined for /foo\n%q", out)
  2005. }
  2006. out, err = inspectFieldMap("dark_helmet", "Volumes", "/bar/")
  2007. if err != nil {
  2008. t.Fatal(err)
  2009. }
  2010. if out != "<no value>" {
  2011. t.Fatalf("Found unexpected volume entry for '/bar/' in volumes\n%q", out)
  2012. }
  2013. out, err = inspectFieldMap("dark_helmet", "Volumes", "/bar")
  2014. if err != nil {
  2015. t.Fatal(err)
  2016. }
  2017. if !strings.Contains(out, volumesStoragePath) {
  2018. t.Fatalf("Volume was not defined for /bar\n%q", out)
  2019. }
  2020. logDone("run - volume paths are cleaned")
  2021. }
  2022. // Regression test for #3631
  2023. func TestRunSlowStdoutConsumer(t *testing.T) {
  2024. defer deleteAllContainers()
  2025. 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"`)
  2026. stdout, err := c.StdoutPipe()
  2027. if err != nil {
  2028. t.Fatal(err)
  2029. }
  2030. if err := c.Start(); err != nil {
  2031. t.Fatal(err)
  2032. }
  2033. n, err := consumeSlow(stdout, 10000, 5*time.Millisecond)
  2034. if err != nil {
  2035. t.Fatal(err)
  2036. }
  2037. expected := 2 * 1024 * 2000
  2038. if n != expected {
  2039. t.Fatalf("Expected %d, got %d", expected, n)
  2040. }
  2041. logDone("run - slow consumer")
  2042. }
  2043. func consumeSlow(reader io.Reader, chunkSize int, interval time.Duration) (n int, err error) {
  2044. buffer := make([]byte, chunkSize)
  2045. for {
  2046. var readBytes int
  2047. readBytes, err = reader.Read(buffer)
  2048. n += readBytes
  2049. if err != nil {
  2050. if err == io.EOF {
  2051. err = nil
  2052. }
  2053. return
  2054. }
  2055. time.Sleep(interval)
  2056. }
  2057. }