docker_cli_run_test.go 76 KB

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