docker_cli_run_test.go 64 KB

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