docker_cli_run_test.go 97 KB

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