docker_cli_run_test.go 98 KB

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