docker_cli_run_test.go 90 KB

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