docker_cli_run_test.go 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "os/exec"
  9. "path"
  10. "path/filepath"
  11. "reflect"
  12. "regexp"
  13. "sort"
  14. "strings"
  15. "sync"
  16. "testing"
  17. "time"
  18. "github.com/docker/docker/pkg/mount"
  19. "github.com/docker/docker/pkg/networkfs/resolvconf"
  20. )
  21. // "test123" should be printed by docker run
  22. func TestRunEchoStdout(t *testing.T) {
  23. runCmd := exec.Command(dockerBinary, "run", "busybox", "echo", "test123")
  24. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  25. if err != nil {
  26. t.Fatalf("failed to run container: %v, output: %q", err, out)
  27. }
  28. if out != "test123\n" {
  29. t.Errorf("container should've printed 'test123'")
  30. }
  31. deleteAllContainers()
  32. logDone("run - echo test123")
  33. }
  34. // "test" should be printed
  35. func TestRunEchoStdoutWithMemoryLimit(t *testing.T) {
  36. runCmd := exec.Command(dockerBinary, "run", "-m", "2786432", "busybox", "echo", "test")
  37. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  38. if err != nil {
  39. t.Fatalf("failed to run container: %v, output: %q", err, out)
  40. }
  41. out = strings.Trim(out, "\r\n")
  42. if expected := "test"; out != expected {
  43. t.Errorf("container should've printed %q but printed %q", expected, out)
  44. }
  45. deleteAllContainers()
  46. logDone("run - echo with memory limit")
  47. }
  48. // "test" should be printed
  49. func TestRunEchoStdoutWitCPULimit(t *testing.T) {
  50. runCmd := exec.Command(dockerBinary, "run", "-c", "1000", "busybox", "echo", "test")
  51. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  52. if err != nil {
  53. t.Fatalf("failed to run container: %v, output: %q", err, out)
  54. }
  55. if out != "test\n" {
  56. t.Errorf("container should've printed 'test'")
  57. }
  58. deleteAllContainers()
  59. logDone("run - echo with CPU limit")
  60. }
  61. // "test" should be printed
  62. func TestRunEchoStdoutWithCPUAndMemoryLimit(t *testing.T) {
  63. runCmd := exec.Command(dockerBinary, "run", "-c", "1000", "-m", "2786432", "busybox", "echo", "test")
  64. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  65. if err != nil {
  66. t.Fatalf("failed to run container: %v, output: %q", err, out)
  67. }
  68. if out != "test\n" {
  69. t.Errorf("container should've printed 'test', got %q instead", out)
  70. }
  71. deleteAllContainers()
  72. logDone("run - echo with CPU and memory limit")
  73. }
  74. // "test" should be printed
  75. func TestRunEchoNamedContainer(t *testing.T) {
  76. runCmd := exec.Command(dockerBinary, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test")
  77. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  78. if err != nil {
  79. t.Fatalf("failed to run container: %v, output: %q", err, out)
  80. }
  81. if out != "test\n" {
  82. t.Errorf("container should've printed 'test'")
  83. }
  84. if err := deleteContainer("testfoonamedcontainer"); err != nil {
  85. t.Errorf("failed to remove the named container: %v", err)
  86. }
  87. deleteAllContainers()
  88. logDone("run - echo with named container")
  89. }
  90. // docker run should not leak file descriptors
  91. func TestRunLeakyFileDescriptors(t *testing.T) {
  92. runCmd := exec.Command(dockerBinary, "run", "busybox", "ls", "-C", "/proc/self/fd")
  93. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  94. if err != nil {
  95. t.Fatalf("failed to run container: %v, output: %q", err, out)
  96. }
  97. // normally, we should only get 0, 1, and 2, but 3 gets created by "ls" when it does "opendir" on the "fd" directory
  98. if out != "0 1 2 3\n" {
  99. t.Errorf("container should've printed '0 1 2 3', not: %s", out)
  100. }
  101. deleteAllContainers()
  102. logDone("run - check file descriptor leakage")
  103. }
  104. // it should be possible to ping Google DNS resolver
  105. // this will fail when Internet access is unavailable
  106. func TestRunPingGoogle(t *testing.T) {
  107. runCmd := exec.Command(dockerBinary, "run", "busybox", "ping", "-c", "1", "8.8.8.8")
  108. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  109. if err != nil {
  110. t.Fatalf("failed to run container: %v, output: %q", err, out)
  111. }
  112. errorOut(err, t, "container should've been able to ping 8.8.8.8")
  113. deleteAllContainers()
  114. logDone("run - ping 8.8.8.8")
  115. }
  116. // the exit code should be 0
  117. // some versions of lxc might make this test fail
  118. func TestRunExitCodeZero(t *testing.T) {
  119. runCmd := exec.Command(dockerBinary, "run", "busybox", "true")
  120. exitCode, err := runCommand(runCmd)
  121. errorOut(err, t, fmt.Sprintf("%s", err))
  122. if exitCode != 0 {
  123. t.Errorf("container should've exited with exit code 0")
  124. }
  125. deleteAllContainers()
  126. logDone("run - exit with 0")
  127. }
  128. // the exit code should be 1
  129. // some versions of lxc might make this test fail
  130. func TestRunExitCodeOne(t *testing.T) {
  131. runCmd := exec.Command(dockerBinary, "run", "busybox", "false")
  132. exitCode, err := runCommand(runCmd)
  133. if err != nil && !strings.Contains("exit status 1", fmt.Sprintf("%s", err)) {
  134. t.Fatal(err)
  135. }
  136. if exitCode != 1 {
  137. t.Errorf("container should've exited with exit code 1")
  138. }
  139. deleteAllContainers()
  140. logDone("run - exit with 1")
  141. }
  142. // it should be possible to pipe in data via stdin to a process running in a container
  143. // some versions of lxc might make this test fail
  144. func TestRunStdinPipe(t *testing.T) {
  145. runCmd := exec.Command("bash", "-c", `echo "blahblah" | docker run -i -a stdin busybox cat`)
  146. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  147. if err != nil {
  148. t.Fatalf("failed to run container: %v, output: %q", err, out)
  149. }
  150. out = stripTrailingCharacters(out)
  151. inspectCmd := exec.Command(dockerBinary, "inspect", out)
  152. inspectOut, _, err := runCommandWithOutput(inspectCmd)
  153. errorOut(err, t, fmt.Sprintf("out should've been a container id: %s %s", out, inspectOut))
  154. waitCmd := exec.Command(dockerBinary, "wait", out)
  155. _, _, err = runCommandWithOutput(waitCmd)
  156. errorOut(err, t, fmt.Sprintf("error thrown while waiting for container: %s", out))
  157. logsCmd := exec.Command(dockerBinary, "logs", out)
  158. containerLogs, _, err := runCommandWithOutput(logsCmd)
  159. errorOut(err, t, fmt.Sprintf("error thrown while trying to get container logs: %s", err))
  160. containerLogs = stripTrailingCharacters(containerLogs)
  161. if containerLogs != "blahblah" {
  162. t.Errorf("logs didn't print the container's logs %s", containerLogs)
  163. }
  164. rmCmd := exec.Command(dockerBinary, "rm", out)
  165. _, _, err = runCommandWithOutput(rmCmd)
  166. errorOut(err, t, fmt.Sprintf("rm failed to remove container %s", err))
  167. deleteAllContainers()
  168. logDone("run - pipe in with -i -a stdin")
  169. }
  170. // the container's ID should be printed when starting a container in detached mode
  171. func TestRunDetachedContainerIDPrinting(t *testing.T) {
  172. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "true")
  173. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  174. if err != nil {
  175. t.Fatalf("failed to run container: %v, output: %q", err, out)
  176. }
  177. out = stripTrailingCharacters(out)
  178. inspectCmd := exec.Command(dockerBinary, "inspect", out)
  179. inspectOut, _, err := runCommandWithOutput(inspectCmd)
  180. errorOut(err, t, fmt.Sprintf("out should've been a container id: %s %s", out, inspectOut))
  181. waitCmd := exec.Command(dockerBinary, "wait", out)
  182. _, _, err = runCommandWithOutput(waitCmd)
  183. errorOut(err, t, fmt.Sprintf("error thrown while waiting for container: %s", out))
  184. rmCmd := exec.Command(dockerBinary, "rm", out)
  185. rmOut, _, err := runCommandWithOutput(rmCmd)
  186. errorOut(err, t, "rm failed to remove container")
  187. rmOut = stripTrailingCharacters(rmOut)
  188. if rmOut != out {
  189. t.Errorf("rm didn't print the container ID %s %s", out, rmOut)
  190. }
  191. deleteAllContainers()
  192. logDone("run - print container ID in detached mode")
  193. }
  194. // the working directory should be set correctly
  195. func TestRunWorkingDirectory(t *testing.T) {
  196. runCmd := exec.Command(dockerBinary, "run", "-w", "/root", "busybox", "pwd")
  197. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  198. if err != nil {
  199. t.Fatalf("failed to run container: %v, output: %q", err, out)
  200. }
  201. out = stripTrailingCharacters(out)
  202. if out != "/root" {
  203. t.Errorf("-w failed to set working directory")
  204. }
  205. runCmd = exec.Command(dockerBinary, "run", "--workdir", "/root", "busybox", "pwd")
  206. out, _, _, err = runCommandWithStdoutStderr(runCmd)
  207. errorOut(err, t, out)
  208. out = stripTrailingCharacters(out)
  209. if out != "/root" {
  210. t.Errorf("--workdir failed to set working directory")
  211. }
  212. deleteAllContainers()
  213. logDone("run - run with working directory set by -w")
  214. logDone("run - run with working directory set by --workdir")
  215. }
  216. // pinging Google's DNS resolver should fail when we disable the networking
  217. func TestRunWithoutNetworking(t *testing.T) {
  218. runCmd := exec.Command(dockerBinary, "run", "--net=none", "busybox", "ping", "-c", "1", "8.8.8.8")
  219. out, _, exitCode, err := runCommandWithStdoutStderr(runCmd)
  220. if err != nil && exitCode != 1 {
  221. t.Fatal(out, err)
  222. }
  223. if exitCode != 1 {
  224. t.Errorf("--net=none should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
  225. }
  226. runCmd = exec.Command(dockerBinary, "run", "-n=false", "busybox", "ping", "-c", "1", "8.8.8.8")
  227. out, _, exitCode, err = runCommandWithStdoutStderr(runCmd)
  228. if err != nil && exitCode != 1 {
  229. t.Fatal(out, err)
  230. }
  231. if exitCode != 1 {
  232. t.Errorf("-n=false should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
  233. }
  234. deleteAllContainers()
  235. logDone("run - disable networking with --net=none")
  236. logDone("run - disable networking with -n=false")
  237. }
  238. // Regression test for #4741
  239. func TestRunWithVolumesAsFiles(t *testing.T) {
  240. runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", "/etc/hosts:/target-file", "busybox", "true")
  241. out, stderr, exitCode, err := runCommandWithStdoutStderr(runCmd)
  242. if err != nil && exitCode != 0 {
  243. t.Fatal("1", out, stderr, err)
  244. }
  245. runCmd = exec.Command(dockerBinary, "run", "--volumes-from", "test-data", "busybox", "cat", "/target-file")
  246. out, stderr, exitCode, err = runCommandWithStdoutStderr(runCmd)
  247. if err != nil && exitCode != 0 {
  248. t.Fatal("2", out, stderr, err)
  249. }
  250. deleteAllContainers()
  251. logDone("run - regression test for #4741 - volumes from as files")
  252. }
  253. // Regression test for #4979
  254. func TestRunWithVolumesFromExited(t *testing.T) {
  255. runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file")
  256. out, stderr, exitCode, err := runCommandWithStdoutStderr(runCmd)
  257. if err != nil && exitCode != 0 {
  258. t.Fatal("1", out, stderr, err)
  259. }
  260. runCmd = exec.Command(dockerBinary, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file")
  261. out, stderr, exitCode, err = runCommandWithStdoutStderr(runCmd)
  262. if err != nil && exitCode != 0 {
  263. t.Fatal("2", out, stderr, err)
  264. }
  265. deleteAllContainers()
  266. logDone("run - regression test for #4979 - volumes-from on exited container")
  267. }
  268. // Regression test for #4830
  269. func TestRunWithRelativePath(t *testing.T) {
  270. runCmd := exec.Command(dockerBinary, "run", "-v", "tmp:/other-tmp", "busybox", "true")
  271. if _, _, _, err := runCommandWithStdoutStderr(runCmd); err == nil {
  272. t.Fatalf("relative path should result in an error")
  273. }
  274. deleteAllContainers()
  275. logDone("run - volume with relative path")
  276. }
  277. func TestRunVolumesMountedAsReadonly(t *testing.T) {
  278. cmd := exec.Command(dockerBinary, "run", "-v", "/test:/test:ro", "busybox", "touch", "/test/somefile")
  279. if code, err := runCommand(cmd); err == nil || code == 0 {
  280. t.Fatalf("run should fail because volume is ro: exit code %d", code)
  281. }
  282. deleteAllContainers()
  283. logDone("run - volumes as readonly mount")
  284. }
  285. func TestRunVolumesFromInReadonlyMode(t *testing.T) {
  286. cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test", "busybox", "true")
  287. if _, err := runCommand(cmd); err != nil {
  288. t.Fatal(err)
  289. }
  290. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent:ro", "busybox", "touch", "/test/file")
  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 from as readonly mount")
  296. }
  297. // Regression test for #1201
  298. func TestRunVolumesFromInReadWriteMode(t *testing.T) {
  299. cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test", "busybox", "true")
  300. if _, err := runCommand(cmd); err != nil {
  301. t.Fatal(err)
  302. }
  303. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent", "busybox", "touch", "/test/file")
  304. if _, err := runCommand(cmd); err != nil {
  305. t.Fatal(err)
  306. }
  307. deleteAllContainers()
  308. logDone("run - volumes from as read write mount")
  309. }
  310. func TestVolumesFromGetsProperMode(t *testing.T) {
  311. cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test:/test:ro", "busybox", "true")
  312. if _, err := runCommand(cmd); err != nil {
  313. t.Fatal(err)
  314. }
  315. // Expect this "rw" mode to be be ignored since the inheritted volume is "ro"
  316. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file")
  317. if _, err := runCommand(cmd); err == nil {
  318. t.Fatal("Expected volumes-from to inherit read-only volume even when passing in `rw`")
  319. }
  320. cmd = exec.Command(dockerBinary, "run", "--name", "parent2", "-v", "/test:/test:ro", "busybox", "true")
  321. if _, err := runCommand(cmd); err != nil {
  322. t.Fatal(err)
  323. }
  324. // Expect this to be read-only since both are "ro"
  325. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent2:ro", "busybox", "touch", "/test/file")
  326. if _, err := runCommand(cmd); err == nil {
  327. t.Fatal("Expected volumes-from to inherit read-only volume even when passing in `ro`")
  328. }
  329. deleteAllContainers()
  330. logDone("run - volumes from ignores `rw` if inherrited volume is `ro`")
  331. }
  332. // Test for #1351
  333. func TestRunApplyVolumesFromBeforeVolumes(t *testing.T) {
  334. cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test", "busybox", "touch", "/test/foo")
  335. if _, err := runCommand(cmd); err != nil {
  336. t.Fatal(err)
  337. }
  338. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent", "-v", "/test", "busybox", "cat", "/test/foo")
  339. if out, _, err := runCommandWithOutput(cmd); err != nil {
  340. t.Fatal(out, err)
  341. }
  342. deleteAllContainers()
  343. logDone("run - volumes from mounted first")
  344. }
  345. func TestRunMultipleVolumesFrom(t *testing.T) {
  346. cmd := exec.Command(dockerBinary, "run", "--name", "parent1", "-v", "/test", "busybox", "touch", "/test/foo")
  347. if _, err := runCommand(cmd); err != nil {
  348. t.Fatal(err)
  349. }
  350. cmd = exec.Command(dockerBinary, "run", "--name", "parent2", "-v", "/other", "busybox", "touch", "/other/bar")
  351. if _, err := runCommand(cmd); err != nil {
  352. t.Fatal(err)
  353. }
  354. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent1", "--volumes-from", "parent2",
  355. "busybox", "sh", "-c", "cat /test/foo && cat /other/bar")
  356. if _, err := runCommand(cmd); err != nil {
  357. t.Fatal(err)
  358. }
  359. deleteAllContainers()
  360. logDone("run - multiple volumes from")
  361. }
  362. // this tests verifies the ID format for the container
  363. func TestRunVerifyContainerID(t *testing.T) {
  364. cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "true")
  365. out, exit, err := runCommandWithOutput(cmd)
  366. if err != nil {
  367. t.Fatal(err)
  368. }
  369. if exit != 0 {
  370. t.Fatalf("expected exit code 0 received %d", exit)
  371. }
  372. match, err := regexp.MatchString("^[0-9a-f]{64}$", strings.TrimSuffix(out, "\n"))
  373. if err != nil {
  374. t.Fatal(err)
  375. }
  376. if !match {
  377. t.Fatalf("Invalid container ID: %s", out)
  378. }
  379. deleteAllContainers()
  380. logDone("run - verify container ID")
  381. }
  382. // Test that creating a container with a volume doesn't crash. Regression test for #995.
  383. func TestRunCreateVolume(t *testing.T) {
  384. cmd := exec.Command(dockerBinary, "run", "-v", "/var/lib/data", "busybox", "true")
  385. if _, err := runCommand(cmd); err != nil {
  386. t.Fatal(err)
  387. }
  388. deleteAllContainers()
  389. logDone("run - create docker managed volume")
  390. }
  391. // Test that creating a volume with a symlink in its path works correctly. Test for #5152.
  392. // Note that this bug happens only with symlinks with a target that starts with '/'.
  393. func TestRunCreateVolumeWithSymlink(t *testing.T) {
  394. buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-createvolumewithsymlink", "-")
  395. buildCmd.Stdin = strings.NewReader(`FROM busybox
  396. RUN mkdir /foo && ln -s /foo /bar`)
  397. buildCmd.Dir = workingDirectory
  398. err := buildCmd.Run()
  399. if err != nil {
  400. t.Fatalf("could not build 'docker-test-createvolumewithsymlink': %v", err)
  401. }
  402. cmd := exec.Command(dockerBinary, "run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", "docker-test-createvolumewithsymlink", "sh", "-c", "mount | grep -q /foo/foo")
  403. exitCode, err := runCommand(cmd)
  404. if err != nil || exitCode != 0 {
  405. t.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
  406. }
  407. var volPath string
  408. cmd = exec.Command(dockerBinary, "inspect", "-f", "{{range .Volumes}}{{.}}{{end}}", "test-createvolumewithsymlink")
  409. volPath, exitCode, err = runCommandWithOutput(cmd)
  410. if err != nil || exitCode != 0 {
  411. t.Fatalf("[inspect] err: %v, exitcode: %d", err, exitCode)
  412. }
  413. cmd = exec.Command(dockerBinary, "rm", "-v", "test-createvolumewithsymlink")
  414. exitCode, err = runCommand(cmd)
  415. if err != nil || exitCode != 0 {
  416. t.Fatalf("[rm] err: %v, exitcode: %d", err, exitCode)
  417. }
  418. f, err := os.Open(volPath)
  419. defer f.Close()
  420. if !os.IsNotExist(err) {
  421. t.Fatalf("[open] (expecting 'file does not exist' error) err: %v, volPath: %s", err, volPath)
  422. }
  423. deleteImages("docker-test-createvolumewithsymlink")
  424. deleteAllContainers()
  425. logDone("run - create volume with symlink")
  426. }
  427. // Tests that a volume path that has a symlink exists in a container mounting it with `--volumes-from`.
  428. func TestRunVolumesFromSymlinkPath(t *testing.T) {
  429. buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-volumesfromsymlinkpath", "-")
  430. buildCmd.Stdin = strings.NewReader(`FROM busybox
  431. RUN mkdir /baz && ln -s /baz /foo
  432. VOLUME ["/foo/bar"]`)
  433. buildCmd.Dir = workingDirectory
  434. err := buildCmd.Run()
  435. if err != nil {
  436. t.Fatalf("could not build 'docker-test-volumesfromsymlinkpath': %v", err)
  437. }
  438. cmd := exec.Command(dockerBinary, "run", "--name", "test-volumesfromsymlinkpath", "docker-test-volumesfromsymlinkpath")
  439. exitCode, err := runCommand(cmd)
  440. if err != nil || exitCode != 0 {
  441. t.Fatalf("[run] (volume) err: %v, exitcode: %d", err, exitCode)
  442. }
  443. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "test-volumesfromsymlinkpath", "busybox", "sh", "-c", "ls /foo | grep -q bar")
  444. exitCode, err = runCommand(cmd)
  445. if err != nil || exitCode != 0 {
  446. t.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
  447. }
  448. deleteImages("docker-test-volumesfromsymlinkpath")
  449. deleteAllContainers()
  450. logDone("run - volumes-from symlink path")
  451. }
  452. func TestRunExitCode(t *testing.T) {
  453. cmd := exec.Command(dockerBinary, "run", "busybox", "/bin/sh", "-c", "exit 72")
  454. exit, err := runCommand(cmd)
  455. if err == nil {
  456. t.Fatal("should not have a non nil error")
  457. }
  458. if exit != 72 {
  459. t.Fatalf("expected exit code 72 received %d", exit)
  460. }
  461. deleteAllContainers()
  462. logDone("run - correct exit code")
  463. }
  464. func TestRunUserDefaultsToRoot(t *testing.T) {
  465. cmd := exec.Command(dockerBinary, "run", "busybox", "id")
  466. out, _, err := runCommandWithOutput(cmd)
  467. if err != nil {
  468. t.Fatal(err, out)
  469. }
  470. if !strings.Contains(out, "uid=0(root) gid=0(root)") {
  471. t.Fatalf("expected root user got %s", out)
  472. }
  473. deleteAllContainers()
  474. logDone("run - default user")
  475. }
  476. func TestRunUserByName(t *testing.T) {
  477. cmd := exec.Command(dockerBinary, "run", "-u", "root", "busybox", "id")
  478. out, _, err := runCommandWithOutput(cmd)
  479. if err != nil {
  480. t.Fatal(err, out)
  481. }
  482. if !strings.Contains(out, "uid=0(root) gid=0(root)") {
  483. t.Fatalf("expected root user got %s", out)
  484. }
  485. deleteAllContainers()
  486. logDone("run - user by name")
  487. }
  488. func TestRunUserByID(t *testing.T) {
  489. cmd := exec.Command(dockerBinary, "run", "-u", "1", "busybox", "id")
  490. out, _, err := runCommandWithOutput(cmd)
  491. if err != nil {
  492. t.Fatal(err, out)
  493. }
  494. if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") {
  495. t.Fatalf("expected daemon user got %s", out)
  496. }
  497. deleteAllContainers()
  498. logDone("run - user by id")
  499. }
  500. func TestRunUserByIDBig(t *testing.T) {
  501. cmd := exec.Command(dockerBinary, "run", "-u", "2147483648", "busybox", "id")
  502. out, _, err := runCommandWithOutput(cmd)
  503. if err == nil {
  504. t.Fatal("No error, but must be.", out)
  505. }
  506. if !strings.Contains(out, "Uids and gids must be in range") {
  507. t.Fatalf("expected error about uids range, got %s", out)
  508. }
  509. deleteAllContainers()
  510. logDone("run - user by id, id too big")
  511. }
  512. func TestRunUserByIDNegative(t *testing.T) {
  513. cmd := exec.Command(dockerBinary, "run", "-u", "-1", "busybox", "id")
  514. out, _, err := runCommandWithOutput(cmd)
  515. if err == nil {
  516. t.Fatal("No error, but must be.", out)
  517. }
  518. if !strings.Contains(out, "Uids and gids must be in range") {
  519. t.Fatalf("expected error about uids range, got %s", out)
  520. }
  521. deleteAllContainers()
  522. logDone("run - user by id, id negative")
  523. }
  524. func TestRunUserByIDZero(t *testing.T) {
  525. cmd := exec.Command(dockerBinary, "run", "-u", "0", "busybox", "id")
  526. out, _, err := runCommandWithOutput(cmd)
  527. if err != nil {
  528. t.Fatal(err, out)
  529. }
  530. if !strings.Contains(out, "uid=0(root) gid=0(root) groups=10(wheel)") {
  531. t.Fatalf("expected daemon user got %s", out)
  532. }
  533. deleteAllContainers()
  534. logDone("run - user by id, zero uid")
  535. }
  536. func TestRunUserNotFound(t *testing.T) {
  537. cmd := exec.Command(dockerBinary, "run", "-u", "notme", "busybox", "id")
  538. _, err := runCommand(cmd)
  539. if err == nil {
  540. t.Fatal("unknown user should cause container to fail")
  541. }
  542. deleteAllContainers()
  543. logDone("run - user not found")
  544. }
  545. func TestRunTwoConcurrentContainers(t *testing.T) {
  546. group := sync.WaitGroup{}
  547. group.Add(2)
  548. for i := 0; i < 2; i++ {
  549. go func() {
  550. defer group.Done()
  551. cmd := exec.Command(dockerBinary, "run", "busybox", "sleep", "2")
  552. if _, err := runCommand(cmd); err != nil {
  553. t.Fatal(err)
  554. }
  555. }()
  556. }
  557. group.Wait()
  558. deleteAllContainers()
  559. logDone("run - two concurrent containers")
  560. }
  561. func TestRunEnvironment(t *testing.T) {
  562. cmd := exec.Command(dockerBinary, "run", "-h", "testing", "-e=FALSE=true", "-e=TRUE", "-e=TRICKY", "-e=HOME=", "busybox", "env")
  563. cmd.Env = append(os.Environ(),
  564. "TRUE=false",
  565. "TRICKY=tri\ncky\n",
  566. )
  567. out, _, err := runCommandWithOutput(cmd)
  568. if err != nil {
  569. t.Fatal(err, out)
  570. }
  571. actualEnv := strings.Split(out, "\n")
  572. if actualEnv[len(actualEnv)-1] == "" {
  573. actualEnv = actualEnv[:len(actualEnv)-1]
  574. }
  575. sort.Strings(actualEnv)
  576. goodEnv := []string{
  577. "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  578. "HOSTNAME=testing",
  579. "FALSE=true",
  580. "TRUE=false",
  581. "TRICKY=tri",
  582. "cky",
  583. "",
  584. "HOME=/root",
  585. }
  586. sort.Strings(goodEnv)
  587. if len(goodEnv) != len(actualEnv) {
  588. t.Fatalf("Wrong environment: should be %d variables, not: '%s'\n", len(goodEnv), strings.Join(actualEnv, ", "))
  589. }
  590. for i := range goodEnv {
  591. if actualEnv[i] != goodEnv[i] {
  592. t.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
  593. }
  594. }
  595. deleteAllContainers()
  596. logDone("run - verify environment")
  597. }
  598. func TestRunContainerNetwork(t *testing.T) {
  599. cmd := exec.Command(dockerBinary, "run", "busybox", "ping", "-c", "1", "127.0.0.1")
  600. if _, err := runCommand(cmd); err != nil {
  601. t.Fatal(err)
  602. }
  603. deleteAllContainers()
  604. logDone("run - test container network via ping")
  605. }
  606. // Issue #4681
  607. func TestRunLoopbackWhenNetworkDisabled(t *testing.T) {
  608. cmd := exec.Command(dockerBinary, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1")
  609. if _, err := runCommand(cmd); err != nil {
  610. t.Fatal(err)
  611. }
  612. deleteAllContainers()
  613. logDone("run - test container loopback when networking disabled")
  614. }
  615. func TestRunNetHostNotAllowedWithLinks(t *testing.T) {
  616. _, _, err := cmd(t, "run", "--name", "linked", "busybox", "true")
  617. cmd := exec.Command(dockerBinary, "run", "--net=host", "--link", "linked:linked", "busybox", "true")
  618. _, _, err = runCommandWithOutput(cmd)
  619. if err == nil {
  620. t.Fatal("Expected error")
  621. }
  622. deleteAllContainers()
  623. logDone("run - don't allow --net=host to be used with links")
  624. }
  625. func TestRunLoopbackOnlyExistsWhenNetworkingDisabled(t *testing.T) {
  626. cmd := exec.Command(dockerBinary, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up")
  627. out, _, err := runCommandWithOutput(cmd)
  628. if err != nil {
  629. t.Fatal(err, out)
  630. }
  631. var (
  632. count = 0
  633. parts = strings.Split(out, "\n")
  634. )
  635. for _, l := range parts {
  636. if l != "" {
  637. count++
  638. }
  639. }
  640. if count != 1 {
  641. t.Fatalf("Wrong interface count in container %d", count)
  642. }
  643. if !strings.HasPrefix(out, "1: lo") {
  644. t.Fatalf("Wrong interface in test container: expected [1: lo], got %s", out)
  645. }
  646. deleteAllContainers()
  647. logDone("run - test loopback only exists when networking disabled")
  648. }
  649. // #7851 hostname outside container shows FQDN, inside only shortname
  650. // For testing purposes it is not required to set host's hostname directly
  651. // and use "--net=host" (as the original issue submitter did), as the same
  652. // codepath is executed with "docker run -h <hostname>". Both were manually
  653. // tested, but this testcase takes the simpler path of using "run -h .."
  654. func TestRunFullHostnameSet(t *testing.T) {
  655. cmd := exec.Command(dockerBinary, "run", "-h", "foo.bar.baz", "busybox", "hostname")
  656. out, _, err := runCommandWithOutput(cmd)
  657. if err != nil {
  658. t.Fatal(err, out)
  659. }
  660. if actual := strings.Trim(out, "\r\n"); actual != "foo.bar.baz" {
  661. t.Fatalf("expected hostname 'foo.bar.baz', received %s", actual)
  662. }
  663. deleteAllContainers()
  664. logDone("run - test fully qualified hostname set with -h")
  665. }
  666. func TestRunPrivilegedCanMknod(t *testing.T) {
  667. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  668. out, _, err := runCommandWithOutput(cmd)
  669. if err != nil {
  670. t.Fatal(err)
  671. }
  672. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  673. t.Fatalf("expected output ok received %s", actual)
  674. }
  675. deleteAllContainers()
  676. logDone("run - test privileged can mknod")
  677. }
  678. func TestRunUnPrivilegedCanMknod(t *testing.T) {
  679. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  680. out, _, err := runCommandWithOutput(cmd)
  681. if err != nil {
  682. t.Fatal(err)
  683. }
  684. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  685. t.Fatalf("expected output ok received %s", actual)
  686. }
  687. deleteAllContainers()
  688. logDone("run - test un-privileged can mknod")
  689. }
  690. func TestRunCapDropInvalid(t *testing.T) {
  691. cmd := exec.Command(dockerBinary, "run", "--cap-drop=CHPASS", "busybox", "ls")
  692. out, _, err := runCommandWithOutput(cmd)
  693. if err == nil {
  694. t.Fatal(err, out)
  695. }
  696. logDone("run - test --cap-drop=CHPASS invalid")
  697. }
  698. func TestRunCapDropCannotMknod(t *testing.T) {
  699. cmd := exec.Command(dockerBinary, "run", "--cap-drop=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  700. out, _, err := runCommandWithOutput(cmd)
  701. if err == nil {
  702. t.Fatal(err, out)
  703. }
  704. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  705. t.Fatalf("expected output not ok received %s", actual)
  706. }
  707. deleteAllContainers()
  708. logDone("run - test --cap-drop=MKNOD cannot mknod")
  709. }
  710. func TestRunCapDropCannotMknodLowerCase(t *testing.T) {
  711. cmd := exec.Command(dockerBinary, "run", "--cap-drop=mknod", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  712. out, _, err := runCommandWithOutput(cmd)
  713. if err == nil {
  714. t.Fatal(err, out)
  715. }
  716. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  717. t.Fatalf("expected output not ok received %s", actual)
  718. }
  719. deleteAllContainers()
  720. logDone("run - test --cap-drop=mknod cannot mknod lowercase")
  721. }
  722. func TestRunCapDropALLCannotMknod(t *testing.T) {
  723. cmd := exec.Command(dockerBinary, "run", "--cap-drop=ALL", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  724. out, _, err := runCommandWithOutput(cmd)
  725. if err == nil {
  726. t.Fatal(err, out)
  727. }
  728. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  729. t.Fatalf("expected output not ok received %s", actual)
  730. }
  731. deleteAllContainers()
  732. logDone("run - test --cap-drop=ALL cannot mknod")
  733. }
  734. func TestRunCapDropALLAddMknodCannotMknod(t *testing.T) {
  735. cmd := exec.Command(dockerBinary, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  736. out, _, err := runCommandWithOutput(cmd)
  737. if err != nil {
  738. t.Fatal(err, out)
  739. }
  740. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  741. t.Fatalf("expected output ok received %s", actual)
  742. }
  743. deleteAllContainers()
  744. logDone("run - test --cap-drop=ALL --cap-add=MKNOD can mknod")
  745. }
  746. func TestRunCapAddInvalid(t *testing.T) {
  747. cmd := exec.Command(dockerBinary, "run", "--cap-add=CHPASS", "busybox", "ls")
  748. out, _, err := runCommandWithOutput(cmd)
  749. if err == nil {
  750. t.Fatal(err, out)
  751. }
  752. logDone("run - test --cap-add=CHPASS invalid")
  753. }
  754. func TestRunCapAddCanDownInterface(t *testing.T) {
  755. cmd := exec.Command(dockerBinary, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && 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-add=NET_ADMIN can set eth0 down")
  765. }
  766. func TestRunCapAddALLCanDownInterface(t *testing.T) {
  767. cmd := exec.Command(dockerBinary, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  768. out, _, err := runCommandWithOutput(cmd)
  769. if err != nil {
  770. t.Fatal(err, out)
  771. }
  772. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  773. t.Fatalf("expected output ok received %s", actual)
  774. }
  775. deleteAllContainers()
  776. logDone("run - test --cap-add=ALL can set eth0 down")
  777. }
  778. func TestRunCapAddALLDropNetAdminCanDownInterface(t *testing.T) {
  779. cmd := exec.Command(dockerBinary, "run", "--cap-add=ALL", "--cap-drop=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  780. out, _, err := runCommandWithOutput(cmd)
  781. if err == nil {
  782. t.Fatal(err, out)
  783. }
  784. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  785. t.Fatalf("expected output not ok received %s", actual)
  786. }
  787. deleteAllContainers()
  788. logDone("run - test --cap-add=ALL --cap-drop=NET_ADMIN cannot set eth0 down")
  789. }
  790. func TestRunPrivilegedCanMount(t *testing.T) {
  791. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
  792. out, _, err := runCommandWithOutput(cmd)
  793. if err != nil {
  794. t.Fatal(err)
  795. }
  796. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  797. t.Fatalf("expected output ok received %s", actual)
  798. }
  799. deleteAllContainers()
  800. logDone("run - test privileged can mount")
  801. }
  802. func TestRunUnPrivilegedCannotMount(t *testing.T) {
  803. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
  804. out, _, err := runCommandWithOutput(cmd)
  805. if err == nil {
  806. t.Fatal(err, out)
  807. }
  808. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  809. t.Fatalf("expected output not ok received %s", actual)
  810. }
  811. deleteAllContainers()
  812. logDone("run - test un-privileged cannot mount")
  813. }
  814. func TestRunSysNotWritableInNonPrivilegedContainers(t *testing.T) {
  815. cmd := exec.Command(dockerBinary, "run", "busybox", "touch", "/sys/kernel/profiling")
  816. if code, err := runCommand(cmd); err == nil || code == 0 {
  817. t.Fatal("sys should not be writable in a non privileged container")
  818. }
  819. deleteAllContainers()
  820. logDone("run - sys not writable in non privileged container")
  821. }
  822. func TestRunSysWritableInPrivilegedContainers(t *testing.T) {
  823. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "touch", "/sys/kernel/profiling")
  824. if code, err := runCommand(cmd); err != nil || code != 0 {
  825. t.Fatalf("sys should be writable in privileged container")
  826. }
  827. deleteAllContainers()
  828. logDone("run - sys writable in privileged container")
  829. }
  830. func TestRunProcNotWritableInNonPrivilegedContainers(t *testing.T) {
  831. cmd := exec.Command(dockerBinary, "run", "busybox", "touch", "/proc/sysrq-trigger")
  832. if code, err := runCommand(cmd); err == nil || code == 0 {
  833. t.Fatal("proc should not be writable in a non privileged container")
  834. }
  835. deleteAllContainers()
  836. logDone("run - proc not writable in non privileged container")
  837. }
  838. func TestRunProcWritableInPrivilegedContainers(t *testing.T) {
  839. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "touch", "/proc/sysrq-trigger")
  840. if code, err := runCommand(cmd); err != nil || code != 0 {
  841. t.Fatalf("proc should be writable in privileged container")
  842. }
  843. deleteAllContainers()
  844. logDone("run - proc writable in privileged container")
  845. }
  846. func TestRunWithCpuset(t *testing.T) {
  847. cmd := exec.Command(dockerBinary, "run", "--cpuset", "0", "busybox", "true")
  848. if code, err := runCommand(cmd); err != nil || code != 0 {
  849. t.Fatalf("container should run successfuly with cpuset of 0: %s", err)
  850. }
  851. deleteAllContainers()
  852. logDone("run - cpuset 0")
  853. }
  854. func TestRunDeviceNumbers(t *testing.T) {
  855. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "ls -l /dev/null")
  856. out, _, err := runCommandWithOutput(cmd)
  857. if err != nil {
  858. t.Fatal(err, out)
  859. }
  860. deviceLineFields := strings.Fields(out)
  861. deviceLineFields[6] = ""
  862. deviceLineFields[7] = ""
  863. deviceLineFields[8] = ""
  864. expected := []string{"crw-rw-rw-", "1", "root", "root", "1,", "3", "", "", "", "/dev/null"}
  865. if !(reflect.DeepEqual(deviceLineFields, expected)) {
  866. t.Fatalf("expected output\ncrw-rw-rw- 1 root root 1, 3 May 24 13:29 /dev/null\n received\n %s\n", out)
  867. }
  868. deleteAllContainers()
  869. logDone("run - test device numbers")
  870. }
  871. func TestRunThatCharacterDevicesActLikeCharacterDevices(t *testing.T) {
  872. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero")
  873. out, _, err := runCommandWithOutput(cmd)
  874. if err != nil {
  875. t.Fatal(err, out)
  876. }
  877. if actual := strings.Trim(out, "\r\n"); actual[0] == '0' {
  878. t.Fatalf("expected a new file called /zero to be create that is greater than 0 bytes long, but du says: %s", actual)
  879. }
  880. deleteAllContainers()
  881. logDone("run - test that character devices work.")
  882. }
  883. func TestRunUnprivilegedWithChroot(t *testing.T) {
  884. cmd := exec.Command(dockerBinary, "run", "busybox", "chroot", "/", "true")
  885. if _, err := runCommand(cmd); err != nil {
  886. t.Fatal(err)
  887. }
  888. deleteAllContainers()
  889. logDone("run - unprivileged with chroot")
  890. }
  891. func TestRunAddingOptionalDevices(t *testing.T) {
  892. cmd := exec.Command(dockerBinary, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo")
  893. out, _, err := runCommandWithOutput(cmd)
  894. if err != nil {
  895. t.Fatal(err, out)
  896. }
  897. if actual := strings.Trim(out, "\r\n"); actual != "/dev/nulo" {
  898. t.Fatalf("expected output /dev/nulo, received %s", actual)
  899. }
  900. deleteAllContainers()
  901. logDone("run - test --device argument")
  902. }
  903. func TestRunModeHostname(t *testing.T) {
  904. cmd := exec.Command(dockerBinary, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname")
  905. out, _, err := runCommandWithOutput(cmd)
  906. if err != nil {
  907. t.Fatal(err, out)
  908. }
  909. if actual := strings.Trim(out, "\r\n"); actual != "testhostname" {
  910. t.Fatalf("expected 'testhostname', but says: '%s'", actual)
  911. }
  912. cmd = exec.Command(dockerBinary, "run", "--net=host", "busybox", "cat", "/etc/hostname")
  913. out, _, err = runCommandWithOutput(cmd)
  914. if err != nil {
  915. t.Fatal(err, out)
  916. }
  917. hostname, err := os.Hostname()
  918. if err != nil {
  919. t.Fatal(err)
  920. }
  921. if actual := strings.Trim(out, "\r\n"); actual != hostname {
  922. t.Fatalf("expected '%s', but says: '%s'", hostname, actual)
  923. }
  924. deleteAllContainers()
  925. logDone("run - hostname and several network modes")
  926. }
  927. func TestRunRootWorkdir(t *testing.T) {
  928. s, _, err := cmd(t, "run", "--workdir", "/", "busybox", "pwd")
  929. if err != nil {
  930. t.Fatal(s, err)
  931. }
  932. if s != "/\n" {
  933. t.Fatalf("pwd returned '%s' (expected /\\n)", s)
  934. }
  935. deleteAllContainers()
  936. logDone("run - workdir /")
  937. }
  938. func TestRunAllowBindMountingRoot(t *testing.T) {
  939. s, _, err := cmd(t, "run", "-v", "/:/host", "busybox", "ls", "/host")
  940. if err != nil {
  941. t.Fatal(s, err)
  942. }
  943. deleteAllContainers()
  944. logDone("run - bind mount / as volume")
  945. }
  946. func TestRunDisallowBindMountingRootToRoot(t *testing.T) {
  947. cmd := exec.Command(dockerBinary, "run", "-v", "/:/", "busybox", "ls", "/host")
  948. out, _, err := runCommandWithOutput(cmd)
  949. if err == nil {
  950. t.Fatal(out, err)
  951. }
  952. deleteAllContainers()
  953. logDone("run - bind mount /:/ as volume should fail")
  954. }
  955. // Test recursive bind mount works by default
  956. func TestRunWithVolumesIsRecursive(t *testing.T) {
  957. tmpDir, err := ioutil.TempDir("", "docker_recursive_mount_test")
  958. if err != nil {
  959. t.Fatal(err)
  960. }
  961. defer os.RemoveAll(tmpDir)
  962. // Create a temporary tmpfs mount.
  963. tmpfsDir := filepath.Join(tmpDir, "tmpfs")
  964. if err := os.MkdirAll(tmpfsDir, 0777); err != nil {
  965. t.Fatalf("failed to mkdir at %s - %s", tmpfsDir, err)
  966. }
  967. if err := mount.Mount("tmpfs", tmpfsDir, "tmpfs", ""); err != nil {
  968. t.Fatalf("failed to create a tmpfs mount at %s - %s", tmpfsDir, err)
  969. }
  970. f, err := ioutil.TempFile(tmpfsDir, "touch-me")
  971. if err != nil {
  972. t.Fatal(err)
  973. }
  974. defer f.Close()
  975. runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox:latest", "ls", "/tmp/tmpfs")
  976. out, stderr, exitCode, err := runCommandWithStdoutStderr(runCmd)
  977. if err != nil && exitCode != 0 {
  978. t.Fatal(out, stderr, err)
  979. }
  980. if !strings.Contains(out, filepath.Base(f.Name())) {
  981. t.Fatal("Recursive bind mount test failed. Expected file not found")
  982. }
  983. deleteAllContainers()
  984. logDone("run - volumes are bind mounted recursively")
  985. }
  986. func TestRunDnsDefaultOptions(t *testing.T) {
  987. cmd := exec.Command(dockerBinary, "run", "busybox", "cat", "/etc/resolv.conf")
  988. actual, _, err := runCommandWithOutput(cmd)
  989. if err != nil {
  990. t.Fatal(err, actual)
  991. }
  992. resolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  993. if os.IsNotExist(err) {
  994. t.Fatalf("/etc/resolv.conf does not exist")
  995. }
  996. if actual != string(resolvConf) {
  997. t.Fatalf("expected resolv.conf is not the same of actual")
  998. }
  999. deleteAllContainers()
  1000. logDone("run - dns default options")
  1001. }
  1002. func TestRunDnsOptions(t *testing.T) {
  1003. cmd := exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
  1004. out, _, err := runCommandWithOutput(cmd)
  1005. if err != nil {
  1006. t.Fatal(err, out)
  1007. }
  1008. actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1)
  1009. if actual != "nameserver 127.0.0.1 search mydomain" {
  1010. t.Fatalf("expected 'nameserver 127.0.0.1 search mydomain', but says: '%s'", actual)
  1011. }
  1012. cmd = exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "--dns-search=.", "busybox", "cat", "/etc/resolv.conf")
  1013. out, _, err = runCommandWithOutput(cmd)
  1014. if err != nil {
  1015. t.Fatal(err, out)
  1016. }
  1017. actual = strings.Replace(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ", -1)
  1018. if actual != "nameserver 127.0.0.1" {
  1019. t.Fatalf("expected 'nameserver 127.0.0.1', but says: '%s'", actual)
  1020. }
  1021. logDone("run - dns options")
  1022. }
  1023. func TestRunDnsOptionsBasedOnHostResolvConf(t *testing.T) {
  1024. resolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  1025. if os.IsNotExist(err) {
  1026. t.Fatalf("/etc/resolv.conf does not exist")
  1027. }
  1028. hostNamservers := resolvconf.GetNameservers(resolvConf)
  1029. hostSearch := resolvconf.GetSearchDomains(resolvConf)
  1030. cmd := exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf")
  1031. out, _, err := runCommandWithOutput(cmd)
  1032. if err != nil {
  1033. t.Fatal(err, out)
  1034. }
  1035. if actualNameservers := resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "127.0.0.1" {
  1036. t.Fatalf("expected '127.0.0.1', but says: '%s'", string(actualNameservers[0]))
  1037. }
  1038. actualSearch := resolvconf.GetSearchDomains([]byte(out))
  1039. if len(actualSearch) != len(hostSearch) {
  1040. t.Fatalf("expected '%s' search domain(s), but it has: '%s'", len(hostSearch), len(actualSearch))
  1041. }
  1042. for i := range actualSearch {
  1043. if actualSearch[i] != hostSearch[i] {
  1044. t.Fatalf("expected '%s' domain, but says: '%s'", actualSearch[i], hostSearch[i])
  1045. }
  1046. }
  1047. cmd = exec.Command(dockerBinary, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
  1048. out, _, err = runCommandWithOutput(cmd)
  1049. if err != nil {
  1050. t.Fatal(err, out)
  1051. }
  1052. actualNameservers := resolvconf.GetNameservers([]byte(out))
  1053. if len(actualNameservers) != len(hostNamservers) {
  1054. t.Fatalf("expected '%s' nameserver(s), but it has: '%s'", len(hostNamservers), len(actualNameservers))
  1055. }
  1056. for i := range actualNameservers {
  1057. if actualNameservers[i] != hostNamservers[i] {
  1058. t.Fatalf("expected '%s' nameserver, but says: '%s'", actualNameservers[i], hostNamservers[i])
  1059. }
  1060. }
  1061. if actualSearch = resolvconf.GetSearchDomains([]byte(out)); string(actualSearch[0]) != "mydomain" {
  1062. t.Fatalf("expected 'mydomain', but says: '%s'", string(actualSearch[0]))
  1063. }
  1064. deleteAllContainers()
  1065. logDone("run - dns options based on host resolv.conf")
  1066. }
  1067. func TestRunAddHost(t *testing.T) {
  1068. defer deleteAllContainers()
  1069. cmd := exec.Command(dockerBinary, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts")
  1070. out, _, err := runCommandWithOutput(cmd)
  1071. if err != nil {
  1072. t.Fatal(err, out)
  1073. }
  1074. actual := strings.Trim(out, "\r\n")
  1075. if actual != "86.75.30.9\textra" {
  1076. t.Fatalf("expected '86.75.30.9\textra', but says: '%s'", actual)
  1077. }
  1078. logDone("run - add-host option")
  1079. }
  1080. // Regression test for #6983
  1081. func TestRunAttachStdErrOnlyTTYMode(t *testing.T) {
  1082. cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stderr", "busybox", "true")
  1083. exitCode, err := runCommand(cmd)
  1084. if err != nil {
  1085. t.Fatal(err)
  1086. } else if exitCode != 0 {
  1087. t.Fatalf("Container should have exited with error code 0")
  1088. }
  1089. deleteAllContainers()
  1090. logDone("run - Attach stderr only with -t")
  1091. }
  1092. // Regression test for #6983
  1093. func TestRunAttachStdOutOnlyTTYMode(t *testing.T) {
  1094. cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stdout", "busybox", "true")
  1095. exitCode, err := runCommand(cmd)
  1096. if err != nil {
  1097. t.Fatal(err)
  1098. } else if exitCode != 0 {
  1099. t.Fatalf("Container should have exited with error code 0")
  1100. }
  1101. deleteAllContainers()
  1102. logDone("run - Attach stdout only with -t")
  1103. }
  1104. // Regression test for #6983
  1105. func TestRunAttachStdOutAndErrTTYMode(t *testing.T) {
  1106. cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true")
  1107. exitCode, err := runCommand(cmd)
  1108. if err != nil {
  1109. t.Fatal(err)
  1110. } else if exitCode != 0 {
  1111. t.Fatalf("Container should have exited with error code 0")
  1112. }
  1113. deleteAllContainers()
  1114. logDone("run - Attach stderr and stdout with -t")
  1115. }
  1116. func TestRunState(t *testing.T) {
  1117. defer deleteAllContainers()
  1118. cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  1119. out, _, err := runCommandWithOutput(cmd)
  1120. if err != nil {
  1121. t.Fatal(err, out)
  1122. }
  1123. id := strings.TrimSpace(out)
  1124. state, err := inspectField(id, "State.Running")
  1125. if err != nil {
  1126. t.Fatal(err)
  1127. }
  1128. if state != "true" {
  1129. t.Fatal("Container state is 'not running'")
  1130. }
  1131. pid1, err := inspectField(id, "State.Pid")
  1132. if err != nil {
  1133. t.Fatal(err)
  1134. }
  1135. if pid1 == "0" {
  1136. t.Fatal("Container state Pid 0")
  1137. }
  1138. cmd = exec.Command(dockerBinary, "stop", id)
  1139. out, _, err = runCommandWithOutput(cmd)
  1140. if err != nil {
  1141. t.Fatal(err, out)
  1142. }
  1143. state, err = inspectField(id, "State.Running")
  1144. if err != nil {
  1145. t.Fatal(err)
  1146. }
  1147. if state != "false" {
  1148. t.Fatal("Container state is 'running'")
  1149. }
  1150. pid2, err := inspectField(id, "State.Pid")
  1151. if err != nil {
  1152. t.Fatal(err)
  1153. }
  1154. if pid2 == pid1 {
  1155. t.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1156. }
  1157. cmd = exec.Command(dockerBinary, "start", id)
  1158. out, _, err = runCommandWithOutput(cmd)
  1159. if err != nil {
  1160. t.Fatal(err, out)
  1161. }
  1162. state, err = inspectField(id, "State.Running")
  1163. if err != nil {
  1164. t.Fatal(err)
  1165. }
  1166. if state != "true" {
  1167. t.Fatal("Container state is 'not running'")
  1168. }
  1169. pid3, err := inspectField(id, "State.Pid")
  1170. if err != nil {
  1171. t.Fatal(err)
  1172. }
  1173. if pid3 == pid1 {
  1174. t.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1175. }
  1176. logDone("run - test container state.")
  1177. }
  1178. // Test for #1737
  1179. func TestRunCopyVolumeUidGid(t *testing.T) {
  1180. name := "testrunvolumesuidgid"
  1181. defer deleteImages(name)
  1182. defer deleteAllContainers()
  1183. _, err := buildImage(name,
  1184. `FROM busybox
  1185. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1186. RUN echo 'dockerio:x:1001:' >> /etc/group
  1187. RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`,
  1188. true)
  1189. if err != nil {
  1190. t.Fatal(err)
  1191. }
  1192. // Test that the uid and gid is copied from the image to the volume
  1193. cmd := exec.Command(dockerBinary, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'")
  1194. out, _, err := runCommandWithOutput(cmd)
  1195. if err != nil {
  1196. t.Fatal(err, out)
  1197. }
  1198. out = strings.TrimSpace(out)
  1199. if out != "dockerio:dockerio" {
  1200. t.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out)
  1201. }
  1202. logDone("run - copy uid/gid for volume")
  1203. }
  1204. // Test for #1582
  1205. func TestRunCopyVolumeContent(t *testing.T) {
  1206. name := "testruncopyvolumecontent"
  1207. defer deleteImages(name)
  1208. defer deleteAllContainers()
  1209. _, err := buildImage(name,
  1210. `FROM busybox
  1211. RUN mkdir -p /hello/local && echo hello > /hello/local/world`,
  1212. true)
  1213. if err != nil {
  1214. t.Fatal(err)
  1215. }
  1216. // Test that the content is copied from the image to the volume
  1217. cmd := exec.Command(dockerBinary, "run", "--rm", "-v", "/hello", name, "sh", "-c", "find", "/hello")
  1218. out, _, err := runCommandWithOutput(cmd)
  1219. if err != nil {
  1220. t.Fatal(err, out)
  1221. }
  1222. if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) {
  1223. t.Fatal("Container failed to transfer content to volume")
  1224. }
  1225. logDone("run - copy volume content")
  1226. }
  1227. func TestRunCleanupCmdOnEntrypoint(t *testing.T) {
  1228. name := "testrunmdcleanuponentrypoint"
  1229. defer deleteImages(name)
  1230. defer deleteAllContainers()
  1231. if _, err := buildImage(name,
  1232. `FROM busybox
  1233. ENTRYPOINT ["echo"]
  1234. CMD ["testingpoint"]`,
  1235. true); err != nil {
  1236. t.Fatal(err)
  1237. }
  1238. runCmd := exec.Command(dockerBinary, "run", "--entrypoint", "whoami", name)
  1239. out, exit, err := runCommandWithOutput(runCmd)
  1240. if err != nil {
  1241. t.Fatalf("Error: %v, out: %q", err, out)
  1242. }
  1243. if exit != 0 {
  1244. t.Fatalf("expected exit code 0 received %d, out: %q", exit, out)
  1245. }
  1246. out = strings.TrimSpace(out)
  1247. if out != "root" {
  1248. t.Fatalf("Expected output root, got %q", out)
  1249. }
  1250. logDone("run - cleanup cmd on --entrypoint")
  1251. }
  1252. // TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected
  1253. func TestRunWorkdirExistsAndIsFile(t *testing.T) {
  1254. defer deleteAllContainers()
  1255. runCmd := exec.Command(dockerBinary, "run", "-w", "/bin/cat", "busybox")
  1256. out, exit, err := runCommandWithOutput(runCmd)
  1257. if !(err != nil && exit == 1 && strings.Contains(out, "Cannot mkdir: /bin/cat is not a directory")) {
  1258. t.Fatalf("Docker must complains about making dir, but we got out: %s, exit: %d, err: %s", out, exit, err)
  1259. }
  1260. logDone("run - error on existing file for workdir")
  1261. }
  1262. func TestRunExitOnStdinClose(t *testing.T) {
  1263. name := "testrunexitonstdinclose"
  1264. defer deleteAllContainers()
  1265. runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", "/bin/cat")
  1266. stdin, err := runCmd.StdinPipe()
  1267. if err != nil {
  1268. t.Fatal(err)
  1269. }
  1270. stdout, err := runCmd.StdoutPipe()
  1271. if err != nil {
  1272. t.Fatal(err)
  1273. }
  1274. if err := runCmd.Start(); err != nil {
  1275. t.Fatal(err)
  1276. }
  1277. if _, err := stdin.Write([]byte("hello\n")); err != nil {
  1278. t.Fatal(err)
  1279. }
  1280. r := bufio.NewReader(stdout)
  1281. line, err := r.ReadString('\n')
  1282. if err != nil {
  1283. t.Fatal(err)
  1284. }
  1285. line = strings.TrimSpace(line)
  1286. if line != "hello" {
  1287. t.Fatalf("Output should be 'hello', got '%q'", line)
  1288. }
  1289. if err := stdin.Close(); err != nil {
  1290. t.Fatal(err)
  1291. }
  1292. finish := make(chan struct{})
  1293. go func() {
  1294. if err := runCmd.Wait(); err != nil {
  1295. t.Fatal(err)
  1296. }
  1297. close(finish)
  1298. }()
  1299. select {
  1300. case <-finish:
  1301. case <-time.After(1 * time.Second):
  1302. t.Fatal("docker run failed to exit on stdin close")
  1303. }
  1304. state, err := inspectField(name, "State.Running")
  1305. if err != nil {
  1306. t.Fatal(err)
  1307. }
  1308. if state != "false" {
  1309. t.Fatal("Container must be stopped after stdin closing")
  1310. }
  1311. logDone("run - exit on stdin closing")
  1312. }
  1313. // Test for #2267
  1314. func TestRunWriteHostsFileAndNotCommit(t *testing.T) {
  1315. name := "writehosts"
  1316. cmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hosts && cat /etc/hosts")
  1317. out, _, err := runCommandWithOutput(cmd)
  1318. if err != nil {
  1319. t.Fatal(err, out)
  1320. }
  1321. if !strings.Contains(out, "test2267") {
  1322. t.Fatal("/etc/hosts should contain 'test2267'")
  1323. }
  1324. cmd = exec.Command(dockerBinary, "diff", name)
  1325. if err != nil {
  1326. t.Fatal(err, out)
  1327. }
  1328. out, _, err = runCommandWithOutput(cmd)
  1329. if err != nil {
  1330. t.Fatal(err, out)
  1331. }
  1332. if len(strings.Trim(out, "\r\n")) != 0 {
  1333. t.Fatal("diff should be empty")
  1334. }
  1335. logDone("run - write to /etc/hosts and not commited")
  1336. }
  1337. // Test for #2267
  1338. func TestRunWriteHostnameFileAndNotCommit(t *testing.T) {
  1339. name := "writehostname"
  1340. cmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hostname && cat /etc/hostname")
  1341. out, _, err := runCommandWithOutput(cmd)
  1342. if err != nil {
  1343. t.Fatal(err, out)
  1344. }
  1345. if !strings.Contains(out, "test2267") {
  1346. t.Fatal("/etc/hostname should contain 'test2267'")
  1347. }
  1348. cmd = exec.Command(dockerBinary, "diff", name)
  1349. if err != nil {
  1350. t.Fatal(err, out)
  1351. }
  1352. out, _, err = runCommandWithOutput(cmd)
  1353. if err != nil {
  1354. t.Fatal(err, out)
  1355. }
  1356. if len(strings.Trim(out, "\r\n")) != 0 {
  1357. t.Fatal("diff should be empty")
  1358. }
  1359. logDone("run - write to /etc/hostname and not commited")
  1360. }
  1361. // Test for #2267
  1362. func TestRunWriteResolvFileAndNotCommit(t *testing.T) {
  1363. name := "writeresolv"
  1364. cmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/resolv.conf && cat /etc/resolv.conf")
  1365. out, _, err := runCommandWithOutput(cmd)
  1366. if err != nil {
  1367. t.Fatal(err, out)
  1368. }
  1369. if !strings.Contains(out, "test2267") {
  1370. t.Fatal("/etc/resolv.conf should contain 'test2267'")
  1371. }
  1372. cmd = exec.Command(dockerBinary, "diff", name)
  1373. if err != nil {
  1374. t.Fatal(err, out)
  1375. }
  1376. out, _, err = runCommandWithOutput(cmd)
  1377. if err != nil {
  1378. t.Fatal(err, out)
  1379. }
  1380. if len(strings.Trim(out, "\r\n")) != 0 {
  1381. t.Fatal("diff should be empty")
  1382. }
  1383. logDone("run - write to /etc/resolv.conf and not commited")
  1384. }
  1385. func TestRunWithBadDevice(t *testing.T) {
  1386. name := "baddevice"
  1387. cmd := exec.Command(dockerBinary, "run", "--name", name, "--device", "/etc", "busybox", "true")
  1388. out, _, err := runCommandWithOutput(cmd)
  1389. if err == nil {
  1390. t.Fatal("Run should fail with bad device")
  1391. }
  1392. expected := `"/etc": not a device node`
  1393. if !strings.Contains(out, expected) {
  1394. t.Fatalf("Output should contain %q, actual out: %q", expected, out)
  1395. }
  1396. logDone("run - error with bad device")
  1397. }
  1398. func TestRunEntrypoint(t *testing.T) {
  1399. name := "entrypoint"
  1400. cmd := exec.Command(dockerBinary, "run", "--name", name, "--entrypoint", "/bin/echo", "busybox", "-n", "foobar")
  1401. out, _, err := runCommandWithOutput(cmd)
  1402. if err != nil {
  1403. t.Fatal(err, out)
  1404. }
  1405. expected := "foobar"
  1406. if out != expected {
  1407. t.Fatalf("Output should be %q, actual out: %q", expected, out)
  1408. }
  1409. logDone("run - entrypoint")
  1410. }
  1411. func TestRunBindMounts(t *testing.T) {
  1412. tmpDir, err := ioutil.TempDir("", "docker-test-container")
  1413. if err != nil {
  1414. t.Fatal(err)
  1415. }
  1416. defer os.RemoveAll(tmpDir)
  1417. writeFile(path.Join(tmpDir, "touch-me"), "", t)
  1418. // Test reading from a read-only bind mount
  1419. cmd := exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox", "ls", "/tmp")
  1420. out, _, err := runCommandWithOutput(cmd)
  1421. if err != nil {
  1422. t.Fatal(err, out)
  1423. }
  1424. if !strings.Contains(out, "touch-me") {
  1425. t.Fatal("Container failed to read from bind mount")
  1426. }
  1427. // test writing to bind mount
  1428. cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla")
  1429. out, _, err = runCommandWithOutput(cmd)
  1430. if err != nil {
  1431. t.Fatal(err, out)
  1432. }
  1433. readFile(path.Join(tmpDir, "holla"), t) // Will fail if the file doesn't exist
  1434. // test mounting to an illegal destination directory
  1435. cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:.", tmpDir), "busybox", "ls", ".")
  1436. _, err = runCommand(cmd)
  1437. if err == nil {
  1438. t.Fatal("Container bind mounted illegal directory")
  1439. }
  1440. // test mount a file
  1441. cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla")
  1442. _, err = runCommand(cmd)
  1443. if err != nil {
  1444. t.Fatal(err, out)
  1445. }
  1446. content := readFile(path.Join(tmpDir, "holla"), t) // Will fail if the file doesn't exist
  1447. expected := "yotta"
  1448. if content != expected {
  1449. t.Fatalf("Output should be %q, actual out: %q", expected, content)
  1450. }
  1451. logDone("run - bind mounts")
  1452. }
  1453. func TestRunMutableNetworkFiles(t *testing.T) {
  1454. defer deleteAllContainers()
  1455. for _, fn := range []string{"resolv.conf", "hosts"} {
  1456. deleteAllContainers()
  1457. 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)))
  1458. if err != nil {
  1459. t.Fatal(err, out)
  1460. }
  1461. time.Sleep(1 * time.Second)
  1462. contID := strings.TrimSpace(out)
  1463. f, err := os.Open(filepath.Join("/var/lib/docker/containers", contID, fn))
  1464. if err != nil {
  1465. t.Fatal(err)
  1466. }
  1467. content, err := ioutil.ReadAll(f)
  1468. f.Close()
  1469. if strings.TrimSpace(string(content)) != "success" {
  1470. t.Fatal("Content was not what was modified in the container", string(content))
  1471. }
  1472. 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)))
  1473. if err != nil {
  1474. t.Fatal(err)
  1475. }
  1476. contID = strings.TrimSpace(out)
  1477. resolvConfPath := filepath.Join("/var/lib/docker/containers", contID, fn)
  1478. f, err = os.OpenFile(resolvConfPath, os.O_WRONLY|os.O_SYNC|os.O_APPEND, 0644)
  1479. if err != nil {
  1480. t.Fatal(err)
  1481. }
  1482. if _, err := f.Seek(0, 0); err != nil {
  1483. f.Close()
  1484. t.Fatal(err)
  1485. }
  1486. if err := f.Truncate(0); err != nil {
  1487. f.Close()
  1488. t.Fatal(err)
  1489. }
  1490. if _, err := f.Write([]byte("success2\n")); err != nil {
  1491. f.Close()
  1492. t.Fatal(err)
  1493. }
  1494. f.Close()
  1495. time.Sleep(2 * time.Second) // don't race sleep
  1496. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "logs", "c2"))
  1497. if err != nil {
  1498. t.Fatal(err)
  1499. }
  1500. lines := strings.Split(out, "\n")
  1501. if strings.TrimSpace(lines[len(lines)-2]) != "success2" {
  1502. t.Fatalf("Did not find the correct output in /etc/%s: %s %#v", fn, out, lines)
  1503. }
  1504. }
  1505. }
  1506. func TestRunHostsLinkedContainerUpdate(t *testing.T) {
  1507. deleteAllContainers()
  1508. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", "c1", "busybox", "sh", "-c", "while true; do sleep 1; done"))
  1509. if err != nil {
  1510. t.Fatal(err, out)
  1511. }
  1512. // TODO fix docker cp and /etc/hosts
  1513. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--link", "c1:c1", "--name", "c2", "busybox", "sh", "-c", "while true;do sleep 1; done"))
  1514. if err != nil {
  1515. t.Fatal(err, out)
  1516. }
  1517. contID := strings.TrimSpace(out)
  1518. f, err := os.Open(filepath.Join("/var/lib/docker/containers", contID, "hosts"))
  1519. if err != nil {
  1520. t.Fatal(err)
  1521. }
  1522. originalContent, err := ioutil.ReadAll(f)
  1523. f.Close()
  1524. if err != nil {
  1525. t.Fatal(err)
  1526. }
  1527. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "restart", "-t", "0", "c1"))
  1528. if err != nil {
  1529. t.Fatal(err, out)
  1530. }
  1531. f, err = os.Open(filepath.Join("/var/lib/docker/containers", contID, "hosts"))
  1532. if err != nil {
  1533. t.Fatal(err)
  1534. }
  1535. newContent, err := ioutil.ReadAll(f)
  1536. f.Close()
  1537. if err != nil {
  1538. t.Fatal(err)
  1539. }
  1540. if strings.TrimSpace(string(originalContent)) == strings.TrimSpace(string(newContent)) {
  1541. t.Fatalf("expected /etc/hosts to be updated, but wasn't")
  1542. }
  1543. deleteAllContainers()
  1544. logDone("run - /etc/hosts updated in parent when restart")
  1545. }
  1546. // Ensure that CIDFile gets deleted if it's empty
  1547. // Perform this test by making `docker run` fail
  1548. func TestRunCidFileCleanupIfEmpty(t *testing.T) {
  1549. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1550. if err != nil {
  1551. t.Fatal(err)
  1552. }
  1553. defer os.RemoveAll(tmpDir)
  1554. tmpCidFile := path.Join(tmpDir, "cid")
  1555. cmd := exec.Command(dockerBinary, "run", "--cidfile", tmpCidFile, "scratch")
  1556. out, _, err := runCommandWithOutput(cmd)
  1557. t.Log(out)
  1558. if err == nil {
  1559. t.Fatal("Run without command must fail")
  1560. }
  1561. if _, err := os.Stat(tmpCidFile); err == nil {
  1562. t.Fatalf("empty CIDFile '%s' should've been deleted", tmpCidFile)
  1563. }
  1564. deleteAllContainers()
  1565. logDone("run - cleanup empty cidfile on fail")
  1566. }
  1567. // #2098 - Docker cidFiles only contain short version of the containerId
  1568. //sudo docker run --cidfile /tmp/docker_test.cid ubuntu echo "test"
  1569. // TestRunCidFile tests that run --cidfile returns the longid
  1570. func TestRunCidFileCheckIDLength(t *testing.T) {
  1571. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1572. if err != nil {
  1573. t.Fatal(err)
  1574. }
  1575. tmpCidFile := path.Join(tmpDir, "cid")
  1576. defer os.RemoveAll(tmpDir)
  1577. cmd := exec.Command(dockerBinary, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true")
  1578. out, _, err := runCommandWithOutput(cmd)
  1579. if err != nil {
  1580. t.Fatal(err)
  1581. }
  1582. id := strings.TrimSpace(out)
  1583. buffer, err := ioutil.ReadFile(tmpCidFile)
  1584. if err != nil {
  1585. t.Fatal(err)
  1586. }
  1587. cid := string(buffer)
  1588. if len(cid) != 64 {
  1589. t.Fatalf("--cidfile should be a long id, not '%s'", id)
  1590. }
  1591. if cid != id {
  1592. t.Fatalf("cid must be equal to %s, got %s", id, cid)
  1593. }
  1594. deleteAllContainers()
  1595. logDone("run - cidfile contains long id")
  1596. }
  1597. func TestRunNetworkNotInitializedNoneMode(t *testing.T) {
  1598. cmd := exec.Command(dockerBinary, "run", "-d", "--net=none", "busybox", "top")
  1599. out, _, err := runCommandWithOutput(cmd)
  1600. if err != nil {
  1601. t.Fatal(err)
  1602. }
  1603. id := strings.TrimSpace(out)
  1604. res, err := inspectField(id, "NetworkSettings.IPAddress")
  1605. if err != nil {
  1606. t.Fatal(err)
  1607. }
  1608. if res != "" {
  1609. t.Fatal("For 'none' mode network must not be initialized, but container got IP: %s", res)
  1610. }
  1611. deleteAllContainers()
  1612. logDone("run - network must not be initialized in 'none' mode")
  1613. }
  1614. func TestRunDeallocatePortOnMissingIptablesRule(t *testing.T) {
  1615. cmd := exec.Command(dockerBinary, "run", "-d", "-p", "23:23", "busybox", "top")
  1616. out, _, err := runCommandWithOutput(cmd)
  1617. if err != nil {
  1618. t.Fatal(err)
  1619. }
  1620. id := strings.TrimSpace(out)
  1621. ip, err := inspectField(id, "NetworkSettings.IPAddress")
  1622. if err != nil {
  1623. t.Fatal(err)
  1624. }
  1625. iptCmd := exec.Command("iptables", "-D", "FORWARD", "-d", fmt.Sprintf("%s/32", ip),
  1626. "!", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-m", "tcp", "--dport", "23", "-j", "ACCEPT")
  1627. out, _, err = runCommandWithOutput(iptCmd)
  1628. if err != nil {
  1629. t.Fatal(err, out)
  1630. }
  1631. if err := deleteContainer(id); err != nil {
  1632. t.Fatal(err)
  1633. }
  1634. cmd = exec.Command(dockerBinary, "run", "-d", "-p", "23:23", "busybox", "top")
  1635. out, _, err = runCommandWithOutput(cmd)
  1636. if err != nil {
  1637. t.Fatal(err, out)
  1638. }
  1639. deleteAllContainers()
  1640. logDone("run - port should be deallocated even on iptables error")
  1641. }
  1642. func TestRunPortInUse(t *testing.T) {
  1643. port := "1234"
  1644. l, err := net.Listen("tcp", ":"+port)
  1645. if err != nil {
  1646. t.Fatal(err)
  1647. }
  1648. defer l.Close()
  1649. cmd := exec.Command(dockerBinary, "run", "-p", port+":80", "busybox", "true")
  1650. out, _, err := runCommandWithOutput(cmd)
  1651. if err == nil {
  1652. t.Fatalf("Binding on used port must fail")
  1653. }
  1654. if !strings.Contains(out, "address already in use") {
  1655. t.Fatalf("Out must be about \"address already in use\", got %s", out)
  1656. }
  1657. deleteAllContainers()
  1658. logDone("run - fail if port already in use")
  1659. }
  1660. // Regression test for #7792
  1661. func TestRunMountOrdering(t *testing.T) {
  1662. tmpDir, err := ioutil.TempDir("", "docker_nested_mount_test")
  1663. if err != nil {
  1664. t.Fatal(err)
  1665. }
  1666. defer os.RemoveAll(tmpDir)
  1667. tmpDir2, err := ioutil.TempDir("", "docker_nested_mount_test2")
  1668. if err != nil {
  1669. t.Fatal(err)
  1670. }
  1671. defer os.RemoveAll(tmpDir2)
  1672. // Create a temporary tmpfs mount.
  1673. fooDir := filepath.Join(tmpDir, "foo")
  1674. if err := os.MkdirAll(filepath.Join(tmpDir, "foo"), 0755); err != nil {
  1675. t.Fatalf("failed to mkdir at %s - %s", fooDir, err)
  1676. }
  1677. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", fooDir), []byte{}, 0644); err != nil {
  1678. t.Fatal(err)
  1679. }
  1680. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir), []byte{}, 0644); err != nil {
  1681. t.Fatal(err)
  1682. }
  1683. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir2), []byte{}, 0644); err != nil {
  1684. t.Fatal(err)
  1685. }
  1686. 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")
  1687. out, _, err := runCommandWithOutput(cmd)
  1688. if err != nil {
  1689. t.Fatal(out, err)
  1690. }
  1691. deleteAllContainers()
  1692. logDone("run - volumes are mounted in the correct order")
  1693. }