docker_cli_run_test.go 77 KB

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