docker_cli_run_test.go 89 KB

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