docker_cli_run_test.go 78 KB

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