docker_cli_run_test.go 60 KB

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