docker_cli_run_test.go 69 KB

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