docker_cli_run_test.go 58 KB

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