docker_cli_run_test.go 96 KB

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