docker_cli_run_test.go 104 KB

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