docker_cli_run_test.go 70 KB

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