docker_cli_run_test.go 62 KB

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