docker_cli_run_test.go 101 KB

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