docker_cli_run_test.go 73 KB

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