docker_cli_run_test.go 74 KB

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