docker_cli_run_test.go 64 KB

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