docker_cli_run_test.go 103 KB

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