docker_cli_run_test.go 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996
  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 TestDockerRunEchoStdout(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 TestDockerRunEchoStdoutWithMemoryLimit(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 TestDockerRunEchoStdoutWitCPULimit(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 TestDockerRunEchoStdoutWithCPUAndMemoryLimit(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 TestDockerRunEchoNamedContainer(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 TestDockerRunLeakyFileDescriptors(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 TestDockerRunPingGoogle(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 TestDockerRunExitCodeZero(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 TestDockerRunExitCodeOne(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 TestDockerRunDetachedContainerIDPrinting(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 TestDockerRunWorkingDirectory(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 TestDockerRunWithoutNetworking(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 TestDockerRunWithVolumesAsFiles(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 TestDockerRunWithVolumesFromExited(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 TestDockerRunWithRelativePath(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 TestVolumesMountedAsReadonly(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 TestVolumesFromInReadonlyMode(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 TestVolumesFromInReadWriteMode(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 TestVolumesFromInheritsReadOnly(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 to inherit read-only volume even when passing in `rw`")
  319. }
  320. deleteAllContainers()
  321. logDone("run - volumes from ignores `rw` if inherrited volume is `ro`")
  322. }
  323. // Test for #1351
  324. func TestApplyVolumesFromBeforeVolumes(t *testing.T) {
  325. cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test", "busybox", "touch", "/test/foo")
  326. if _, err := runCommand(cmd); err != nil {
  327. t.Fatal(err)
  328. }
  329. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent", "-v", "/test", "busybox", "cat", "/test/foo")
  330. if _, err := runCommand(cmd); err != nil {
  331. t.Fatal(err)
  332. }
  333. deleteAllContainers()
  334. logDone("run - volumes from mounted first")
  335. }
  336. func TestMultipleVolumesFrom(t *testing.T) {
  337. cmd := exec.Command(dockerBinary, "run", "--name", "parent1", "-v", "/test", "busybox", "touch", "/test/foo")
  338. if _, err := runCommand(cmd); err != nil {
  339. t.Fatal(err)
  340. }
  341. cmd = exec.Command(dockerBinary, "run", "--name", "parent2", "-v", "/other", "busybox", "touch", "/other/bar")
  342. if _, err := runCommand(cmd); err != nil {
  343. t.Fatal(err)
  344. }
  345. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent1", "--volumes-from", "parent2",
  346. "busybox", "sh", "-c", "cat /test/foo && cat /other/bar")
  347. if _, err := runCommand(cmd); err != nil {
  348. t.Fatal(err)
  349. }
  350. deleteAllContainers()
  351. logDone("run - multiple volumes from")
  352. }
  353. // this tests verifies the ID format for the container
  354. func TestVerifyContainerID(t *testing.T) {
  355. cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "true")
  356. out, exit, err := runCommandWithOutput(cmd)
  357. if err != nil {
  358. t.Fatal(err)
  359. }
  360. if exit != 0 {
  361. t.Fatalf("expected exit code 0 received %d", exit)
  362. }
  363. match, err := regexp.MatchString("^[0-9a-f]{64}$", strings.TrimSuffix(out, "\n"))
  364. if err != nil {
  365. t.Fatal(err)
  366. }
  367. if !match {
  368. t.Fatalf("Invalid container ID: %s", out)
  369. }
  370. deleteAllContainers()
  371. logDone("run - verify container ID")
  372. }
  373. // Test that creating a container with a volume doesn't crash. Regression test for #995.
  374. func TestCreateVolume(t *testing.T) {
  375. cmd := exec.Command(dockerBinary, "run", "-v", "/var/lib/data", "busybox", "true")
  376. if _, err := runCommand(cmd); err != nil {
  377. t.Fatal(err)
  378. }
  379. deleteAllContainers()
  380. logDone("run - create docker managed volume")
  381. }
  382. // Test that creating a volume with a symlink in its path works correctly. Test for #5152.
  383. // Note that this bug happens only with symlinks with a target that starts with '/'.
  384. func TestCreateVolumeWithSymlink(t *testing.T) {
  385. buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-createvolumewithsymlink", "-")
  386. buildCmd.Stdin = strings.NewReader(`FROM busybox
  387. RUN mkdir /foo && ln -s /foo /bar`)
  388. buildCmd.Dir = workingDirectory
  389. err := buildCmd.Run()
  390. if err != nil {
  391. t.Fatalf("could not build 'docker-test-createvolumewithsymlink': %v", err)
  392. }
  393. cmd := exec.Command(dockerBinary, "run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", "docker-test-createvolumewithsymlink", "sh", "-c", "mount | grep -q /foo/foo")
  394. exitCode, err := runCommand(cmd)
  395. if err != nil || exitCode != 0 {
  396. t.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
  397. }
  398. var volPath string
  399. cmd = exec.Command(dockerBinary, "inspect", "-f", "{{range .Volumes}}{{.}}{{end}}", "test-createvolumewithsymlink")
  400. volPath, exitCode, err = runCommandWithOutput(cmd)
  401. if err != nil || exitCode != 0 {
  402. t.Fatalf("[inspect] err: %v, exitcode: %d", err, exitCode)
  403. }
  404. cmd = exec.Command(dockerBinary, "rm", "-v", "test-createvolumewithsymlink")
  405. exitCode, err = runCommand(cmd)
  406. if err != nil || exitCode != 0 {
  407. t.Fatalf("[rm] err: %v, exitcode: %d", err, exitCode)
  408. }
  409. f, err := os.Open(volPath)
  410. defer f.Close()
  411. if !os.IsNotExist(err) {
  412. t.Fatalf("[open] (expecting 'file does not exist' error) err: %v, volPath: %s", err, volPath)
  413. }
  414. deleteImages("docker-test-createvolumewithsymlink")
  415. deleteAllContainers()
  416. logDone("run - create volume with symlink")
  417. }
  418. // Tests that a volume path that has a symlink exists in a container mounting it with `--volumes-from`.
  419. func TestVolumesFromSymlinkPath(t *testing.T) {
  420. buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-volumesfromsymlinkpath", "-")
  421. buildCmd.Stdin = strings.NewReader(`FROM busybox
  422. RUN mkdir /baz && ln -s /baz /foo
  423. VOLUME ["/foo/bar"]`)
  424. buildCmd.Dir = workingDirectory
  425. err := buildCmd.Run()
  426. if err != nil {
  427. t.Fatalf("could not build 'docker-test-volumesfromsymlinkpath': %v", err)
  428. }
  429. cmd := exec.Command(dockerBinary, "run", "--name", "test-volumesfromsymlinkpath", "docker-test-volumesfromsymlinkpath")
  430. exitCode, err := runCommand(cmd)
  431. if err != nil || exitCode != 0 {
  432. t.Fatalf("[run] (volume) err: %v, exitcode: %d", err, exitCode)
  433. }
  434. cmd = exec.Command(dockerBinary, "run", "--volumes-from", "test-volumesfromsymlinkpath", "busybox", "sh", "-c", "ls /foo | grep -q bar")
  435. exitCode, err = runCommand(cmd)
  436. if err != nil || exitCode != 0 {
  437. t.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
  438. }
  439. deleteImages("docker-test-volumesfromsymlinkpath")
  440. deleteAllContainers()
  441. logDone("run - volumes-from symlink path")
  442. }
  443. func TestExitCode(t *testing.T) {
  444. cmd := exec.Command(dockerBinary, "run", "busybox", "/bin/sh", "-c", "exit 72")
  445. exit, err := runCommand(cmd)
  446. if err == nil {
  447. t.Fatal("should not have a non nil error")
  448. }
  449. if exit != 72 {
  450. t.Fatalf("expected exit code 72 received %d", exit)
  451. }
  452. deleteAllContainers()
  453. logDone("run - correct exit code")
  454. }
  455. func TestUserDefaultsToRoot(t *testing.T) {
  456. cmd := exec.Command(dockerBinary, "run", "busybox", "id")
  457. out, _, err := runCommandWithOutput(cmd)
  458. if err != nil {
  459. t.Fatal(err, out)
  460. }
  461. if !strings.Contains(out, "uid=0(root) gid=0(root)") {
  462. t.Fatalf("expected root user got %s", out)
  463. }
  464. deleteAllContainers()
  465. logDone("run - default user")
  466. }
  467. func TestUserByName(t *testing.T) {
  468. cmd := exec.Command(dockerBinary, "run", "-u", "root", "busybox", "id")
  469. out, _, err := runCommandWithOutput(cmd)
  470. if err != nil {
  471. t.Fatal(err, out)
  472. }
  473. if !strings.Contains(out, "uid=0(root) gid=0(root)") {
  474. t.Fatalf("expected root user got %s", out)
  475. }
  476. deleteAllContainers()
  477. logDone("run - user by name")
  478. }
  479. func TestUserByID(t *testing.T) {
  480. cmd := exec.Command(dockerBinary, "run", "-u", "1", "busybox", "id")
  481. out, _, err := runCommandWithOutput(cmd)
  482. if err != nil {
  483. t.Fatal(err, out)
  484. }
  485. if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") {
  486. t.Fatalf("expected daemon user got %s", out)
  487. }
  488. deleteAllContainers()
  489. logDone("run - user by id")
  490. }
  491. func TestUserByIDBig(t *testing.T) {
  492. cmd := exec.Command(dockerBinary, "run", "-u", "2147483648", "busybox", "id")
  493. out, _, err := runCommandWithOutput(cmd)
  494. if err == nil {
  495. t.Fatal("No error, but must be.", out)
  496. }
  497. if !strings.Contains(out, "Uids and gids must be in range") {
  498. t.Fatalf("expected error about uids range, got %s", out)
  499. }
  500. deleteAllContainers()
  501. logDone("run - user by id, id too big")
  502. }
  503. func TestUserByIDNegative(t *testing.T) {
  504. cmd := exec.Command(dockerBinary, "run", "-u", "-1", "busybox", "id")
  505. out, _, err := runCommandWithOutput(cmd)
  506. if err == nil {
  507. t.Fatal("No error, but must be.", out)
  508. }
  509. if !strings.Contains(out, "Uids and gids must be in range") {
  510. t.Fatalf("expected error about uids range, got %s", out)
  511. }
  512. deleteAllContainers()
  513. logDone("run - user by id, id negative")
  514. }
  515. func TestUserByIDZero(t *testing.T) {
  516. cmd := exec.Command(dockerBinary, "run", "-u", "0", "busybox", "id")
  517. out, _, err := runCommandWithOutput(cmd)
  518. if err != nil {
  519. t.Fatal(err, out)
  520. }
  521. if !strings.Contains(out, "uid=0(root) gid=0(root) groups=10(wheel)") {
  522. t.Fatalf("expected daemon user got %s", out)
  523. }
  524. deleteAllContainers()
  525. logDone("run - user by id, zero uid")
  526. }
  527. func TestUserNotFound(t *testing.T) {
  528. cmd := exec.Command(dockerBinary, "run", "-u", "notme", "busybox", "id")
  529. _, err := runCommand(cmd)
  530. if err == nil {
  531. t.Fatal("unknown user should cause container to fail")
  532. }
  533. deleteAllContainers()
  534. logDone("run - user not found")
  535. }
  536. func TestRunTwoConcurrentContainers(t *testing.T) {
  537. group := sync.WaitGroup{}
  538. group.Add(2)
  539. for i := 0; i < 2; i++ {
  540. go func() {
  541. defer group.Done()
  542. cmd := exec.Command(dockerBinary, "run", "busybox", "sleep", "2")
  543. if _, err := runCommand(cmd); err != nil {
  544. t.Fatal(err)
  545. }
  546. }()
  547. }
  548. group.Wait()
  549. deleteAllContainers()
  550. logDone("run - two concurrent containers")
  551. }
  552. func TestEnvironment(t *testing.T) {
  553. cmd := exec.Command(dockerBinary, "run", "-h", "testing", "-e=FALSE=true", "-e=TRUE", "-e=TRICKY", "-e=HOME=", "busybox", "env")
  554. cmd.Env = append(os.Environ(),
  555. "TRUE=false",
  556. "TRICKY=tri\ncky\n",
  557. )
  558. out, _, err := runCommandWithOutput(cmd)
  559. if err != nil {
  560. t.Fatal(err, out)
  561. }
  562. actualEnv := strings.Split(out, "\n")
  563. if actualEnv[len(actualEnv)-1] == "" {
  564. actualEnv = actualEnv[:len(actualEnv)-1]
  565. }
  566. sort.Strings(actualEnv)
  567. goodEnv := []string{
  568. "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  569. "HOSTNAME=testing",
  570. "FALSE=true",
  571. "TRUE=false",
  572. "TRICKY=tri",
  573. "cky",
  574. "",
  575. "HOME=/root",
  576. }
  577. sort.Strings(goodEnv)
  578. if len(goodEnv) != len(actualEnv) {
  579. t.Fatalf("Wrong environment: should be %d variables, not: '%s'\n", len(goodEnv), strings.Join(actualEnv, ", "))
  580. }
  581. for i := range goodEnv {
  582. if actualEnv[i] != goodEnv[i] {
  583. t.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
  584. }
  585. }
  586. deleteAllContainers()
  587. logDone("run - verify environment")
  588. }
  589. func TestContainerNetwork(t *testing.T) {
  590. cmd := exec.Command(dockerBinary, "run", "busybox", "ping", "-c", "1", "127.0.0.1")
  591. if _, err := runCommand(cmd); err != nil {
  592. t.Fatal(err)
  593. }
  594. deleteAllContainers()
  595. logDone("run - test container network via ping")
  596. }
  597. // Issue #4681
  598. func TestLoopbackWhenNetworkDisabled(t *testing.T) {
  599. cmd := exec.Command(dockerBinary, "run", "--net=none", "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 loopback when networking disabled")
  605. }
  606. func TestNetHostNotAllowedWithLinks(t *testing.T) {
  607. _, _, err := cmd(t, "run", "--name", "linked", "busybox", "true")
  608. cmd := exec.Command(dockerBinary, "run", "--net=host", "--link", "linked:linked", "busybox", "true")
  609. _, _, err = runCommandWithOutput(cmd)
  610. if err == nil {
  611. t.Fatal("Expected error")
  612. }
  613. deleteAllContainers()
  614. logDone("run - don't allow --net=host to be used with links")
  615. }
  616. func TestLoopbackOnlyExistsWhenNetworkingDisabled(t *testing.T) {
  617. cmd := exec.Command(dockerBinary, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up")
  618. out, _, err := runCommandWithOutput(cmd)
  619. if err != nil {
  620. t.Fatal(err, out)
  621. }
  622. var (
  623. count = 0
  624. parts = strings.Split(out, "\n")
  625. )
  626. for _, l := range parts {
  627. if l != "" {
  628. count++
  629. }
  630. }
  631. if count != 1 {
  632. t.Fatalf("Wrong interface count in container %d", count)
  633. }
  634. if !strings.HasPrefix(out, "1: lo") {
  635. t.Fatalf("Wrong interface in test container: expected [1: lo], got %s", out)
  636. }
  637. deleteAllContainers()
  638. logDone("run - test loopback only exists when networking disabled")
  639. }
  640. func TestPrivilegedCanMknod(t *testing.T) {
  641. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  642. out, _, err := runCommandWithOutput(cmd)
  643. if err != nil {
  644. t.Fatal(err)
  645. }
  646. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  647. t.Fatalf("expected output ok received %s", actual)
  648. }
  649. deleteAllContainers()
  650. logDone("run - test privileged can mknod")
  651. }
  652. func TestUnPrivilegedCanMknod(t *testing.T) {
  653. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  654. out, _, err := runCommandWithOutput(cmd)
  655. if err != nil {
  656. t.Fatal(err)
  657. }
  658. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  659. t.Fatalf("expected output ok received %s", actual)
  660. }
  661. deleteAllContainers()
  662. logDone("run - test un-privileged can mknod")
  663. }
  664. func TestCapDropInvalid(t *testing.T) {
  665. cmd := exec.Command(dockerBinary, "run", "--cap-drop=CHPASS", "busybox", "ls")
  666. out, _, err := runCommandWithOutput(cmd)
  667. if err == nil {
  668. t.Fatal(err, out)
  669. }
  670. logDone("run - test --cap-drop=CHPASS invalid")
  671. }
  672. func TestCapDropCannotMknod(t *testing.T) {
  673. cmd := exec.Command(dockerBinary, "run", "--cap-drop=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  674. out, _, err := runCommandWithOutput(cmd)
  675. if err == nil {
  676. t.Fatal(err, out)
  677. }
  678. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  679. t.Fatalf("expected output not ok received %s", actual)
  680. }
  681. deleteAllContainers()
  682. logDone("run - test --cap-drop=MKNOD cannot mknod")
  683. }
  684. func TestCapDropCannotMknodLowerCase(t *testing.T) {
  685. cmd := exec.Command(dockerBinary, "run", "--cap-drop=mknod", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  686. out, _, err := runCommandWithOutput(cmd)
  687. if err == nil {
  688. t.Fatal(err, out)
  689. }
  690. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  691. t.Fatalf("expected output not ok received %s", actual)
  692. }
  693. deleteAllContainers()
  694. logDone("run - test --cap-drop=mknod cannot mknod lowercase")
  695. }
  696. func TestCapDropALLCannotMknod(t *testing.T) {
  697. cmd := exec.Command(dockerBinary, "run", "--cap-drop=ALL", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  698. out, _, err := runCommandWithOutput(cmd)
  699. if err == nil {
  700. t.Fatal(err, out)
  701. }
  702. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  703. t.Fatalf("expected output not ok received %s", actual)
  704. }
  705. deleteAllContainers()
  706. logDone("run - test --cap-drop=ALL cannot mknod")
  707. }
  708. func TestCapDropALLAddMknodCannotMknod(t *testing.T) {
  709. cmd := exec.Command(dockerBinary, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  710. out, _, err := runCommandWithOutput(cmd)
  711. if err != nil {
  712. t.Fatal(err, out)
  713. }
  714. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  715. t.Fatalf("expected output ok received %s", actual)
  716. }
  717. deleteAllContainers()
  718. logDone("run - test --cap-drop=ALL --cap-add=MKNOD can mknod")
  719. }
  720. func TestCapAddInvalid(t *testing.T) {
  721. cmd := exec.Command(dockerBinary, "run", "--cap-add=CHPASS", "busybox", "ls")
  722. out, _, err := runCommandWithOutput(cmd)
  723. if err == nil {
  724. t.Fatal(err, out)
  725. }
  726. logDone("run - test --cap-add=CHPASS invalid")
  727. }
  728. func TestCapAddCanDownInterface(t *testing.T) {
  729. cmd := exec.Command(dockerBinary, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  730. out, _, err := runCommandWithOutput(cmd)
  731. if err != nil {
  732. t.Fatal(err, out)
  733. }
  734. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  735. t.Fatalf("expected output ok received %s", actual)
  736. }
  737. deleteAllContainers()
  738. logDone("run - test --cap-add=NET_ADMIN can set eth0 down")
  739. }
  740. func TestCapAddALLCanDownInterface(t *testing.T) {
  741. cmd := exec.Command(dockerBinary, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  742. out, _, err := runCommandWithOutput(cmd)
  743. if err != nil {
  744. t.Fatal(err, out)
  745. }
  746. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  747. t.Fatalf("expected output ok received %s", actual)
  748. }
  749. deleteAllContainers()
  750. logDone("run - test --cap-add=ALL can set eth0 down")
  751. }
  752. func TestCapAddALLDropNetAdminCanDownInterface(t *testing.T) {
  753. cmd := exec.Command(dockerBinary, "run", "--cap-add=ALL", "--cap-drop=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  754. out, _, err := runCommandWithOutput(cmd)
  755. if err == nil {
  756. t.Fatal(err, out)
  757. }
  758. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  759. t.Fatalf("expected output not ok received %s", actual)
  760. }
  761. deleteAllContainers()
  762. logDone("run - test --cap-add=ALL --cap-drop=NET_ADMIN cannot set eth0 down")
  763. }
  764. func TestPrivilegedCanMount(t *testing.T) {
  765. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
  766. out, _, err := runCommandWithOutput(cmd)
  767. if err != nil {
  768. t.Fatal(err)
  769. }
  770. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  771. t.Fatalf("expected output ok received %s", actual)
  772. }
  773. deleteAllContainers()
  774. logDone("run - test privileged can mount")
  775. }
  776. func TestUnPrivilegedCannotMount(t *testing.T) {
  777. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
  778. out, _, err := runCommandWithOutput(cmd)
  779. if err == nil {
  780. t.Fatal(err, out)
  781. }
  782. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  783. t.Fatalf("expected output not ok received %s", actual)
  784. }
  785. deleteAllContainers()
  786. logDone("run - test un-privileged cannot mount")
  787. }
  788. func TestSysNotWritableInNonPrivilegedContainers(t *testing.T) {
  789. cmd := exec.Command(dockerBinary, "run", "busybox", "touch", "/sys/kernel/profiling")
  790. if code, err := runCommand(cmd); err == nil || code == 0 {
  791. t.Fatal("sys should not be writable in a non privileged container")
  792. }
  793. deleteAllContainers()
  794. logDone("run - sys not writable in non privileged container")
  795. }
  796. func TestSysWritableInPrivilegedContainers(t *testing.T) {
  797. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "touch", "/sys/kernel/profiling")
  798. if code, err := runCommand(cmd); err != nil || code != 0 {
  799. t.Fatalf("sys should be writable in privileged container")
  800. }
  801. deleteAllContainers()
  802. logDone("run - sys writable in privileged container")
  803. }
  804. func TestProcNotWritableInNonPrivilegedContainers(t *testing.T) {
  805. cmd := exec.Command(dockerBinary, "run", "busybox", "touch", "/proc/sysrq-trigger")
  806. if code, err := runCommand(cmd); err == nil || code == 0 {
  807. t.Fatal("proc should not be writable in a non privileged container")
  808. }
  809. deleteAllContainers()
  810. logDone("run - proc not writable in non privileged container")
  811. }
  812. func TestProcWritableInPrivilegedContainers(t *testing.T) {
  813. cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "touch", "/proc/sysrq-trigger")
  814. if code, err := runCommand(cmd); err != nil || code != 0 {
  815. t.Fatalf("proc should be writable in privileged container")
  816. }
  817. deleteAllContainers()
  818. logDone("run - proc writable in privileged container")
  819. }
  820. func TestRunWithCpuset(t *testing.T) {
  821. cmd := exec.Command(dockerBinary, "run", "--cpuset", "0", "busybox", "true")
  822. if code, err := runCommand(cmd); err != nil || code != 0 {
  823. t.Fatalf("container should run successfuly with cpuset of 0: %s", err)
  824. }
  825. deleteAllContainers()
  826. logDone("run - cpuset 0")
  827. }
  828. func TestDeviceNumbers(t *testing.T) {
  829. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "ls -l /dev/null")
  830. out, _, err := runCommandWithOutput(cmd)
  831. if err != nil {
  832. t.Fatal(err, out)
  833. }
  834. deviceLineFields := strings.Fields(out)
  835. deviceLineFields[6] = ""
  836. deviceLineFields[7] = ""
  837. deviceLineFields[8] = ""
  838. expected := []string{"crw-rw-rw-", "1", "root", "root", "1,", "3", "", "", "", "/dev/null"}
  839. if !(reflect.DeepEqual(deviceLineFields, expected)) {
  840. t.Fatalf("expected output\ncrw-rw-rw- 1 root root 1, 3 May 24 13:29 /dev/null\n received\n %s\n", out)
  841. }
  842. deleteAllContainers()
  843. logDone("run - test device numbers")
  844. }
  845. func TestThatCharacterDevicesActLikeCharacterDevices(t *testing.T) {
  846. cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero")
  847. out, _, err := runCommandWithOutput(cmd)
  848. if err != nil {
  849. t.Fatal(err, out)
  850. }
  851. if actual := strings.Trim(out, "\r\n"); actual[0] == '0' {
  852. t.Fatalf("expected a new file called /zero to be create that is greater than 0 bytes long, but du says: %s", actual)
  853. }
  854. deleteAllContainers()
  855. logDone("run - test that character devices work.")
  856. }
  857. func TestRunUnprivilegedWithChroot(t *testing.T) {
  858. cmd := exec.Command(dockerBinary, "run", "busybox", "chroot", "/", "true")
  859. if _, err := runCommand(cmd); err != nil {
  860. t.Fatal(err)
  861. }
  862. deleteAllContainers()
  863. logDone("run - unprivileged with chroot")
  864. }
  865. func TestAddingOptionalDevices(t *testing.T) {
  866. cmd := exec.Command(dockerBinary, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo")
  867. out, _, err := runCommandWithOutput(cmd)
  868. if err != nil {
  869. t.Fatal(err, out)
  870. }
  871. if actual := strings.Trim(out, "\r\n"); actual != "/dev/nulo" {
  872. t.Fatalf("expected output /dev/nulo, received %s", actual)
  873. }
  874. deleteAllContainers()
  875. logDone("run - test --device argument")
  876. }
  877. func TestModeHostname(t *testing.T) {
  878. cmd := exec.Command(dockerBinary, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname")
  879. out, _, err := runCommandWithOutput(cmd)
  880. if err != nil {
  881. t.Fatal(err, out)
  882. }
  883. if actual := strings.Trim(out, "\r\n"); actual != "testhostname" {
  884. t.Fatalf("expected 'testhostname', but says: '%s'", actual)
  885. }
  886. cmd = exec.Command(dockerBinary, "run", "--net=host", "busybox", "cat", "/etc/hostname")
  887. out, _, err = runCommandWithOutput(cmd)
  888. if err != nil {
  889. t.Fatal(err, out)
  890. }
  891. hostname, err := os.Hostname()
  892. if err != nil {
  893. t.Fatal(err)
  894. }
  895. if actual := strings.Trim(out, "\r\n"); actual != hostname {
  896. t.Fatalf("expected '%s', but says: '%s'", hostname, actual)
  897. }
  898. deleteAllContainers()
  899. logDone("run - hostname and several network modes")
  900. }
  901. func TestRootWorkdir(t *testing.T) {
  902. s, _, err := cmd(t, "run", "--workdir", "/", "busybox", "pwd")
  903. if err != nil {
  904. t.Fatal(s, err)
  905. }
  906. if s != "/\n" {
  907. t.Fatalf("pwd returned '%s' (expected /\\n)", s)
  908. }
  909. deleteAllContainers()
  910. logDone("run - workdir /")
  911. }
  912. func TestAllowBindMountingRoot(t *testing.T) {
  913. s, _, err := cmd(t, "run", "-v", "/:/host", "busybox", "ls", "/host")
  914. if err != nil {
  915. t.Fatal(s, err)
  916. }
  917. deleteAllContainers()
  918. logDone("run - bind mount / as volume")
  919. }
  920. func TestDisallowBindMountingRootToRoot(t *testing.T) {
  921. cmd := exec.Command(dockerBinary, "run", "-v", "/:/", "busybox", "ls", "/host")
  922. out, _, err := runCommandWithOutput(cmd)
  923. if err == nil {
  924. t.Fatal(out, err)
  925. }
  926. deleteAllContainers()
  927. logDone("run - bind mount /:/ as volume should fail")
  928. }
  929. // Test recursive bind mount works by default
  930. func TestDockerRunWithVolumesIsRecursive(t *testing.T) {
  931. tmpDir, err := ioutil.TempDir("", "docker_recursive_mount_test")
  932. if err != nil {
  933. t.Fatal(err)
  934. }
  935. defer os.RemoveAll(tmpDir)
  936. // Create a temporary tmpfs mount.
  937. tmpfsDir := filepath.Join(tmpDir, "tmpfs")
  938. if err := os.MkdirAll(tmpfsDir, 0777); err != nil {
  939. t.Fatalf("failed to mkdir at %s - %s", tmpfsDir, err)
  940. }
  941. if err := mount.Mount("tmpfs", tmpfsDir, "tmpfs", ""); err != nil {
  942. t.Fatalf("failed to create a tmpfs mount at %s - %s", tmpfsDir, err)
  943. }
  944. f, err := ioutil.TempFile(tmpfsDir, "touch-me")
  945. if err != nil {
  946. t.Fatal(err)
  947. }
  948. defer f.Close()
  949. runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox:latest", "ls", "/tmp/tmpfs")
  950. out, stderr, exitCode, err := runCommandWithStdoutStderr(runCmd)
  951. if err != nil && exitCode != 0 {
  952. t.Fatal(out, stderr, err)
  953. }
  954. if !strings.Contains(out, filepath.Base(f.Name())) {
  955. t.Fatal("Recursive bind mount test failed. Expected file not found")
  956. }
  957. deleteAllContainers()
  958. logDone("run - volumes are bind mounted recursively")
  959. }
  960. func TestDnsDefaultOptions(t *testing.T) {
  961. cmd := exec.Command(dockerBinary, "run", "busybox", "cat", "/etc/resolv.conf")
  962. actual, _, err := runCommandWithOutput(cmd)
  963. if err != nil {
  964. t.Fatal(err, actual)
  965. }
  966. resolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  967. if os.IsNotExist(err) {
  968. t.Fatalf("/etc/resolv.conf does not exist")
  969. }
  970. if actual != string(resolvConf) {
  971. t.Fatalf("expected resolv.conf is not the same of actual")
  972. }
  973. deleteAllContainers()
  974. logDone("run - dns default options")
  975. }
  976. func TestDnsOptions(t *testing.T) {
  977. cmd := exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
  978. out, _, err := runCommandWithOutput(cmd)
  979. if err != nil {
  980. t.Fatal(err, out)
  981. }
  982. actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1)
  983. if actual != "nameserver 127.0.0.1 search mydomain" {
  984. t.Fatalf("expected 'nameserver 127.0.0.1 search mydomain', but says: '%s'", actual)
  985. }
  986. cmd = exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "--dns-search=.", "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(strings.Trim(out, "\r\n"), " "), "\n", " ", -1)
  992. if actual != "nameserver 127.0.0.1" {
  993. t.Fatalf("expected 'nameserver 127.0.0.1', but says: '%s'", actual)
  994. }
  995. logDone("run - dns options")
  996. }
  997. func TestDnsOptionsBasedOnHostResolvConf(t *testing.T) {
  998. resolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  999. if os.IsNotExist(err) {
  1000. t.Fatalf("/etc/resolv.conf does not exist")
  1001. }
  1002. hostNamservers := resolvconf.GetNameservers(resolvConf)
  1003. hostSearch := resolvconf.GetSearchDomains(resolvConf)
  1004. cmd := exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf")
  1005. out, _, err := runCommandWithOutput(cmd)
  1006. if err != nil {
  1007. t.Fatal(err, out)
  1008. }
  1009. if actualNameservers := resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "127.0.0.1" {
  1010. t.Fatalf("expected '127.0.0.1', but says: '%s'", string(actualNameservers[0]))
  1011. }
  1012. actualSearch := resolvconf.GetSearchDomains([]byte(out))
  1013. if len(actualSearch) != len(hostSearch) {
  1014. t.Fatalf("expected '%s' search domain(s), but it has: '%s'", len(hostSearch), len(actualSearch))
  1015. }
  1016. for i := range actualSearch {
  1017. if actualSearch[i] != hostSearch[i] {
  1018. t.Fatalf("expected '%s' domain, but says: '%s'", actualSearch[i], hostSearch[i])
  1019. }
  1020. }
  1021. cmd = exec.Command(dockerBinary, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
  1022. out, _, err = runCommandWithOutput(cmd)
  1023. if err != nil {
  1024. t.Fatal(err, out)
  1025. }
  1026. actualNameservers := resolvconf.GetNameservers([]byte(out))
  1027. if len(actualNameservers) != len(hostNamservers) {
  1028. t.Fatalf("expected '%s' nameserver(s), but it has: '%s'", len(hostNamservers), len(actualNameservers))
  1029. }
  1030. for i := range actualNameservers {
  1031. if actualNameservers[i] != hostNamservers[i] {
  1032. t.Fatalf("expected '%s' nameserver, but says: '%s'", actualNameservers[i], hostNamservers[i])
  1033. }
  1034. }
  1035. if actualSearch = resolvconf.GetSearchDomains([]byte(out)); string(actualSearch[0]) != "mydomain" {
  1036. t.Fatalf("expected 'mydomain', but says: '%s'", string(actualSearch[0]))
  1037. }
  1038. deleteAllContainers()
  1039. logDone("run - dns options based on host resolv.conf")
  1040. }
  1041. // Regression test for #6983
  1042. func TestAttachStdErrOnlyTTYMode(t *testing.T) {
  1043. cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stderr", "busybox", "true")
  1044. exitCode, err := runCommand(cmd)
  1045. if err != nil {
  1046. t.Fatal(err)
  1047. } else if exitCode != 0 {
  1048. t.Fatalf("Container should have exited with error code 0")
  1049. }
  1050. deleteAllContainers()
  1051. logDone("run - Attach stderr only with -t")
  1052. }
  1053. // Regression test for #6983
  1054. func TestAttachStdOutOnlyTTYMode(t *testing.T) {
  1055. cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stdout", "busybox", "true")
  1056. exitCode, err := runCommand(cmd)
  1057. if err != nil {
  1058. t.Fatal(err)
  1059. } else if exitCode != 0 {
  1060. t.Fatalf("Container should have exited with error code 0")
  1061. }
  1062. deleteAllContainers()
  1063. logDone("run - Attach stdout only with -t")
  1064. }
  1065. // Regression test for #6983
  1066. func TestAttachStdOutAndErrTTYMode(t *testing.T) {
  1067. cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true")
  1068. exitCode, err := runCommand(cmd)
  1069. if err != nil {
  1070. t.Fatal(err)
  1071. } else if exitCode != 0 {
  1072. t.Fatalf("Container should have exited with error code 0")
  1073. }
  1074. deleteAllContainers()
  1075. logDone("run - Attach stderr and stdout with -t")
  1076. }
  1077. func TestState(t *testing.T) {
  1078. defer deleteAllContainers()
  1079. cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
  1080. out, _, err := runCommandWithOutput(cmd)
  1081. if err != nil {
  1082. t.Fatal(err, out)
  1083. }
  1084. id := strings.TrimSpace(out)
  1085. state, err := inspectField(id, "State.Running")
  1086. if err != nil {
  1087. t.Fatal(err)
  1088. }
  1089. if state != "true" {
  1090. t.Fatal("Container state is 'not running'")
  1091. }
  1092. pid1, err := inspectField(id, "State.Pid")
  1093. if err != nil {
  1094. t.Fatal(err)
  1095. }
  1096. if pid1 == "0" {
  1097. t.Fatal("Container state Pid 0")
  1098. }
  1099. cmd = exec.Command(dockerBinary, "stop", id)
  1100. out, _, err = runCommandWithOutput(cmd)
  1101. if err != nil {
  1102. t.Fatal(err, out)
  1103. }
  1104. state, err = inspectField(id, "State.Running")
  1105. if err != nil {
  1106. t.Fatal(err)
  1107. }
  1108. if state != "false" {
  1109. t.Fatal("Container state is 'running'")
  1110. }
  1111. pid2, err := inspectField(id, "State.Pid")
  1112. if err != nil {
  1113. t.Fatal(err)
  1114. }
  1115. if pid2 == pid1 {
  1116. t.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1117. }
  1118. cmd = exec.Command(dockerBinary, "start", id)
  1119. out, _, err = runCommandWithOutput(cmd)
  1120. if err != nil {
  1121. t.Fatal(err, out)
  1122. }
  1123. state, err = inspectField(id, "State.Running")
  1124. if err != nil {
  1125. t.Fatal(err)
  1126. }
  1127. if state != "true" {
  1128. t.Fatal("Container state is 'not running'")
  1129. }
  1130. pid3, err := inspectField(id, "State.Pid")
  1131. if err != nil {
  1132. t.Fatal(err)
  1133. }
  1134. if pid3 == pid1 {
  1135. t.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1136. }
  1137. logDone("run - test container state.")
  1138. }
  1139. // Test for #1737
  1140. func TestCopyVolumeUidGid(t *testing.T) {
  1141. name := "testrunvolumesuidgid"
  1142. defer deleteImages(name)
  1143. defer deleteAllContainers()
  1144. _, err := buildImage(name,
  1145. `FROM busybox
  1146. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1147. RUN echo 'dockerio:x:1001:' >> /etc/group
  1148. RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`,
  1149. true)
  1150. if err != nil {
  1151. t.Fatal(err)
  1152. }
  1153. // Test that the uid and gid is copied from the image to the volume
  1154. cmd := exec.Command(dockerBinary, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'")
  1155. out, _, err := runCommandWithOutput(cmd)
  1156. if err != nil {
  1157. t.Fatal(err, out)
  1158. }
  1159. out = strings.TrimSpace(out)
  1160. if out != "dockerio:dockerio" {
  1161. t.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out)
  1162. }
  1163. logDone("run - copy uid/gid for volume")
  1164. }
  1165. // Test for #1582
  1166. func TestCopyVolumeContent(t *testing.T) {
  1167. name := "testruncopyvolumecontent"
  1168. defer deleteImages(name)
  1169. defer deleteAllContainers()
  1170. _, err := buildImage(name,
  1171. `FROM busybox
  1172. RUN mkdir -p /hello/local && echo hello > /hello/local/world`,
  1173. true)
  1174. if err != nil {
  1175. t.Fatal(err)
  1176. }
  1177. // Test that the content is copied from the image to the volume
  1178. cmd := exec.Command(dockerBinary, "run", "--rm", "-v", "/hello", name, "sh", "-c", "find", "/hello")
  1179. out, _, err := runCommandWithOutput(cmd)
  1180. if err != nil {
  1181. t.Fatal(err, out)
  1182. }
  1183. if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) {
  1184. t.Fatal("Container failed to transfer content to volume")
  1185. }
  1186. logDone("run - copy volume content")
  1187. }
  1188. func TestRunCleanupCmdOnEntrypoint(t *testing.T) {
  1189. name := "testrunmdcleanuponentrypoint"
  1190. defer deleteImages(name)
  1191. defer deleteAllContainers()
  1192. if _, err := buildImage(name,
  1193. `FROM busybox
  1194. ENTRYPOINT ["echo"]
  1195. CMD ["testingpoint"]`,
  1196. true); err != nil {
  1197. t.Fatal(err)
  1198. }
  1199. runCmd := exec.Command(dockerBinary, "run", "--entrypoint", "whoami", name)
  1200. out, exit, err := runCommandWithOutput(runCmd)
  1201. if err != nil {
  1202. t.Fatalf("Error: %v, out: %q", err, out)
  1203. }
  1204. if exit != 0 {
  1205. t.Fatalf("expected exit code 0 received %d, out: %q", exit, out)
  1206. }
  1207. out = strings.TrimSpace(out)
  1208. if out != "root" {
  1209. t.Fatalf("Expected output root, got %q", out)
  1210. }
  1211. logDone("run - cleanup cmd on --entrypoint")
  1212. }
  1213. // TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected
  1214. func TestRunWorkdirExistsAndIsFile(t *testing.T) {
  1215. defer deleteAllContainers()
  1216. runCmd := exec.Command(dockerBinary, "run", "-w", "/bin/cat", "busybox")
  1217. out, exit, err := runCommandWithOutput(runCmd)
  1218. if !(err != nil && exit == 1 && strings.Contains(out, "Cannot mkdir: /bin/cat is not a directory")) {
  1219. t.Fatalf("Docker must complains about making dir, but we got out: %s, exit: %d, err: %s", out, exit, err)
  1220. }
  1221. logDone("run - error on existing file for workdir")
  1222. }
  1223. func TestRunExitOnStdinClose(t *testing.T) {
  1224. name := "testrunexitonstdinclose"
  1225. defer deleteAllContainers()
  1226. runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", "/bin/cat")
  1227. stdin, err := runCmd.StdinPipe()
  1228. if err != nil {
  1229. t.Fatal(err)
  1230. }
  1231. stdout, err := runCmd.StdoutPipe()
  1232. if err != nil {
  1233. t.Fatal(err)
  1234. }
  1235. if err := runCmd.Start(); err != nil {
  1236. t.Fatal(err)
  1237. }
  1238. if _, err := stdin.Write([]byte("hello\n")); err != nil {
  1239. t.Fatal(err)
  1240. }
  1241. r := bufio.NewReader(stdout)
  1242. line, err := r.ReadString('\n')
  1243. if err != nil {
  1244. t.Fatal(err)
  1245. }
  1246. line = strings.TrimSpace(line)
  1247. if line != "hello" {
  1248. t.Fatalf("Output should be 'hello', got '%q'", line)
  1249. }
  1250. if err := stdin.Close(); err != nil {
  1251. t.Fatal(err)
  1252. }
  1253. finish := make(chan struct{})
  1254. go func() {
  1255. if err := runCmd.Wait(); err != nil {
  1256. t.Fatal(err)
  1257. }
  1258. close(finish)
  1259. }()
  1260. select {
  1261. case <-finish:
  1262. case <-time.After(1 * time.Second):
  1263. t.Fatal("docker run failed to exit on stdin close")
  1264. }
  1265. state, err := inspectField(name, "State.Running")
  1266. if err != nil {
  1267. t.Fatal(err)
  1268. }
  1269. if state != "false" {
  1270. t.Fatal("Container must be stopped after stdin closing")
  1271. }
  1272. logDone("run - exit on stdin closing")
  1273. }
  1274. // Test for #2267
  1275. func TestWriteHostsFileAndNotCommit(t *testing.T) {
  1276. name := "writehosts"
  1277. cmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hosts && cat /etc/hosts")
  1278. out, _, err := runCommandWithOutput(cmd)
  1279. if err != nil {
  1280. t.Fatal(err, out)
  1281. }
  1282. if !strings.Contains(out, "test2267") {
  1283. t.Fatal("/etc/hosts should contain 'test2267'")
  1284. }
  1285. cmd = exec.Command(dockerBinary, "diff", name)
  1286. if err != nil {
  1287. t.Fatal(err, out)
  1288. }
  1289. out, _, err = runCommandWithOutput(cmd)
  1290. if err != nil {
  1291. t.Fatal(err, out)
  1292. }
  1293. if len(strings.Trim(out, "\r\n")) != 0 {
  1294. t.Fatal("diff should be empty")
  1295. }
  1296. logDone("run - write to /etc/hosts and not commited")
  1297. }
  1298. // Test for #2267
  1299. func TestWriteHostnameFileAndNotCommit(t *testing.T) {
  1300. name := "writehostname"
  1301. cmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hostname && cat /etc/hostname")
  1302. out, _, err := runCommandWithOutput(cmd)
  1303. if err != nil {
  1304. t.Fatal(err, out)
  1305. }
  1306. if !strings.Contains(out, "test2267") {
  1307. t.Fatal("/etc/hostname should contain 'test2267'")
  1308. }
  1309. cmd = exec.Command(dockerBinary, "diff", name)
  1310. if err != nil {
  1311. t.Fatal(err, out)
  1312. }
  1313. out, _, err = runCommandWithOutput(cmd)
  1314. if err != nil {
  1315. t.Fatal(err, out)
  1316. }
  1317. if len(strings.Trim(out, "\r\n")) != 0 {
  1318. t.Fatal("diff should be empty")
  1319. }
  1320. logDone("run - write to /etc/hostname and not commited")
  1321. }
  1322. // Test for #2267
  1323. func TestWriteResolvFileAndNotCommit(t *testing.T) {
  1324. name := "writeresolv"
  1325. cmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/resolv.conf && cat /etc/resolv.conf")
  1326. out, _, err := runCommandWithOutput(cmd)
  1327. if err != nil {
  1328. t.Fatal(err, out)
  1329. }
  1330. if !strings.Contains(out, "test2267") {
  1331. t.Fatal("/etc/resolv.conf should contain 'test2267'")
  1332. }
  1333. cmd = exec.Command(dockerBinary, "diff", name)
  1334. if err != nil {
  1335. t.Fatal(err, out)
  1336. }
  1337. out, _, err = runCommandWithOutput(cmd)
  1338. if err != nil {
  1339. t.Fatal(err, out)
  1340. }
  1341. if len(strings.Trim(out, "\r\n")) != 0 {
  1342. t.Fatal("diff should be empty")
  1343. }
  1344. logDone("run - write to /etc/resolv.conf and not commited")
  1345. }
  1346. func TestRunWithBadDevice(t *testing.T) {
  1347. name := "baddevice"
  1348. cmd := exec.Command(dockerBinary, "run", "--name", name, "--device", "/etc", "busybox", "true")
  1349. out, _, err := runCommandWithOutput(cmd)
  1350. if err == nil {
  1351. t.Fatal("Run should fail with bad device")
  1352. }
  1353. expected := `"/etc": not a device node`
  1354. if !strings.Contains(out, expected) {
  1355. t.Fatalf("Output should contain %q, actual out: %q", expected, out)
  1356. }
  1357. logDone("run - error with bad device")
  1358. }
  1359. func TestEntrypoint(t *testing.T) {
  1360. name := "entrypoint"
  1361. cmd := exec.Command(dockerBinary, "run", "--name", name, "--entrypoint", "/bin/echo", "busybox", "-n", "foobar")
  1362. out, _, err := runCommandWithOutput(cmd)
  1363. if err != nil {
  1364. t.Fatal(err, out)
  1365. }
  1366. expected := "foobar"
  1367. if out != expected {
  1368. t.Fatalf("Output should be %q, actual out: %q", expected, out)
  1369. }
  1370. logDone("run - entrypoint")
  1371. }
  1372. func TestBindMounts(t *testing.T) {
  1373. tmpDir, err := ioutil.TempDir("", "docker-test-container")
  1374. if err != nil {
  1375. t.Fatal(err)
  1376. }
  1377. defer os.RemoveAll(tmpDir)
  1378. writeFile(path.Join(tmpDir, "touch-me"), "", t)
  1379. // Test reading from a read-only bind mount
  1380. cmd := exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox", "ls", "/tmp")
  1381. out, _, err := runCommandWithOutput(cmd)
  1382. if err != nil {
  1383. t.Fatal(err, out)
  1384. }
  1385. if !strings.Contains(out, "touch-me") {
  1386. t.Fatal("Container failed to read from bind mount")
  1387. }
  1388. // test writing to bind mount
  1389. cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla")
  1390. out, _, err = runCommandWithOutput(cmd)
  1391. if err != nil {
  1392. t.Fatal(err, out)
  1393. }
  1394. readFile(path.Join(tmpDir, "holla"), t) // Will fail if the file doesn't exist
  1395. // test mounting to an illegal destination directory
  1396. cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:.", tmpDir), "busybox", "ls", ".")
  1397. _, err = runCommand(cmd)
  1398. if err == nil {
  1399. t.Fatal("Container bind mounted illegal directory")
  1400. }
  1401. // test mount a file
  1402. cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla")
  1403. _, err = runCommand(cmd)
  1404. if err != nil {
  1405. t.Fatal(err, out)
  1406. }
  1407. content := readFile(path.Join(tmpDir, "holla"), t) // Will fail if the file doesn't exist
  1408. expected := "yotta"
  1409. if content != expected {
  1410. t.Fatalf("Output should be %q, actual out: %q", expected, content)
  1411. }
  1412. logDone("run - bind mounts")
  1413. }
  1414. func TestMutableNetworkFiles(t *testing.T) {
  1415. defer deleteAllContainers()
  1416. for _, fn := range []string{"resolv.conf", "hosts"} {
  1417. deleteAllContainers()
  1418. 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)))
  1419. if err != nil {
  1420. t.Fatal(err, out)
  1421. }
  1422. time.Sleep(1 * time.Second)
  1423. contID := strings.TrimSpace(out)
  1424. f, err := os.Open(filepath.Join("/var/lib/docker/containers", contID, fn))
  1425. if err != nil {
  1426. t.Fatal(err)
  1427. }
  1428. content, err := ioutil.ReadAll(f)
  1429. f.Close()
  1430. if strings.TrimSpace(string(content)) != "success" {
  1431. t.Fatal("Content was not what was modified in the container", string(content))
  1432. }
  1433. 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)))
  1434. if err != nil {
  1435. t.Fatal(err)
  1436. }
  1437. contID = strings.TrimSpace(out)
  1438. resolvConfPath := filepath.Join("/var/lib/docker/containers", contID, fn)
  1439. f, err = os.OpenFile(resolvConfPath, os.O_WRONLY|os.O_SYNC|os.O_APPEND, 0644)
  1440. if err != nil {
  1441. t.Fatal(err)
  1442. }
  1443. if _, err := f.Seek(0, 0); err != nil {
  1444. f.Close()
  1445. t.Fatal(err)
  1446. }
  1447. if err := f.Truncate(0); err != nil {
  1448. f.Close()
  1449. t.Fatal(err)
  1450. }
  1451. if _, err := f.Write([]byte("success2\n")); err != nil {
  1452. f.Close()
  1453. t.Fatal(err)
  1454. }
  1455. f.Close()
  1456. time.Sleep(2 * time.Second) // don't race sleep
  1457. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "logs", "c2"))
  1458. if err != nil {
  1459. t.Fatal(err)
  1460. }
  1461. lines := strings.Split(out, "\n")
  1462. if strings.TrimSpace(lines[len(lines)-2]) != "success2" {
  1463. t.Fatalf("Did not find the correct output in /etc/%s: %s %#v", fn, out, lines)
  1464. }
  1465. }
  1466. }
  1467. func TestHostsLinkedContainerUpdate(t *testing.T) {
  1468. deleteAllContainers()
  1469. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", "c1", "busybox", "sh", "-c", "while true; do sleep 1; done"))
  1470. if err != nil {
  1471. t.Fatal(err, out)
  1472. }
  1473. // TODO fix docker cp and /etc/hosts
  1474. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--link", "c1:c1", "--name", "c2", "busybox", "sh", "-c", "while true;do sleep 1; done"))
  1475. if err != nil {
  1476. t.Fatal(err, out)
  1477. }
  1478. contID := strings.TrimSpace(out)
  1479. f, err := os.Open(filepath.Join("/var/lib/docker/containers", contID, "hosts"))
  1480. if err != nil {
  1481. t.Fatal(err)
  1482. }
  1483. originalContent, err := ioutil.ReadAll(f)
  1484. f.Close()
  1485. if err != nil {
  1486. t.Fatal(err)
  1487. }
  1488. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "restart", "-t", "0", "c1"))
  1489. if err != nil {
  1490. t.Fatal(err, out)
  1491. }
  1492. f, err = os.Open(filepath.Join("/var/lib/docker/containers", contID, "hosts"))
  1493. if err != nil {
  1494. t.Fatal(err)
  1495. }
  1496. newContent, err := ioutil.ReadAll(f)
  1497. f.Close()
  1498. if err != nil {
  1499. t.Fatal(err)
  1500. }
  1501. if strings.TrimSpace(string(originalContent)) == strings.TrimSpace(string(newContent)) {
  1502. t.Fatalf("expected /etc/hosts to be updated, but wasn't")
  1503. }
  1504. deleteAllContainers()
  1505. logDone("run - /etc/hosts updated in parent when restart")
  1506. }
  1507. // Ensure that CIDFile gets deleted if it's empty
  1508. // Perform this test by making `docker run` fail
  1509. func TestRunCidFileCleanupIfEmpty(t *testing.T) {
  1510. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1511. if err != nil {
  1512. t.Fatal(err)
  1513. }
  1514. defer os.RemoveAll(tmpDir)
  1515. tmpCidFile := path.Join(tmpDir, "cid")
  1516. cmd := exec.Command(dockerBinary, "run", "--cidfile", tmpCidFile, "scratch")
  1517. out, _, err := runCommandWithOutput(cmd)
  1518. t.Log(out)
  1519. if err == nil {
  1520. t.Fatal("Run without command must fail")
  1521. }
  1522. if _, err := os.Stat(tmpCidFile); err == nil {
  1523. t.Fatalf("empty CIDFile '%s' should've been deleted", tmpCidFile)
  1524. }
  1525. deleteAllContainers()
  1526. logDone("run - cleanup empty cidfile on fail")
  1527. }
  1528. // #2098 - Docker cidFiles only contain short version of the containerId
  1529. //sudo docker run --cidfile /tmp/docker_test.cid ubuntu echo "test"
  1530. // TestRunCidFile tests that run --cidfile returns the longid
  1531. func TestRunCidFileCheckIDLength(t *testing.T) {
  1532. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1533. if err != nil {
  1534. t.Fatal(err)
  1535. }
  1536. tmpCidFile := path.Join(tmpDir, "cid")
  1537. defer os.RemoveAll(tmpDir)
  1538. cmd := exec.Command(dockerBinary, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true")
  1539. out, _, err := runCommandWithOutput(cmd)
  1540. if err != nil {
  1541. t.Fatal(err)
  1542. }
  1543. id := strings.TrimSpace(out)
  1544. buffer, err := ioutil.ReadFile(tmpCidFile)
  1545. if err != nil {
  1546. t.Fatal(err)
  1547. }
  1548. cid := string(buffer)
  1549. if len(cid) != 64 {
  1550. t.Fatalf("--cidfile should be a long id, not '%s'", id)
  1551. }
  1552. if cid != id {
  1553. t.Fatalf("cid must be equal to %s, got %s", id, cid)
  1554. }
  1555. deleteAllContainers()
  1556. logDone("run - cidfile contains long id")
  1557. }
  1558. func TestRunNetworkNotInitializedNoneMode(t *testing.T) {
  1559. cmd := exec.Command(dockerBinary, "run", "-d", "--net=none", "busybox", "top")
  1560. out, _, err := runCommandWithOutput(cmd)
  1561. if err != nil {
  1562. t.Fatal(err)
  1563. }
  1564. id := strings.TrimSpace(out)
  1565. res, err := inspectField(id, "NetworkSettings.IPAddress")
  1566. if err != nil {
  1567. t.Fatal(err)
  1568. }
  1569. if res != "" {
  1570. t.Fatal("For 'none' mode network must not be initialized, but container got IP: %s", res)
  1571. }
  1572. deleteAllContainers()
  1573. logDone("run - network must not be initialized in 'none' mode")
  1574. }
  1575. func TestRunDeallocatePortOnMissingIptablesRule(t *testing.T) {
  1576. cmd := exec.Command(dockerBinary, "run", "-d", "-p", "23:23", "busybox", "top")
  1577. out, _, err := runCommandWithOutput(cmd)
  1578. if err != nil {
  1579. t.Fatal(err)
  1580. }
  1581. id := strings.TrimSpace(out)
  1582. ip, err := inspectField(id, "NetworkSettings.IPAddress")
  1583. if err != nil {
  1584. t.Fatal(err)
  1585. }
  1586. iptCmd := exec.Command("iptables", "-D", "FORWARD", "-d", fmt.Sprintf("%s/32", ip),
  1587. "!", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-m", "tcp", "--dport", "23", "-j", "ACCEPT")
  1588. out, _, err = runCommandWithOutput(iptCmd)
  1589. if err != nil {
  1590. t.Fatal(err, out)
  1591. }
  1592. if err := deleteContainer(id); err != nil {
  1593. t.Fatal(err)
  1594. }
  1595. cmd = exec.Command(dockerBinary, "run", "-d", "-p", "23:23", "busybox", "top")
  1596. out, _, err = runCommandWithOutput(cmd)
  1597. if err != nil {
  1598. t.Fatal(err, out)
  1599. }
  1600. deleteAllContainers()
  1601. logDone("run - port should be deallocated even on iptables error")
  1602. }
  1603. func TestRunPortInUse(t *testing.T) {
  1604. port := "1234"
  1605. l, err := net.Listen("tcp", ":"+port)
  1606. if err != nil {
  1607. t.Fatal(err)
  1608. }
  1609. defer l.Close()
  1610. cmd := exec.Command(dockerBinary, "run", "-p", port+":80", "busybox", "true")
  1611. out, _, err := runCommandWithOutput(cmd)
  1612. if err == nil {
  1613. t.Fatalf("Binding on used port must fail")
  1614. }
  1615. if !strings.Contains(out, "address already in use") {
  1616. t.Fatalf("Out must be about \"address already in use\", got %s", out)
  1617. }
  1618. deleteAllContainers()
  1619. logDone("run - fail if port already in use")
  1620. }