docker_cli_run_test.go 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "os/exec"
  9. "path"
  10. "path/filepath"
  11. "reflect"
  12. "regexp"
  13. "sort"
  14. "strings"
  15. "sync"
  16. "testing"
  17. "time"
  18. "github.com/docker/docker/pkg/mount"
  19. "github.com/docker/docker/pkg/networkfs/resolvconf"
  20. )
  21. // "test123" should be printed by docker run
  22. func TestRunEchoStdout(t *testing.T) {
  23. runCmd := exec.Command(dockerBinary, "run", "busybox", "echo", "test123")
  24. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  25. if err != nil {
  26. t.Fatalf("failed to run container: %v, output: %q", err, out)
  27. }
  28. if out != "test123\n" {
  29. t.Errorf("container should've printed 'test123'")
  30. }
  31. deleteAllContainers()
  32. logDone("run - echo test123")
  33. }
  34. // "test" should be printed
  35. func TestRunEchoStdoutWithMemoryLimit(t *testing.T) {
  36. runCmd := exec.Command(dockerBinary, "run", "-m", "2786432", "busybox", "echo", "test")
  37. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  38. if err != nil {
  39. t.Fatalf("failed to run container: %v, output: %q", err, out)
  40. }
  41. out = strings.Trim(out, "\r\n")
  42. if expected := "test"; out != expected {
  43. t.Errorf("container should've printed %q but printed %q", expected, out)
  44. }
  45. deleteAllContainers()
  46. logDone("run - echo with memory limit")
  47. }
  48. // "test" should be printed
  49. func TestRunEchoStdoutWitCPULimit(t *testing.T) {
  50. runCmd := exec.Command(dockerBinary, "run", "-c", "1000", "busybox", "echo", "test")
  51. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  52. if err != nil {
  53. t.Fatalf("failed to run container: %v, output: %q", err, out)
  54. }
  55. if out != "test\n" {
  56. t.Errorf("container should've printed 'test'")
  57. }
  58. deleteAllContainers()
  59. logDone("run - echo with CPU limit")
  60. }
  61. // "test" should be printed
  62. func TestRunEchoStdoutWithCPUAndMemoryLimit(t *testing.T) {
  63. runCmd := exec.Command(dockerBinary, "run", "-c", "1000", "-m", "2786432", "busybox", "echo", "test")
  64. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  65. if err != nil {
  66. t.Fatalf("failed to run container: %v, output: %q", err, out)
  67. }
  68. if out != "test\n" {
  69. t.Errorf("container should've printed 'test', got %q instead", out)
  70. }
  71. deleteAllContainers()
  72. logDone("run - echo with CPU and memory limit")
  73. }
  74. // "test" should be printed
  75. func TestRunEchoNamedContainer(t *testing.T) {
  76. runCmd := exec.Command(dockerBinary, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test")
  77. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  78. if err != nil {
  79. t.Fatalf("failed to run container: %v, output: %q", err, out)
  80. }
  81. if out != "test\n" {
  82. t.Errorf("container should've printed 'test'")
  83. }
  84. if err := deleteContainer("testfoonamedcontainer"); err != nil {
  85. t.Errorf("failed to remove the named container: %v", err)
  86. }
  87. deleteAllContainers()
  88. logDone("run - echo with named container")
  89. }
  90. // docker run should not leak file descriptors
  91. func TestRunLeakyFileDescriptors(t *testing.T) {
  92. runCmd := exec.Command(dockerBinary, "run", "busybox", "ls", "-C", "/proc/self/fd")
  93. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  94. if err != nil {
  95. t.Fatalf("failed to run container: %v, output: %q", err, out)
  96. }
  97. // normally, we should only get 0, 1, and 2, but 3 gets created by "ls" when it does "opendir" on the "fd" directory
  98. if out != "0 1 2 3\n" {
  99. t.Errorf("container should've printed '0 1 2 3', not: %s", out)
  100. }
  101. deleteAllContainers()
  102. logDone("run - check file descriptor leakage")
  103. }
  104. // it should be possible to ping Google DNS resolver
  105. // this will fail when Internet access is unavailable
  106. func TestRunPingGoogle(t *testing.T) {
  107. runCmd := exec.Command(dockerBinary, "run", "busybox", "ping", "-c", "1", "8.8.8.8")
  108. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  109. if err != nil {
  110. t.Fatalf("failed to run container: %v, output: %q", err, out)
  111. }
  112. errorOut(err, t, "container should've been able to ping 8.8.8.8")
  113. deleteAllContainers()
  114. logDone("run - ping 8.8.8.8")
  115. }
  116. // the exit code should be 0
  117. // some versions of lxc might make this test fail
  118. func TestRunExitCodeZero(t *testing.T) {
  119. runCmd := exec.Command(dockerBinary, "run", "busybox", "true")
  120. exitCode, err := runCommand(runCmd)
  121. errorOut(err, t, fmt.Sprintf("%s", err))
  122. if exitCode != 0 {
  123. t.Errorf("container should've exited with exit code 0")
  124. }
  125. deleteAllContainers()
  126. logDone("run - exit with 0")
  127. }
  128. // the exit code should be 1
  129. // some versions of lxc might make this test fail
  130. func TestRunExitCodeOne(t *testing.T) {
  131. runCmd := exec.Command(dockerBinary, "run", "busybox", "false")
  132. exitCode, err := runCommand(runCmd)
  133. if err != nil && !strings.Contains("exit status 1", fmt.Sprintf("%s", err)) {
  134. t.Fatal(err)
  135. }
  136. if exitCode != 1 {
  137. t.Errorf("container should've exited with exit code 1")
  138. }
  139. deleteAllContainers()
  140. logDone("run - exit with 1")
  141. }
  142. // it should be possible to pipe in data via stdin to a process running in a container
  143. // some versions of lxc might make this test fail
  144. func TestRunStdinPipe(t *testing.T) {
  145. runCmd := exec.Command("bash", "-c", `echo "blahblah" | docker run -i -a stdin busybox cat`)
  146. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  147. if err != nil {
  148. t.Fatalf("failed to run container: %v, output: %q", err, out)
  149. }
  150. out = stripTrailingCharacters(out)
  151. inspectCmd := exec.Command(dockerBinary, "inspect", out)
  152. inspectOut, _, err := runCommandWithOutput(inspectCmd)
  153. errorOut(err, t, fmt.Sprintf("out should've been a container id: %s %s", out, inspectOut))
  154. waitCmd := exec.Command(dockerBinary, "wait", out)
  155. _, _, err = runCommandWithOutput(waitCmd)
  156. errorOut(err, t, fmt.Sprintf("error thrown while waiting for container: %s", out))
  157. logsCmd := exec.Command(dockerBinary, "logs", out)
  158. containerLogs, _, err := runCommandWithOutput(logsCmd)
  159. errorOut(err, t, fmt.Sprintf("error thrown while trying to get container logs: %s", err))
  160. containerLogs = stripTrailingCharacters(containerLogs)
  161. if containerLogs != "blahblah" {
  162. t.Errorf("logs didn't print the container's logs %s", containerLogs)
  163. }
  164. rmCmd := exec.Command(dockerBinary, "rm", out)
  165. _, _, err = runCommandWithOutput(rmCmd)
  166. errorOut(err, t, fmt.Sprintf("rm failed to remove container %s", err))
  167. deleteAllContainers()
  168. logDone("run - pipe in with -i -a stdin")
  169. }
  170. // the container's ID should be printed when starting a container in detached mode
  171. func TestRunDetachedContainerIDPrinting(t *testing.T) {
  172. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "true")
  173. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  174. if err != nil {
  175. t.Fatalf("failed to run container: %v, output: %q", err, out)
  176. }
  177. out = stripTrailingCharacters(out)
  178. inspectCmd := exec.Command(dockerBinary, "inspect", out)
  179. inspectOut, _, err := runCommandWithOutput(inspectCmd)
  180. errorOut(err, t, fmt.Sprintf("out should've been a container id: %s %s", out, inspectOut))
  181. waitCmd := exec.Command(dockerBinary, "wait", out)
  182. _, _, err = runCommandWithOutput(waitCmd)
  183. errorOut(err, t, fmt.Sprintf("error thrown while waiting for container: %s", out))
  184. rmCmd := exec.Command(dockerBinary, "rm", out)
  185. rmOut, _, err := runCommandWithOutput(rmCmd)
  186. errorOut(err, t, "rm failed to remove container")
  187. rmOut = stripTrailingCharacters(rmOut)
  188. if rmOut != out {
  189. t.Errorf("rm didn't print the container ID %s %s", out, rmOut)
  190. }
  191. deleteAllContainers()
  192. logDone("run - print container ID in detached mode")
  193. }
  194. // the working directory should be set correctly
  195. func TestRunWorkingDirectory(t *testing.T) {
  196. runCmd := exec.Command(dockerBinary, "run", "-w", "/root", "busybox", "pwd")
  197. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  198. if err != nil {
  199. t.Fatalf("failed to run container: %v, output: %q", err, out)
  200. }
  201. out = stripTrailingCharacters(out)
  202. if out != "/root" {
  203. t.Errorf("-w failed to set working directory")
  204. }
  205. runCmd = exec.Command(dockerBinary, "run", "--workdir", "/root", "busybox", "pwd")
  206. out, _, _, err = runCommandWithStdoutStderr(runCmd)
  207. errorOut(err, t, out)
  208. out = stripTrailingCharacters(out)
  209. if out != "/root" {
  210. t.Errorf("--workdir failed to set working directory")
  211. }
  212. deleteAllContainers()
  213. logDone("run - run with working directory set by -w")
  214. logDone("run - run with working directory set by --workdir")
  215. }
  216. // pinging Google's DNS resolver should fail when we disable the networking
  217. func TestRunWithoutNetworking(t *testing.T) {
  218. runCmd := exec.Command(dockerBinary, "run", "--net=none", "busybox", "ping", "-c", "1", "8.8.8.8")
  219. out, _, exitCode, err := runCommandWithStdoutStderr(runCmd)
  220. if err != nil && exitCode != 1 {
  221. t.Fatal(out, err)
  222. }
  223. if exitCode != 1 {
  224. t.Errorf("--net=none should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
  225. }
  226. runCmd = exec.Command(dockerBinary, "run", "-n=false", "busybox", "ping", "-c", "1", "8.8.8.8")
  227. out, _, exitCode, err = runCommandWithStdoutStderr(runCmd)
  228. if err != nil && exitCode != 1 {
  229. t.Fatal(out, err)
  230. }
  231. if exitCode != 1 {
  232. t.Errorf("-n=false should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
  233. }
  234. deleteAllContainers()
  235. logDone("run - disable networking with --net=none")
  236. logDone("run - disable networking with -n=false")
  237. }
  238. // Regression test for #4741
  239. func TestRunWithVolumesAsFiles(t *testing.T) {
  240. runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", "/etc/hosts:/target-file", "busybox", "true")
  241. out, stderr, exitCode, err := runCommandWithStdoutStderr(runCmd)
  242. if err != nil && exitCode != 0 {
  243. t.Fatal("1", out, stderr, err)
  244. }
  245. runCmd = exec.Command(dockerBinary, "run", "--volumes-from", "test-data", "busybox", "cat", "/target-file")
  246. out, stderr, exitCode, err = runCommandWithStdoutStderr(runCmd)
  247. if err != nil && exitCode != 0 {
  248. t.Fatal("2", out, stderr, err)
  249. }
  250. deleteAllContainers()
  251. logDone("run - regression test for #4741 - volumes from as files")
  252. }
  253. // Regression test for #4979
  254. func TestRunWithVolumesFromExited(t *testing.T) {
  255. runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file")
  256. out, stderr, exitCode, err := runCommandWithStdoutStderr(runCmd)
  257. if err != nil && exitCode != 0 {
  258. t.Fatal("1", out, stderr, err)
  259. }
  260. runCmd = exec.Command(dockerBinary, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file")
  261. out, stderr, exitCode, err = runCommandWithStdoutStderr(runCmd)
  262. if err != nil && exitCode != 0 {
  263. t.Fatal("2", out, stderr, err)
  264. }
  265. deleteAllContainers()
  266. logDone("run - regression test for #4979 - volumes-from on exited container")
  267. }
  268. // Regression test for #4830
  269. func TestRunWithRelativePath(t *testing.T) {
  270. runCmd := exec.Command(dockerBinary, "run", "-v", "tmp:/other-tmp", "busybox", "true")
  271. if _, _, _, err := runCommandWithStdoutStderr(runCmd); err == nil {
  272. t.Fatalf("relative path should result in an error")
  273. }
  274. deleteAllContainers()
  275. logDone("run - volume with relative path")
  276. }
  277. func TestRunVolumesMountedAsReadonly(t *testing.T) {
  278. cmd := exec.Command(dockerBinary, "run", "-v", "/test:/test:ro", "busybox", "touch", "/test/somefile")
  279. if code, err := runCommand(cmd); err == nil || code == 0 {
  280. t.Fatalf("run should fail because volume is ro: exit code %d", code)
  281. }
  282. deleteAllContainers()
  283. logDone("run - volumes as readonly mount")
  284. }
  285. func TestRunVolumesFromInReadonlyMode(t *testing.T) {
  286. cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test", "busybox", "true")
  287. if _, err := runCommand(cmd); err != nil {
  288. t.Fatal(err)
  289. }
  290. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent:ro", "busybox", "touch", "/test/file")
  291. if code, err := runCommand(cmd); err == nil || code == 0 {
  292. t.Fatalf("run should fail because volume is ro: exit code %d", code)
  293. }
  294. deleteAllContainers()
  295. logDone("run - volumes from as readonly mount")
  296. }
  297. // Regression test for #1201
  298. func TestRunVolumesFromInReadWriteMode(t *testing.T) {
  299. cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test", "busybox", "true")
  300. if _, err := runCommand(cmd); err != nil {
  301. t.Fatal(err)
  302. }
  303. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent", "busybox", "touch", "/test/file")
  304. if _, err := runCommand(cmd); err != nil {
  305. t.Fatal(err)
  306. }
  307. deleteAllContainers()
  308. logDone("run - volumes from as read write mount")
  309. }
  310. func TestVolumesFromGetsProperMode(t *testing.T) {
  311. cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test:/test:ro", "busybox", "true")
  312. if _, err := runCommand(cmd); err != nil {
  313. t.Fatal(err)
  314. }
  315. // Expect this "rw" mode to be be ignored since the inheritted volume is "ro"
  316. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file")
  317. if _, err := runCommand(cmd); err == nil {
  318. t.Fatal("Expected volumes-from to inherit read-only volume even when passing in `rw`")
  319. }
  320. cmd = exec.Command(dockerBinary, "run", "--name", "parent2", "-v", "/test:/test:ro", "busybox", "true")
  321. if _, err := runCommand(cmd); err != nil {
  322. t.Fatal(err)
  323. }
  324. // Expect this to be read-only since both are "ro"
  325. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent2:ro", "busybox", "touch", "/test/file")
  326. if _, err := runCommand(cmd); err == nil {
  327. t.Fatal("Expected volumes-from to inherit read-only volume even when passing in `ro`")
  328. }
  329. deleteAllContainers()
  330. logDone("run - volumes from ignores `rw` if inherrited volume is `ro`")
  331. }
  332. // Test for #1351
  333. func TestRunApplyVolumesFromBeforeVolumes(t *testing.T) {
  334. cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test", "busybox", "touch", "/test/foo")
  335. if _, err := runCommand(cmd); err != nil {
  336. t.Fatal(err)
  337. }
  338. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent", "-v", "/test", "busybox", "cat", "/test/foo")
  339. if out, _, err := runCommandWithOutput(cmd); err != nil {
  340. t.Fatal(out, err)
  341. }
  342. deleteAllContainers()
  343. logDone("run - volumes from mounted first")
  344. }
  345. func TestRunMultipleVolumesFrom(t *testing.T) {
  346. cmd := exec.Command(dockerBinary, "run", "--name", "parent1", "-v", "/test", "busybox", "touch", "/test/foo")
  347. if _, err := runCommand(cmd); err != nil {
  348. t.Fatal(err)
  349. }
  350. cmd = exec.Command(dockerBinary, "run", "--name", "parent2", "-v", "/other", "busybox", "touch", "/other/bar")
  351. if _, err := runCommand(cmd); err != nil {
  352. t.Fatal(err)
  353. }
  354. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent1", "--volumes-from", "parent2",
  355. "busybox", "sh", "-c", "cat /test/foo && cat /other/bar")
  356. if _, err := runCommand(cmd); err != nil {
  357. t.Fatal(err)
  358. }
  359. deleteAllContainers()
  360. logDone("run - multiple volumes from")
  361. }
  362. // this tests verifies the ID format for the container
  363. func TestRunVerifyContainerID(t *testing.T) {
  364. cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "true")
  365. out, exit, err := runCommandWithOutput(cmd)
  366. if err != nil {
  367. t.Fatal(err)
  368. }
  369. if exit != 0 {
  370. t.Fatalf("expected exit code 0 received %d", exit)
  371. }
  372. match, err := regexp.MatchString("^[0-9a-f]{64}$", strings.TrimSuffix(out, "\n"))
  373. if err != nil {
  374. t.Fatal(err)
  375. }
  376. if !match {
  377. t.Fatalf("Invalid container ID: %s", out)
  378. }
  379. deleteAllContainers()
  380. logDone("run - verify container ID")
  381. }
  382. // Test that creating a container with a volume doesn't crash. Regression test for #995.
  383. func TestRunCreateVolume(t *testing.T) {
  384. cmd := exec.Command(dockerBinary, "run", "-v", "/var/lib/data", "busybox", "true")
  385. if _, err := runCommand(cmd); err != nil {
  386. t.Fatal(err)
  387. }
  388. deleteAllContainers()
  389. logDone("run - create docker managed volume")
  390. }
  391. // Test that creating a volume with a symlink in its path works correctly. Test for #5152.
  392. // Note that this bug happens only with symlinks with a target that starts with '/'.
  393. func TestRunCreateVolumeWithSymlink(t *testing.T) {
  394. buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-createvolumewithsymlink", "-")
  395. buildCmd.Stdin = strings.NewReader(`FROM busybox
  396. RUN mkdir /foo && ln -s /foo /bar`)
  397. buildCmd.Dir = workingDirectory
  398. err := buildCmd.Run()
  399. if err != nil {
  400. t.Fatalf("could not build 'docker-test-createvolumewithsymlink': %v", err)
  401. }
  402. cmd := exec.Command(dockerBinary, "run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", "docker-test-createvolumewithsymlink", "sh", "-c", "mount | grep -q /foo/foo")
  403. exitCode, err := runCommand(cmd)
  404. if err != nil || exitCode != 0 {
  405. t.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
  406. }
  407. var volPath string
  408. cmd = exec.Command(dockerBinary, "inspect", "-f", "{{range .Volumes}}{{.}}{{end}}", "test-createvolumewithsymlink")
  409. volPath, exitCode, err = runCommandWithOutput(cmd)
  410. if err != nil || exitCode != 0 {
  411. t.Fatalf("[inspect] err: %v, exitcode: %d", err, exitCode)
  412. }
  413. cmd = exec.Command(dockerBinary, "rm", "-v", "test-createvolumewithsymlink")
  414. exitCode, err = runCommand(cmd)
  415. if err != nil || exitCode != 0 {
  416. t.Fatalf("[rm] err: %v, exitcode: %d", err, exitCode)
  417. }
  418. f, err := os.Open(volPath)
  419. defer f.Close()
  420. if !os.IsNotExist(err) {
  421. t.Fatalf("[open] (expecting 'file does not exist' error) err: %v, volPath: %s", err, volPath)
  422. }
  423. deleteImages("docker-test-createvolumewithsymlink")
  424. deleteAllContainers()
  425. logDone("run - create volume with symlink")
  426. }
  427. // Tests that a volume path that has a symlink exists in a container mounting it with `--volumes-from`.
  428. func TestRunVolumesFromSymlinkPath(t *testing.T) {
  429. buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-volumesfromsymlinkpath", "-")
  430. buildCmd.Stdin = strings.NewReader(`FROM busybox
  431. RUN mkdir /baz && ln -s /baz /foo
  432. VOLUME ["/foo/bar"]`)
  433. buildCmd.Dir = workingDirectory
  434. err := buildCmd.Run()
  435. if err != nil {
  436. t.Fatalf("could not build 'docker-test-volumesfromsymlinkpath': %v", err)
  437. }
  438. cmd := exec.Command(dockerBinary, "run", "--name", "test-volumesfromsymlinkpath", "docker-test-volumesfromsymlinkpath")
  439. exitCode, err := runCommand(cmd)
  440. if err != nil || exitCode != 0 {
  441. t.Fatalf("[run] (volume) err: %v, exitcode: %d", err, exitCode)
  442. }
  443. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "test-volumesfromsymlinkpath", "busybox", "sh", "-c", "ls /foo | grep -q bar")
  444. exitCode, err = runCommand(cmd)
  445. if err != nil || exitCode != 0 {
  446. t.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
  447. }
  448. deleteImages("docker-test-volumesfromsymlinkpath")
  449. deleteAllContainers()
  450. logDone("run - volumes-from symlink path")
  451. }
  452. func TestRunExitCode(t *testing.T) {
  453. cmd := exec.Command(dockerBinary, "run", "busybox", "/bin/sh", "-c", "exit 72")
  454. exit, err := runCommand(cmd)
  455. if err == nil {
  456. t.Fatal("should not have a non nil error")
  457. }
  458. if exit != 72 {
  459. t.Fatalf("expected exit code 72 received %d", exit)
  460. }
  461. deleteAllContainers()
  462. logDone("run - correct exit code")
  463. }
  464. func TestRunUserDefaultsToRoot(t *testing.T) {
  465. cmd := exec.Command(dockerBinary, "run", "busybox", "id")
  466. out, _, err := runCommandWithOutput(cmd)
  467. if err != nil {
  468. t.Fatal(err, out)
  469. }
  470. if !strings.Contains(out, "uid=0(root) gid=0(root)") {
  471. t.Fatalf("expected root user got %s", out)
  472. }
  473. deleteAllContainers()
  474. logDone("run - default user")
  475. }
  476. func TestRunUserByName(t *testing.T) {
  477. cmd := exec.Command(dockerBinary, "run", "-u", "root", "busybox", "id")
  478. out, _, err := runCommandWithOutput(cmd)
  479. if err != nil {
  480. t.Fatal(err, out)
  481. }
  482. if !strings.Contains(out, "uid=0(root) gid=0(root)") {
  483. t.Fatalf("expected root user got %s", out)
  484. }
  485. deleteAllContainers()
  486. logDone("run - user by name")
  487. }
  488. func TestRunUserByID(t *testing.T) {
  489. cmd := exec.Command(dockerBinary, "run", "-u", "1", "busybox", "id")
  490. out, _, err := runCommandWithOutput(cmd)
  491. if err != nil {
  492. t.Fatal(err, out)
  493. }
  494. if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") {
  495. t.Fatalf("expected daemon user got %s", out)
  496. }
  497. deleteAllContainers()
  498. logDone("run - user by id")
  499. }
  500. func TestRunUserByIDBig(t *testing.T) {
  501. cmd := exec.Command(dockerBinary, "run", "-u", "2147483648", "busybox", "id")
  502. out, _, err := runCommandWithOutput(cmd)
  503. if err == nil {
  504. t.Fatal("No error, but must be.", out)
  505. }
  506. if !strings.Contains(out, "Uids and gids must be in range") {
  507. t.Fatalf("expected error about uids range, got %s", out)
  508. }
  509. deleteAllContainers()
  510. logDone("run - user by id, id too big")
  511. }
  512. func TestRunUserByIDNegative(t *testing.T) {
  513. cmd := exec.Command(dockerBinary, "run", "-u", "-1", "busybox", "id")
  514. out, _, err := runCommandWithOutput(cmd)
  515. if err == nil {
  516. t.Fatal("No error, but must be.", out)
  517. }
  518. if !strings.Contains(out, "Uids and gids must be in range") {
  519. t.Fatalf("expected error about uids range, got %s", out)
  520. }
  521. deleteAllContainers()
  522. logDone("run - user by id, id negative")
  523. }
  524. func TestRunUserByIDZero(t *testing.T) {
  525. cmd := exec.Command(dockerBinary, "run", "-u", "0", "busybox", "id")
  526. out, _, err := runCommandWithOutput(cmd)
  527. if err != nil {
  528. t.Fatal(err, out)
  529. }
  530. if !strings.Contains(out, "uid=0(root) gid=0(root) groups=10(wheel)") {
  531. t.Fatalf("expected daemon user got %s", out)
  532. }
  533. deleteAllContainers()
  534. logDone("run - user by id, zero uid")
  535. }
  536. func TestRunUserNotFound(t *testing.T) {
  537. cmd := exec.Command(dockerBinary, "run", "-u", "notme", "busybox", "id")
  538. _, err := runCommand(cmd)
  539. if err == nil {
  540. t.Fatal("unknown user should cause container to fail")
  541. }
  542. deleteAllContainers()
  543. logDone("run - user not found")
  544. }
  545. func TestRunTwoConcurrentContainers(t *testing.T) {
  546. group := sync.WaitGroup{}
  547. group.Add(2)
  548. for i := 0; i < 2; i++ {
  549. go func() {
  550. defer group.Done()
  551. cmd := exec.Command(dockerBinary, "run", "busybox", "sleep", "2")
  552. if _, err := runCommand(cmd); err != nil {
  553. t.Fatal(err)
  554. }
  555. }()
  556. }
  557. group.Wait()
  558. deleteAllContainers()
  559. logDone("run - two concurrent containers")
  560. }
  561. func TestRunEnvironment(t *testing.T) {
  562. cmd := exec.Command(dockerBinary, "run", "-h", "testing", "-e=FALSE=true", "-e=TRUE", "-e=TRICKY", "-e=HOME=", "busybox", "env")
  563. cmd.Env = append(os.Environ(),
  564. "TRUE=false",
  565. "TRICKY=tri\ncky\n",
  566. )
  567. out, _, err := runCommandWithOutput(cmd)
  568. if err != nil {
  569. t.Fatal(err, out)
  570. }
  571. actualEnv := strings.Split(out, "\n")
  572. if actualEnv[len(actualEnv)-1] == "" {
  573. actualEnv = actualEnv[:len(actualEnv)-1]
  574. }
  575. sort.Strings(actualEnv)
  576. goodEnv := []string{
  577. "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  578. "HOSTNAME=testing",
  579. "FALSE=true",
  580. "TRUE=false",
  581. "TRICKY=tri",
  582. "cky",
  583. "",
  584. "HOME=/root",
  585. }
  586. sort.Strings(goodEnv)
  587. if len(goodEnv) != len(actualEnv) {
  588. t.Fatalf("Wrong environment: should be %d variables, not: '%s'\n", len(goodEnv), strings.Join(actualEnv, ", "))
  589. }
  590. for i := range goodEnv {
  591. if actualEnv[i] != goodEnv[i] {
  592. t.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
  593. }
  594. }
  595. deleteAllContainers()
  596. logDone("run - verify environment")
  597. }
  598. func TestRunContainerNetwork(t *testing.T) {
  599. cmd := exec.Command(dockerBinary, "run", "busybox", "ping", "-c", "1", "127.0.0.1")
  600. if _, err := runCommand(cmd); err != nil {
  601. t.Fatal(err)
  602. }
  603. deleteAllContainers()
  604. logDone("run - test container network via ping")
  605. }
  606. // Issue #4681
  607. func TestRunLoopbackWhenNetworkDisabled(t *testing.T) {
  608. cmd := exec.Command(dockerBinary, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1")
  609. if _, err := runCommand(cmd); err != nil {
  610. t.Fatal(err)
  611. }
  612. deleteAllContainers()
  613. logDone("run - test container loopback when networking disabled")
  614. }
  615. func TestRunNetHostNotAllowedWithLinks(t *testing.T) {
  616. _, _, err := cmd(t, "run", "--name", "linked", "busybox", "true")
  617. cmd := exec.Command(dockerBinary, "run", "--net=host", "--link", "linked:linked", "busybox", "true")
  618. _, _, err = runCommandWithOutput(cmd)
  619. if err == nil {
  620. t.Fatal("Expected error")
  621. }
  622. deleteAllContainers()
  623. logDone("run - don't allow --net=host to be used with links")
  624. }
  625. func TestRunLoopbackOnlyExistsWhenNetworkingDisabled(t *testing.T) {
  626. cmd := exec.Command(dockerBinary, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up")
  627. out, _, err := runCommandWithOutput(cmd)
  628. if err != nil {
  629. t.Fatal(err, out)
  630. }
  631. var (
  632. count = 0
  633. parts = strings.Split(out, "\n")
  634. )
  635. for _, l := range parts {
  636. if l != "" {
  637. count++
  638. }
  639. }
  640. if count != 1 {
  641. t.Fatalf("Wrong interface count in container %d", count)
  642. }
  643. if !strings.HasPrefix(out, "1: lo") {
  644. t.Fatalf("Wrong interface in test container: expected [1: lo], got %s", out)
  645. }
  646. deleteAllContainers()
  647. logDone("run - test loopback only exists when networking disabled")
  648. }
  649. func TestRunPrivilegedCanMknod(t *testing.T) {
  650. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  651. out, _, err := runCommandWithOutput(cmd)
  652. if err != nil {
  653. t.Fatal(err)
  654. }
  655. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  656. t.Fatalf("expected output ok received %s", actual)
  657. }
  658. deleteAllContainers()
  659. logDone("run - test privileged can mknod")
  660. }
  661. func TestRunUnPrivilegedCanMknod(t *testing.T) {
  662. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  663. out, _, err := runCommandWithOutput(cmd)
  664. if err != nil {
  665. t.Fatal(err)
  666. }
  667. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  668. t.Fatalf("expected output ok received %s", actual)
  669. }
  670. deleteAllContainers()
  671. logDone("run - test un-privileged can mknod")
  672. }
  673. func TestRunCapDropInvalid(t *testing.T) {
  674. cmd := exec.Command(dockerBinary, "run", "--cap-drop=CHPASS", "busybox", "ls")
  675. out, _, err := runCommandWithOutput(cmd)
  676. if err == nil {
  677. t.Fatal(err, out)
  678. }
  679. logDone("run - test --cap-drop=CHPASS invalid")
  680. }
  681. func TestRunCapDropCannotMknod(t *testing.T) {
  682. cmd := exec.Command(dockerBinary, "run", "--cap-drop=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  683. out, _, err := runCommandWithOutput(cmd)
  684. if err == nil {
  685. t.Fatal(err, out)
  686. }
  687. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  688. t.Fatalf("expected output not ok received %s", actual)
  689. }
  690. deleteAllContainers()
  691. logDone("run - test --cap-drop=MKNOD cannot mknod")
  692. }
  693. func TestRunCapDropCannotMknodLowerCase(t *testing.T) {
  694. cmd := exec.Command(dockerBinary, "run", "--cap-drop=mknod", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  695. out, _, err := runCommandWithOutput(cmd)
  696. if err == nil {
  697. t.Fatal(err, out)
  698. }
  699. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  700. t.Fatalf("expected output not ok received %s", actual)
  701. }
  702. deleteAllContainers()
  703. logDone("run - test --cap-drop=mknod cannot mknod lowercase")
  704. }
  705. func TestRunCapDropALLCannotMknod(t *testing.T) {
  706. cmd := exec.Command(dockerBinary, "run", "--cap-drop=ALL", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  707. out, _, err := runCommandWithOutput(cmd)
  708. if err == nil {
  709. t.Fatal(err, out)
  710. }
  711. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  712. t.Fatalf("expected output not ok received %s", actual)
  713. }
  714. deleteAllContainers()
  715. logDone("run - test --cap-drop=ALL cannot mknod")
  716. }
  717. func TestRunCapDropALLAddMknodCannotMknod(t *testing.T) {
  718. cmd := exec.Command(dockerBinary, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  719. out, _, err := runCommandWithOutput(cmd)
  720. if err != nil {
  721. t.Fatal(err, out)
  722. }
  723. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  724. t.Fatalf("expected output ok received %s", actual)
  725. }
  726. deleteAllContainers()
  727. logDone("run - test --cap-drop=ALL --cap-add=MKNOD can mknod")
  728. }
  729. func TestRunCapAddInvalid(t *testing.T) {
  730. cmd := exec.Command(dockerBinary, "run", "--cap-add=CHPASS", "busybox", "ls")
  731. out, _, err := runCommandWithOutput(cmd)
  732. if err == nil {
  733. t.Fatal(err, out)
  734. }
  735. logDone("run - test --cap-add=CHPASS invalid")
  736. }
  737. func TestRunCapAddCanDownInterface(t *testing.T) {
  738. cmd := exec.Command(dockerBinary, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  739. out, _, err := runCommandWithOutput(cmd)
  740. if err != nil {
  741. t.Fatal(err, out)
  742. }
  743. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  744. t.Fatalf("expected output ok received %s", actual)
  745. }
  746. deleteAllContainers()
  747. logDone("run - test --cap-add=NET_ADMIN can set eth0 down")
  748. }
  749. func TestRunCapAddALLCanDownInterface(t *testing.T) {
  750. cmd := exec.Command(dockerBinary, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  751. out, _, err := runCommandWithOutput(cmd)
  752. if err != nil {
  753. t.Fatal(err, out)
  754. }
  755. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  756. t.Fatalf("expected output ok received %s", actual)
  757. }
  758. deleteAllContainers()
  759. logDone("run - test --cap-add=ALL can set eth0 down")
  760. }
  761. func TestRunCapAddALLDropNetAdminCanDownInterface(t *testing.T) {
  762. cmd := exec.Command(dockerBinary, "run", "--cap-add=ALL", "--cap-drop=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  763. out, _, err := runCommandWithOutput(cmd)
  764. if err == nil {
  765. t.Fatal(err, out)
  766. }
  767. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  768. t.Fatalf("expected output not ok received %s", actual)
  769. }
  770. deleteAllContainers()
  771. logDone("run - test --cap-add=ALL --cap-drop=NET_ADMIN cannot set eth0 down")
  772. }
  773. func TestRunPrivilegedCanMount(t *testing.T) {
  774. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
  775. out, _, err := runCommandWithOutput(cmd)
  776. if err != nil {
  777. t.Fatal(err)
  778. }
  779. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  780. t.Fatalf("expected output ok received %s", actual)
  781. }
  782. deleteAllContainers()
  783. logDone("run - test privileged can mount")
  784. }
  785. func TestRunUnPrivilegedCannotMount(t *testing.T) {
  786. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
  787. out, _, err := runCommandWithOutput(cmd)
  788. if err == nil {
  789. t.Fatal(err, out)
  790. }
  791. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  792. t.Fatalf("expected output not ok received %s", actual)
  793. }
  794. deleteAllContainers()
  795. logDone("run - test un-privileged cannot mount")
  796. }
  797. func TestRunSysNotWritableInNonPrivilegedContainers(t *testing.T) {
  798. cmd := exec.Command(dockerBinary, "run", "busybox", "touch", "/sys/kernel/profiling")
  799. if code, err := runCommand(cmd); err == nil || code == 0 {
  800. t.Fatal("sys should not be writable in a non privileged container")
  801. }
  802. deleteAllContainers()
  803. logDone("run - sys not writable in non privileged container")
  804. }
  805. func TestRunSysWritableInPrivilegedContainers(t *testing.T) {
  806. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "touch", "/sys/kernel/profiling")
  807. if code, err := runCommand(cmd); err != nil || code != 0 {
  808. t.Fatalf("sys should be writable in privileged container")
  809. }
  810. deleteAllContainers()
  811. logDone("run - sys writable in privileged container")
  812. }
  813. func TestRunProcNotWritableInNonPrivilegedContainers(t *testing.T) {
  814. cmd := exec.Command(dockerBinary, "run", "busybox", "touch", "/proc/sysrq-trigger")
  815. if code, err := runCommand(cmd); err == nil || code == 0 {
  816. t.Fatal("proc should not be writable in a non privileged container")
  817. }
  818. deleteAllContainers()
  819. logDone("run - proc not writable in non privileged container")
  820. }
  821. func TestRunProcWritableInPrivilegedContainers(t *testing.T) {
  822. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "touch", "/proc/sysrq-trigger")
  823. if code, err := runCommand(cmd); err != nil || code != 0 {
  824. t.Fatalf("proc should be writable in privileged container")
  825. }
  826. deleteAllContainers()
  827. logDone("run - proc writable in privileged container")
  828. }
  829. func TestRunWithCpuset(t *testing.T) {
  830. cmd := exec.Command(dockerBinary, "run", "--cpuset", "0", "busybox", "true")
  831. if code, err := runCommand(cmd); err != nil || code != 0 {
  832. t.Fatalf("container should run successfuly with cpuset of 0: %s", err)
  833. }
  834. deleteAllContainers()
  835. logDone("run - cpuset 0")
  836. }
  837. func TestRunDeviceNumbers(t *testing.T) {
  838. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "ls -l /dev/null")
  839. out, _, err := runCommandWithOutput(cmd)
  840. if err != nil {
  841. t.Fatal(err, out)
  842. }
  843. deviceLineFields := strings.Fields(out)
  844. deviceLineFields[6] = ""
  845. deviceLineFields[7] = ""
  846. deviceLineFields[8] = ""
  847. expected := []string{"crw-rw-rw-", "1", "root", "root", "1,", "3", "", "", "", "/dev/null"}
  848. if !(reflect.DeepEqual(deviceLineFields, expected)) {
  849. t.Fatalf("expected output\ncrw-rw-rw- 1 root root 1, 3 May 24 13:29 /dev/null\n received\n %s\n", out)
  850. }
  851. deleteAllContainers()
  852. logDone("run - test device numbers")
  853. }
  854. func TestRunThatCharacterDevicesActLikeCharacterDevices(t *testing.T) {
  855. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero")
  856. out, _, err := runCommandWithOutput(cmd)
  857. if err != nil {
  858. t.Fatal(err, out)
  859. }
  860. if actual := strings.Trim(out, "\r\n"); actual[0] == '0' {
  861. t.Fatalf("expected a new file called /zero to be create that is greater than 0 bytes long, but du says: %s", actual)
  862. }
  863. deleteAllContainers()
  864. logDone("run - test that character devices work.")
  865. }
  866. func TestRunUnprivilegedWithChroot(t *testing.T) {
  867. cmd := exec.Command(dockerBinary, "run", "busybox", "chroot", "/", "true")
  868. if _, err := runCommand(cmd); err != nil {
  869. t.Fatal(err)
  870. }
  871. deleteAllContainers()
  872. logDone("run - unprivileged with chroot")
  873. }
  874. func TestRunAddingOptionalDevices(t *testing.T) {
  875. cmd := exec.Command(dockerBinary, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo")
  876. out, _, err := runCommandWithOutput(cmd)
  877. if err != nil {
  878. t.Fatal(err, out)
  879. }
  880. if actual := strings.Trim(out, "\r\n"); actual != "/dev/nulo" {
  881. t.Fatalf("expected output /dev/nulo, received %s", actual)
  882. }
  883. deleteAllContainers()
  884. logDone("run - test --device argument")
  885. }
  886. func TestRunModeHostname(t *testing.T) {
  887. cmd := exec.Command(dockerBinary, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname")
  888. out, _, err := runCommandWithOutput(cmd)
  889. if err != nil {
  890. t.Fatal(err, out)
  891. }
  892. if actual := strings.Trim(out, "\r\n"); actual != "testhostname" {
  893. t.Fatalf("expected 'testhostname', but says: '%s'", actual)
  894. }
  895. cmd = exec.Command(dockerBinary, "run", "--net=host", "busybox", "cat", "/etc/hostname")
  896. out, _, err = runCommandWithOutput(cmd)
  897. if err != nil {
  898. t.Fatal(err, out)
  899. }
  900. hostname, err := os.Hostname()
  901. if err != nil {
  902. t.Fatal(err)
  903. }
  904. if actual := strings.Trim(out, "\r\n"); actual != hostname {
  905. t.Fatalf("expected '%s', but says: '%s'", hostname, actual)
  906. }
  907. deleteAllContainers()
  908. logDone("run - hostname and several network modes")
  909. }
  910. func TestRunRootWorkdir(t *testing.T) {
  911. s, _, err := cmd(t, "run", "--workdir", "/", "busybox", "pwd")
  912. if err != nil {
  913. t.Fatal(s, err)
  914. }
  915. if s != "/\n" {
  916. t.Fatalf("pwd returned '%s' (expected /\\n)", s)
  917. }
  918. deleteAllContainers()
  919. logDone("run - workdir /")
  920. }
  921. func TestRunAllowBindMountingRoot(t *testing.T) {
  922. s, _, err := cmd(t, "run", "-v", "/:/host", "busybox", "ls", "/host")
  923. if err != nil {
  924. t.Fatal(s, err)
  925. }
  926. deleteAllContainers()
  927. logDone("run - bind mount / as volume")
  928. }
  929. func TestRunDisallowBindMountingRootToRoot(t *testing.T) {
  930. cmd := exec.Command(dockerBinary, "run", "-v", "/:/", "busybox", "ls", "/host")
  931. out, _, err := runCommandWithOutput(cmd)
  932. if err == nil {
  933. t.Fatal(out, err)
  934. }
  935. deleteAllContainers()
  936. logDone("run - bind mount /:/ as volume should fail")
  937. }
  938. // Test recursive bind mount works by default
  939. func TestRunWithVolumesIsRecursive(t *testing.T) {
  940. tmpDir, err := ioutil.TempDir("", "docker_recursive_mount_test")
  941. if err != nil {
  942. t.Fatal(err)
  943. }
  944. defer os.RemoveAll(tmpDir)
  945. // Create a temporary tmpfs mount.
  946. tmpfsDir := filepath.Join(tmpDir, "tmpfs")
  947. if err := os.MkdirAll(tmpfsDir, 0777); err != nil {
  948. t.Fatalf("failed to mkdir at %s - %s", tmpfsDir, err)
  949. }
  950. if err := mount.Mount("tmpfs", tmpfsDir, "tmpfs", ""); err != nil {
  951. t.Fatalf("failed to create a tmpfs mount at %s - %s", tmpfsDir, err)
  952. }
  953. f, err := ioutil.TempFile(tmpfsDir, "touch-me")
  954. if err != nil {
  955. t.Fatal(err)
  956. }
  957. defer f.Close()
  958. runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox:latest", "ls", "/tmp/tmpfs")
  959. out, stderr, exitCode, err := runCommandWithStdoutStderr(runCmd)
  960. if err != nil && exitCode != 0 {
  961. t.Fatal(out, stderr, err)
  962. }
  963. if !strings.Contains(out, filepath.Base(f.Name())) {
  964. t.Fatal("Recursive bind mount test failed. Expected file not found")
  965. }
  966. deleteAllContainers()
  967. logDone("run - volumes are bind mounted recursively")
  968. }
  969. func TestRunDnsDefaultOptions(t *testing.T) {
  970. cmd := exec.Command(dockerBinary, "run", "busybox", "cat", "/etc/resolv.conf")
  971. actual, _, err := runCommandWithOutput(cmd)
  972. if err != nil {
  973. t.Fatal(err, actual)
  974. }
  975. resolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  976. if os.IsNotExist(err) {
  977. t.Fatalf("/etc/resolv.conf does not exist")
  978. }
  979. if actual != string(resolvConf) {
  980. t.Fatalf("expected resolv.conf is not the same of actual")
  981. }
  982. deleteAllContainers()
  983. logDone("run - dns default options")
  984. }
  985. func TestRunDnsOptions(t *testing.T) {
  986. cmd := exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
  987. out, _, err := runCommandWithOutput(cmd)
  988. if err != nil {
  989. t.Fatal(err, out)
  990. }
  991. actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1)
  992. if actual != "nameserver 127.0.0.1 search mydomain" {
  993. t.Fatalf("expected 'nameserver 127.0.0.1 search mydomain', but says: '%s'", actual)
  994. }
  995. cmd = exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "--dns-search=.", "busybox", "cat", "/etc/resolv.conf")
  996. out, _, err = runCommandWithOutput(cmd)
  997. if err != nil {
  998. t.Fatal(err, out)
  999. }
  1000. actual = strings.Replace(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ", -1)
  1001. if actual != "nameserver 127.0.0.1" {
  1002. t.Fatalf("expected 'nameserver 127.0.0.1', but says: '%s'", actual)
  1003. }
  1004. logDone("run - dns options")
  1005. }
  1006. func TestRunDnsOptionsBasedOnHostResolvConf(t *testing.T) {
  1007. resolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  1008. if os.IsNotExist(err) {
  1009. t.Fatalf("/etc/resolv.conf does not exist")
  1010. }
  1011. hostNamservers := resolvconf.GetNameservers(resolvConf)
  1012. hostSearch := resolvconf.GetSearchDomains(resolvConf)
  1013. cmd := exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf")
  1014. out, _, err := runCommandWithOutput(cmd)
  1015. if err != nil {
  1016. t.Fatal(err, out)
  1017. }
  1018. if actualNameservers := resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "127.0.0.1" {
  1019. t.Fatalf("expected '127.0.0.1', but says: '%s'", string(actualNameservers[0]))
  1020. }
  1021. actualSearch := resolvconf.GetSearchDomains([]byte(out))
  1022. if len(actualSearch) != len(hostSearch) {
  1023. t.Fatalf("expected '%s' search domain(s), but it has: '%s'", len(hostSearch), len(actualSearch))
  1024. }
  1025. for i := range actualSearch {
  1026. if actualSearch[i] != hostSearch[i] {
  1027. t.Fatalf("expected '%s' domain, but says: '%s'", actualSearch[i], hostSearch[i])
  1028. }
  1029. }
  1030. cmd = exec.Command(dockerBinary, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
  1031. out, _, err = runCommandWithOutput(cmd)
  1032. if err != nil {
  1033. t.Fatal(err, out)
  1034. }
  1035. actualNameservers := resolvconf.GetNameservers([]byte(out))
  1036. if len(actualNameservers) != len(hostNamservers) {
  1037. t.Fatalf("expected '%s' nameserver(s), but it has: '%s'", len(hostNamservers), len(actualNameservers))
  1038. }
  1039. for i := range actualNameservers {
  1040. if actualNameservers[i] != hostNamservers[i] {
  1041. t.Fatalf("expected '%s' nameserver, but says: '%s'", actualNameservers[i], hostNamservers[i])
  1042. }
  1043. }
  1044. if actualSearch = resolvconf.GetSearchDomains([]byte(out)); string(actualSearch[0]) != "mydomain" {
  1045. t.Fatalf("expected 'mydomain', but says: '%s'", string(actualSearch[0]))
  1046. }
  1047. deleteAllContainers()
  1048. logDone("run - dns options based on host resolv.conf")
  1049. }
  1050. func TestRunAddHost(t *testing.T) {
  1051. defer deleteAllContainers()
  1052. cmd := exec.Command(dockerBinary, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts")
  1053. out, _, err := runCommandWithOutput(cmd)
  1054. if err != nil {
  1055. t.Fatal(err, out)
  1056. }
  1057. actual := strings.Trim(out, "\r\n")
  1058. if actual != "86.75.30.9\textra" {
  1059. t.Fatalf("expected '86.75.30.9\textra', but says: '%s'", actual)
  1060. }
  1061. logDone("run - add-host option")
  1062. }
  1063. // Regression test for #6983
  1064. func TestRunAttachStdErrOnlyTTYMode(t *testing.T) {
  1065. cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stderr", "busybox", "true")
  1066. exitCode, err := runCommand(cmd)
  1067. if err != nil {
  1068. t.Fatal(err)
  1069. } else if exitCode != 0 {
  1070. t.Fatalf("Container should have exited with error code 0")
  1071. }
  1072. deleteAllContainers()
  1073. logDone("run - Attach stderr only with -t")
  1074. }
  1075. // Regression test for #6983
  1076. func TestRunAttachStdOutOnlyTTYMode(t *testing.T) {
  1077. cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stdout", "busybox", "true")
  1078. exitCode, err := runCommand(cmd)
  1079. if err != nil {
  1080. t.Fatal(err)
  1081. } else if exitCode != 0 {
  1082. t.Fatalf("Container should have exited with error code 0")
  1083. }
  1084. deleteAllContainers()
  1085. logDone("run - Attach stdout only with -t")
  1086. }
  1087. // Regression test for #6983
  1088. func TestRunAttachStdOutAndErrTTYMode(t *testing.T) {
  1089. cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true")
  1090. exitCode, err := runCommand(cmd)
  1091. if err != nil {
  1092. t.Fatal(err)
  1093. } else if exitCode != 0 {
  1094. t.Fatalf("Container should have exited with error code 0")
  1095. }
  1096. deleteAllContainers()
  1097. logDone("run - Attach stderr and stdout with -t")
  1098. }
  1099. func TestRunState(t *testing.T) {
  1100. defer deleteAllContainers()
  1101. cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  1102. out, _, err := runCommandWithOutput(cmd)
  1103. if err != nil {
  1104. t.Fatal(err, out)
  1105. }
  1106. id := strings.TrimSpace(out)
  1107. state, err := inspectField(id, "State.Running")
  1108. if err != nil {
  1109. t.Fatal(err)
  1110. }
  1111. if state != "true" {
  1112. t.Fatal("Container state is 'not running'")
  1113. }
  1114. pid1, err := inspectField(id, "State.Pid")
  1115. if err != nil {
  1116. t.Fatal(err)
  1117. }
  1118. if pid1 == "0" {
  1119. t.Fatal("Container state Pid 0")
  1120. }
  1121. cmd = exec.Command(dockerBinary, "stop", id)
  1122. out, _, err = runCommandWithOutput(cmd)
  1123. if err != nil {
  1124. t.Fatal(err, out)
  1125. }
  1126. state, err = inspectField(id, "State.Running")
  1127. if err != nil {
  1128. t.Fatal(err)
  1129. }
  1130. if state != "false" {
  1131. t.Fatal("Container state is 'running'")
  1132. }
  1133. pid2, err := inspectField(id, "State.Pid")
  1134. if err != nil {
  1135. t.Fatal(err)
  1136. }
  1137. if pid2 == pid1 {
  1138. t.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1139. }
  1140. cmd = exec.Command(dockerBinary, "start", id)
  1141. out, _, err = runCommandWithOutput(cmd)
  1142. if err != nil {
  1143. t.Fatal(err, out)
  1144. }
  1145. state, err = inspectField(id, "State.Running")
  1146. if err != nil {
  1147. t.Fatal(err)
  1148. }
  1149. if state != "true" {
  1150. t.Fatal("Container state is 'not running'")
  1151. }
  1152. pid3, err := inspectField(id, "State.Pid")
  1153. if err != nil {
  1154. t.Fatal(err)
  1155. }
  1156. if pid3 == pid1 {
  1157. t.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1158. }
  1159. logDone("run - test container state.")
  1160. }
  1161. // Test for #1737
  1162. func TestRunCopyVolumeUidGid(t *testing.T) {
  1163. name := "testrunvolumesuidgid"
  1164. defer deleteImages(name)
  1165. defer deleteAllContainers()
  1166. _, err := buildImage(name,
  1167. `FROM busybox
  1168. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1169. RUN echo 'dockerio:x:1001:' >> /etc/group
  1170. RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`,
  1171. true)
  1172. if err != nil {
  1173. t.Fatal(err)
  1174. }
  1175. // Test that the uid and gid is copied from the image to the volume
  1176. cmd := exec.Command(dockerBinary, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'")
  1177. out, _, err := runCommandWithOutput(cmd)
  1178. if err != nil {
  1179. t.Fatal(err, out)
  1180. }
  1181. out = strings.TrimSpace(out)
  1182. if out != "dockerio:dockerio" {
  1183. t.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out)
  1184. }
  1185. logDone("run - copy uid/gid for volume")
  1186. }
  1187. // Test for #1582
  1188. func TestRunCopyVolumeContent(t *testing.T) {
  1189. name := "testruncopyvolumecontent"
  1190. defer deleteImages(name)
  1191. defer deleteAllContainers()
  1192. _, err := buildImage(name,
  1193. `FROM busybox
  1194. RUN mkdir -p /hello/local && echo hello > /hello/local/world`,
  1195. true)
  1196. if err != nil {
  1197. t.Fatal(err)
  1198. }
  1199. // Test that the content is copied from the image to the volume
  1200. cmd := exec.Command(dockerBinary, "run", "--rm", "-v", "/hello", name, "sh", "-c", "find", "/hello")
  1201. out, _, err := runCommandWithOutput(cmd)
  1202. if err != nil {
  1203. t.Fatal(err, out)
  1204. }
  1205. if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) {
  1206. t.Fatal("Container failed to transfer content to volume")
  1207. }
  1208. logDone("run - copy volume content")
  1209. }
  1210. func TestRunCleanupCmdOnEntrypoint(t *testing.T) {
  1211. name := "testrunmdcleanuponentrypoint"
  1212. defer deleteImages(name)
  1213. defer deleteAllContainers()
  1214. if _, err := buildImage(name,
  1215. `FROM busybox
  1216. ENTRYPOINT ["echo"]
  1217. CMD ["testingpoint"]`,
  1218. true); err != nil {
  1219. t.Fatal(err)
  1220. }
  1221. runCmd := exec.Command(dockerBinary, "run", "--entrypoint", "whoami", name)
  1222. out, exit, err := runCommandWithOutput(runCmd)
  1223. if err != nil {
  1224. t.Fatalf("Error: %v, out: %q", err, out)
  1225. }
  1226. if exit != 0 {
  1227. t.Fatalf("expected exit code 0 received %d, out: %q", exit, out)
  1228. }
  1229. out = strings.TrimSpace(out)
  1230. if out != "root" {
  1231. t.Fatalf("Expected output root, got %q", out)
  1232. }
  1233. logDone("run - cleanup cmd on --entrypoint")
  1234. }
  1235. // TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected
  1236. func TestRunWorkdirExistsAndIsFile(t *testing.T) {
  1237. defer deleteAllContainers()
  1238. runCmd := exec.Command(dockerBinary, "run", "-w", "/bin/cat", "busybox")
  1239. out, exit, err := runCommandWithOutput(runCmd)
  1240. if !(err != nil && exit == 1 && strings.Contains(out, "Cannot mkdir: /bin/cat is not a directory")) {
  1241. t.Fatalf("Docker must complains about making dir, but we got out: %s, exit: %d, err: %s", out, exit, err)
  1242. }
  1243. logDone("run - error on existing file for workdir")
  1244. }
  1245. func TestRunExitOnStdinClose(t *testing.T) {
  1246. name := "testrunexitonstdinclose"
  1247. defer deleteAllContainers()
  1248. runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", "/bin/cat")
  1249. stdin, err := runCmd.StdinPipe()
  1250. if err != nil {
  1251. t.Fatal(err)
  1252. }
  1253. stdout, err := runCmd.StdoutPipe()
  1254. if err != nil {
  1255. t.Fatal(err)
  1256. }
  1257. if err := runCmd.Start(); err != nil {
  1258. t.Fatal(err)
  1259. }
  1260. if _, err := stdin.Write([]byte("hello\n")); err != nil {
  1261. t.Fatal(err)
  1262. }
  1263. r := bufio.NewReader(stdout)
  1264. line, err := r.ReadString('\n')
  1265. if err != nil {
  1266. t.Fatal(err)
  1267. }
  1268. line = strings.TrimSpace(line)
  1269. if line != "hello" {
  1270. t.Fatalf("Output should be 'hello', got '%q'", line)
  1271. }
  1272. if err := stdin.Close(); err != nil {
  1273. t.Fatal(err)
  1274. }
  1275. finish := make(chan struct{})
  1276. go func() {
  1277. if err := runCmd.Wait(); err != nil {
  1278. t.Fatal(err)
  1279. }
  1280. close(finish)
  1281. }()
  1282. select {
  1283. case <-finish:
  1284. case <-time.After(1 * time.Second):
  1285. t.Fatal("docker run failed to exit on stdin close")
  1286. }
  1287. state, err := inspectField(name, "State.Running")
  1288. if err != nil {
  1289. t.Fatal(err)
  1290. }
  1291. if state != "false" {
  1292. t.Fatal("Container must be stopped after stdin closing")
  1293. }
  1294. logDone("run - exit on stdin closing")
  1295. }
  1296. // Test for #2267
  1297. func TestRunWriteHostsFileAndNotCommit(t *testing.T) {
  1298. name := "writehosts"
  1299. cmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hosts && cat /etc/hosts")
  1300. out, _, err := runCommandWithOutput(cmd)
  1301. if err != nil {
  1302. t.Fatal(err, out)
  1303. }
  1304. if !strings.Contains(out, "test2267") {
  1305. t.Fatal("/etc/hosts should contain 'test2267'")
  1306. }
  1307. cmd = exec.Command(dockerBinary, "diff", name)
  1308. if err != nil {
  1309. t.Fatal(err, out)
  1310. }
  1311. out, _, err = runCommandWithOutput(cmd)
  1312. if err != nil {
  1313. t.Fatal(err, out)
  1314. }
  1315. if len(strings.Trim(out, "\r\n")) != 0 {
  1316. t.Fatal("diff should be empty")
  1317. }
  1318. logDone("run - write to /etc/hosts and not commited")
  1319. }
  1320. // Test for #2267
  1321. func TestRunWriteHostnameFileAndNotCommit(t *testing.T) {
  1322. name := "writehostname"
  1323. cmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hostname && cat /etc/hostname")
  1324. out, _, err := runCommandWithOutput(cmd)
  1325. if err != nil {
  1326. t.Fatal(err, out)
  1327. }
  1328. if !strings.Contains(out, "test2267") {
  1329. t.Fatal("/etc/hostname should contain 'test2267'")
  1330. }
  1331. cmd = exec.Command(dockerBinary, "diff", name)
  1332. if err != nil {
  1333. t.Fatal(err, out)
  1334. }
  1335. out, _, err = runCommandWithOutput(cmd)
  1336. if err != nil {
  1337. t.Fatal(err, out)
  1338. }
  1339. if len(strings.Trim(out, "\r\n")) != 0 {
  1340. t.Fatal("diff should be empty")
  1341. }
  1342. logDone("run - write to /etc/hostname and not commited")
  1343. }
  1344. // Test for #2267
  1345. func TestRunWriteResolvFileAndNotCommit(t *testing.T) {
  1346. name := "writeresolv"
  1347. cmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/resolv.conf && cat /etc/resolv.conf")
  1348. out, _, err := runCommandWithOutput(cmd)
  1349. if err != nil {
  1350. t.Fatal(err, out)
  1351. }
  1352. if !strings.Contains(out, "test2267") {
  1353. t.Fatal("/etc/resolv.conf should contain 'test2267'")
  1354. }
  1355. cmd = exec.Command(dockerBinary, "diff", name)
  1356. if err != nil {
  1357. t.Fatal(err, out)
  1358. }
  1359. out, _, err = runCommandWithOutput(cmd)
  1360. if err != nil {
  1361. t.Fatal(err, out)
  1362. }
  1363. if len(strings.Trim(out, "\r\n")) != 0 {
  1364. t.Fatal("diff should be empty")
  1365. }
  1366. logDone("run - write to /etc/resolv.conf and not commited")
  1367. }
  1368. func TestRunWithBadDevice(t *testing.T) {
  1369. name := "baddevice"
  1370. cmd := exec.Command(dockerBinary, "run", "--name", name, "--device", "/etc", "busybox", "true")
  1371. out, _, err := runCommandWithOutput(cmd)
  1372. if err == nil {
  1373. t.Fatal("Run should fail with bad device")
  1374. }
  1375. expected := `"/etc": not a device node`
  1376. if !strings.Contains(out, expected) {
  1377. t.Fatalf("Output should contain %q, actual out: %q", expected, out)
  1378. }
  1379. logDone("run - error with bad device")
  1380. }
  1381. func TestRunEntrypoint(t *testing.T) {
  1382. name := "entrypoint"
  1383. cmd := exec.Command(dockerBinary, "run", "--name", name, "--entrypoint", "/bin/echo", "busybox", "-n", "foobar")
  1384. out, _, err := runCommandWithOutput(cmd)
  1385. if err != nil {
  1386. t.Fatal(err, out)
  1387. }
  1388. expected := "foobar"
  1389. if out != expected {
  1390. t.Fatalf("Output should be %q, actual out: %q", expected, out)
  1391. }
  1392. logDone("run - entrypoint")
  1393. }
  1394. func TestRunBindMounts(t *testing.T) {
  1395. tmpDir, err := ioutil.TempDir("", "docker-test-container")
  1396. if err != nil {
  1397. t.Fatal(err)
  1398. }
  1399. defer os.RemoveAll(tmpDir)
  1400. writeFile(path.Join(tmpDir, "touch-me"), "", t)
  1401. // Test reading from a read-only bind mount
  1402. cmd := exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox", "ls", "/tmp")
  1403. out, _, err := runCommandWithOutput(cmd)
  1404. if err != nil {
  1405. t.Fatal(err, out)
  1406. }
  1407. if !strings.Contains(out, "touch-me") {
  1408. t.Fatal("Container failed to read from bind mount")
  1409. }
  1410. // test writing to bind mount
  1411. cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla")
  1412. out, _, err = runCommandWithOutput(cmd)
  1413. if err != nil {
  1414. t.Fatal(err, out)
  1415. }
  1416. readFile(path.Join(tmpDir, "holla"), t) // Will fail if the file doesn't exist
  1417. // test mounting to an illegal destination directory
  1418. cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:.", tmpDir), "busybox", "ls", ".")
  1419. _, err = runCommand(cmd)
  1420. if err == nil {
  1421. t.Fatal("Container bind mounted illegal directory")
  1422. }
  1423. // test mount a file
  1424. cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla")
  1425. _, err = runCommand(cmd)
  1426. if err != nil {
  1427. t.Fatal(err, out)
  1428. }
  1429. content := readFile(path.Join(tmpDir, "holla"), t) // Will fail if the file doesn't exist
  1430. expected := "yotta"
  1431. if content != expected {
  1432. t.Fatalf("Output should be %q, actual out: %q", expected, content)
  1433. }
  1434. logDone("run - bind mounts")
  1435. }
  1436. func TestRunMutableNetworkFiles(t *testing.T) {
  1437. defer deleteAllContainers()
  1438. for _, fn := range []string{"resolv.conf", "hosts"} {
  1439. deleteAllContainers()
  1440. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", "c1", "busybox", "sh", "-c", fmt.Sprintf("echo success >/etc/%s; while true; do sleep 1; done", fn)))
  1441. if err != nil {
  1442. t.Fatal(err, out)
  1443. }
  1444. time.Sleep(1 * time.Second)
  1445. contID := strings.TrimSpace(out)
  1446. f, err := os.Open(filepath.Join("/var/lib/docker/containers", contID, fn))
  1447. if err != nil {
  1448. t.Fatal(err)
  1449. }
  1450. content, err := ioutil.ReadAll(f)
  1451. f.Close()
  1452. if strings.TrimSpace(string(content)) != "success" {
  1453. t.Fatal("Content was not what was modified in the container", string(content))
  1454. }
  1455. 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)))
  1456. if err != nil {
  1457. t.Fatal(err)
  1458. }
  1459. contID = strings.TrimSpace(out)
  1460. resolvConfPath := filepath.Join("/var/lib/docker/containers", contID, fn)
  1461. f, err = os.OpenFile(resolvConfPath, os.O_WRONLY|os.O_SYNC|os.O_APPEND, 0644)
  1462. if err != nil {
  1463. t.Fatal(err)
  1464. }
  1465. if _, err := f.Seek(0, 0); err != nil {
  1466. f.Close()
  1467. t.Fatal(err)
  1468. }
  1469. if err := f.Truncate(0); err != nil {
  1470. f.Close()
  1471. t.Fatal(err)
  1472. }
  1473. if _, err := f.Write([]byte("success2\n")); err != nil {
  1474. f.Close()
  1475. t.Fatal(err)
  1476. }
  1477. f.Close()
  1478. time.Sleep(2 * time.Second) // don't race sleep
  1479. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "logs", "c2"))
  1480. if err != nil {
  1481. t.Fatal(err)
  1482. }
  1483. lines := strings.Split(out, "\n")
  1484. if strings.TrimSpace(lines[len(lines)-2]) != "success2" {
  1485. t.Fatalf("Did not find the correct output in /etc/%s: %s %#v", fn, out, lines)
  1486. }
  1487. }
  1488. }
  1489. func TestRunHostsLinkedContainerUpdate(t *testing.T) {
  1490. deleteAllContainers()
  1491. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", "c1", "busybox", "sh", "-c", "while true; do sleep 1; done"))
  1492. if err != nil {
  1493. t.Fatal(err, out)
  1494. }
  1495. // TODO fix docker cp and /etc/hosts
  1496. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--link", "c1:c1", "--name", "c2", "busybox", "sh", "-c", "while true;do sleep 1; done"))
  1497. if err != nil {
  1498. t.Fatal(err, out)
  1499. }
  1500. contID := strings.TrimSpace(out)
  1501. f, err := os.Open(filepath.Join("/var/lib/docker/containers", contID, "hosts"))
  1502. if err != nil {
  1503. t.Fatal(err)
  1504. }
  1505. originalContent, err := ioutil.ReadAll(f)
  1506. f.Close()
  1507. if err != nil {
  1508. t.Fatal(err)
  1509. }
  1510. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "restart", "-t", "0", "c1"))
  1511. if err != nil {
  1512. t.Fatal(err, out)
  1513. }
  1514. f, err = os.Open(filepath.Join("/var/lib/docker/containers", contID, "hosts"))
  1515. if err != nil {
  1516. t.Fatal(err)
  1517. }
  1518. newContent, err := ioutil.ReadAll(f)
  1519. f.Close()
  1520. if err != nil {
  1521. t.Fatal(err)
  1522. }
  1523. if strings.TrimSpace(string(originalContent)) == strings.TrimSpace(string(newContent)) {
  1524. t.Fatalf("expected /etc/hosts to be updated, but wasn't")
  1525. }
  1526. deleteAllContainers()
  1527. logDone("run - /etc/hosts updated in parent when restart")
  1528. }
  1529. // Ensure that CIDFile gets deleted if it's empty
  1530. // Perform this test by making `docker run` fail
  1531. func TestRunCidFileCleanupIfEmpty(t *testing.T) {
  1532. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1533. if err != nil {
  1534. t.Fatal(err)
  1535. }
  1536. defer os.RemoveAll(tmpDir)
  1537. tmpCidFile := path.Join(tmpDir, "cid")
  1538. cmd := exec.Command(dockerBinary, "run", "--cidfile", tmpCidFile, "scratch")
  1539. out, _, err := runCommandWithOutput(cmd)
  1540. t.Log(out)
  1541. if err == nil {
  1542. t.Fatal("Run without command must fail")
  1543. }
  1544. if _, err := os.Stat(tmpCidFile); err == nil {
  1545. t.Fatalf("empty CIDFile '%s' should've been deleted", tmpCidFile)
  1546. }
  1547. deleteAllContainers()
  1548. logDone("run - cleanup empty cidfile on fail")
  1549. }
  1550. // #2098 - Docker cidFiles only contain short version of the containerId
  1551. //sudo docker run --cidfile /tmp/docker_test.cid ubuntu echo "test"
  1552. // TestRunCidFile tests that run --cidfile returns the longid
  1553. func TestRunCidFileCheckIDLength(t *testing.T) {
  1554. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1555. if err != nil {
  1556. t.Fatal(err)
  1557. }
  1558. tmpCidFile := path.Join(tmpDir, "cid")
  1559. defer os.RemoveAll(tmpDir)
  1560. cmd := exec.Command(dockerBinary, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true")
  1561. out, _, err := runCommandWithOutput(cmd)
  1562. if err != nil {
  1563. t.Fatal(err)
  1564. }
  1565. id := strings.TrimSpace(out)
  1566. buffer, err := ioutil.ReadFile(tmpCidFile)
  1567. if err != nil {
  1568. t.Fatal(err)
  1569. }
  1570. cid := string(buffer)
  1571. if len(cid) != 64 {
  1572. t.Fatalf("--cidfile should be a long id, not '%s'", id)
  1573. }
  1574. if cid != id {
  1575. t.Fatalf("cid must be equal to %s, got %s", id, cid)
  1576. }
  1577. deleteAllContainers()
  1578. logDone("run - cidfile contains long id")
  1579. }
  1580. func TestRunNetworkNotInitializedNoneMode(t *testing.T) {
  1581. cmd := exec.Command(dockerBinary, "run", "-d", "--net=none", "busybox", "top")
  1582. out, _, err := runCommandWithOutput(cmd)
  1583. if err != nil {
  1584. t.Fatal(err)
  1585. }
  1586. id := strings.TrimSpace(out)
  1587. res, err := inspectField(id, "NetworkSettings.IPAddress")
  1588. if err != nil {
  1589. t.Fatal(err)
  1590. }
  1591. if res != "" {
  1592. t.Fatal("For 'none' mode network must not be initialized, but container got IP: %s", res)
  1593. }
  1594. deleteAllContainers()
  1595. logDone("run - network must not be initialized in 'none' mode")
  1596. }
  1597. func TestRunDeallocatePortOnMissingIptablesRule(t *testing.T) {
  1598. cmd := exec.Command(dockerBinary, "run", "-d", "-p", "23:23", "busybox", "top")
  1599. out, _, err := runCommandWithOutput(cmd)
  1600. if err != nil {
  1601. t.Fatal(err)
  1602. }
  1603. id := strings.TrimSpace(out)
  1604. ip, err := inspectField(id, "NetworkSettings.IPAddress")
  1605. if err != nil {
  1606. t.Fatal(err)
  1607. }
  1608. iptCmd := exec.Command("iptables", "-D", "FORWARD", "-d", fmt.Sprintf("%s/32", ip),
  1609. "!", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-m", "tcp", "--dport", "23", "-j", "ACCEPT")
  1610. out, _, err = runCommandWithOutput(iptCmd)
  1611. if err != nil {
  1612. t.Fatal(err, out)
  1613. }
  1614. if err := deleteContainer(id); err != nil {
  1615. t.Fatal(err)
  1616. }
  1617. cmd = exec.Command(dockerBinary, "run", "-d", "-p", "23:23", "busybox", "top")
  1618. out, _, err = runCommandWithOutput(cmd)
  1619. if err != nil {
  1620. t.Fatal(err, out)
  1621. }
  1622. deleteAllContainers()
  1623. logDone("run - port should be deallocated even on iptables error")
  1624. }
  1625. func TestRunPortInUse(t *testing.T) {
  1626. port := "1234"
  1627. l, err := net.Listen("tcp", ":"+port)
  1628. if err != nil {
  1629. t.Fatal(err)
  1630. }
  1631. defer l.Close()
  1632. cmd := exec.Command(dockerBinary, "run", "-p", port+":80", "busybox", "true")
  1633. out, _, err := runCommandWithOutput(cmd)
  1634. if err == nil {
  1635. t.Fatalf("Binding on used port must fail")
  1636. }
  1637. if !strings.Contains(out, "address already in use") {
  1638. t.Fatalf("Out must be about \"address already in use\", got %s", out)
  1639. }
  1640. deleteAllContainers()
  1641. logDone("run - fail if port already in use")
  1642. }
  1643. // Regression test for #7792
  1644. func TestRunMountOrdering(t *testing.T) {
  1645. tmpDir, err := ioutil.TempDir("", "docker_nested_mount_test")
  1646. if err != nil {
  1647. t.Fatal(err)
  1648. }
  1649. defer os.RemoveAll(tmpDir)
  1650. tmpDir2, err := ioutil.TempDir("", "docker_nested_mount_test2")
  1651. if err != nil {
  1652. t.Fatal(err)
  1653. }
  1654. defer os.RemoveAll(tmpDir2)
  1655. // Create a temporary tmpfs mount.
  1656. fooDir := filepath.Join(tmpDir, "foo")
  1657. if err := os.MkdirAll(filepath.Join(tmpDir, "foo"), 0755); err != nil {
  1658. t.Fatalf("failed to mkdir at %s - %s", fooDir, err)
  1659. }
  1660. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", fooDir), []byte{}, 0644); err != nil {
  1661. t.Fatal(err)
  1662. }
  1663. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir), []byte{}, 0644); err != nil {
  1664. t.Fatal(err)
  1665. }
  1666. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir2), []byte{}, 0644); err != nil {
  1667. t.Fatal(err)
  1668. }
  1669. 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")
  1670. out, _, err := runCommandWithOutput(cmd)
  1671. if err != nil {
  1672. t.Fatal(out, err)
  1673. }
  1674. deleteAllContainers()
  1675. logDone("run - volumes are mounted in the correct order")
  1676. }
  1677. func TestRunExecDir(t *testing.T) {
  1678. cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  1679. out, _, err := runCommandWithOutput(cmd)
  1680. if err != nil {
  1681. t.Fatal(err, out)
  1682. }
  1683. id := strings.TrimSpace(out)
  1684. execDir := filepath.Join(execDriverPath, id)
  1685. stateFile := filepath.Join(execDir, "state.json")
  1686. contFile := filepath.Join(execDir, "container.json")
  1687. {
  1688. fi, err := os.Stat(execDir)
  1689. if err != nil {
  1690. t.Fatal(err)
  1691. }
  1692. if !fi.IsDir() {
  1693. t.Fatalf("%q must be a directory", execDir)
  1694. }
  1695. fi, err = os.Stat(stateFile)
  1696. if err != nil {
  1697. t.Fatal(err)
  1698. }
  1699. fi, err = os.Stat(contFile)
  1700. if err != nil {
  1701. t.Fatal(err)
  1702. }
  1703. }
  1704. stopCmd := exec.Command(dockerBinary, "stop", id)
  1705. out, _, err = runCommandWithOutput(stopCmd)
  1706. if err != nil {
  1707. t.Fatal(err, out)
  1708. }
  1709. {
  1710. fi, err := os.Stat(execDir)
  1711. if err != nil {
  1712. t.Fatal(err)
  1713. }
  1714. if !fi.IsDir() {
  1715. t.Fatalf("%q must be a directory", execDir)
  1716. }
  1717. fi, err = os.Stat(stateFile)
  1718. if err == nil {
  1719. t.Fatalf("Statefile %q is exists for stopped container!", stateFile)
  1720. }
  1721. if !os.IsNotExist(err) {
  1722. t.Fatalf("Error should be about non-existing, got %s", err)
  1723. }
  1724. fi, err = os.Stat(contFile)
  1725. if err == nil {
  1726. t.Fatalf("Container file %q is exists for stopped container!", contFile)
  1727. }
  1728. if !os.IsNotExist(err) {
  1729. t.Fatalf("Error should be about non-existing, got %s", err)
  1730. }
  1731. }
  1732. startCmd := exec.Command(dockerBinary, "start", id)
  1733. out, _, err = runCommandWithOutput(startCmd)
  1734. if err != nil {
  1735. t.Fatal(err, out)
  1736. }
  1737. {
  1738. fi, err := os.Stat(execDir)
  1739. if err != nil {
  1740. t.Fatal(err)
  1741. }
  1742. if !fi.IsDir() {
  1743. t.Fatalf("%q must be a directory", execDir)
  1744. }
  1745. fi, err = os.Stat(stateFile)
  1746. if err != nil {
  1747. t.Fatal(err)
  1748. }
  1749. fi, err = os.Stat(contFile)
  1750. if err != nil {
  1751. t.Fatal(err)
  1752. }
  1753. }
  1754. rmCmd := exec.Command(dockerBinary, "rm", "-f", id)
  1755. out, _, err = runCommandWithOutput(rmCmd)
  1756. if err != nil {
  1757. t.Fatal(err, out)
  1758. }
  1759. {
  1760. _, err := os.Stat(execDir)
  1761. if err == nil {
  1762. t.Fatal(err)
  1763. }
  1764. if err == nil {
  1765. t.Fatalf("Exec directory %q is exists for removed container!", execDir)
  1766. }
  1767. if !os.IsNotExist(err) {
  1768. t.Fatalf("Error should be about non-existing, got %s", err)
  1769. }
  1770. }
  1771. logDone("run - check execdriver dir behavior")
  1772. }