docker_cli_run_test.go 89 KB

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