docker_cli_run_test.go 75 KB

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