docker_cli_run_test.go 89 KB

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