docker_cli_run_test.go 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764
  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. "time"
  19. "github.com/docker/docker/pkg/nat"
  20. "github.com/docker/libnetwork/resolvconf"
  21. "github.com/go-check/check"
  22. )
  23. // "test123" should be printed by docker run
  24. func (s *DockerSuite) TestRunEchoStdout(c *check.C) {
  25. out, _ := dockerCmd(c, "run", "busybox", "echo", "test123")
  26. if out != "test123\n" {
  27. c.Fatalf("container should've printed 'test123'")
  28. }
  29. }
  30. // "test" should be printed
  31. func (s *DockerSuite) TestRunEchoNamedContainer(c *check.C) {
  32. out, _ := dockerCmd(c, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test")
  33. if out != "test\n" {
  34. c.Errorf("container should've printed 'test'")
  35. }
  36. }
  37. // docker run should not leak file descriptors
  38. func (s *DockerSuite) TestRunLeakyFileDescriptors(c *check.C) {
  39. out, _ := dockerCmd(c, "run", "busybox", "ls", "-C", "/proc/self/fd")
  40. // normally, we should only get 0, 1, and 2, but 3 gets created by "ls" when it does "opendir" on the "fd" directory
  41. if out != "0 1 2 3\n" {
  42. c.Errorf("container should've printed '0 1 2 3', not: %s", out)
  43. }
  44. }
  45. // it should be possible to lookup Google DNS
  46. // this will fail when Internet access is unavailable
  47. func (s *DockerSuite) TestRunLookupGoogleDns(c *check.C) {
  48. testRequires(c, Network)
  49. dockerCmd(c, "run", "busybox", "nslookup", "google.com")
  50. }
  51. // the exit code should be 0
  52. // some versions of lxc might make this test fail
  53. func (s *DockerSuite) TestRunExitCodeZero(c *check.C) {
  54. dockerCmd(c, "run", "busybox", "true")
  55. }
  56. // the exit code should be 1
  57. // some versions of lxc might make this test fail
  58. func (s *DockerSuite) TestRunExitCodeOne(c *check.C) {
  59. _, exitCode, err := dockerCmdWithError("run", "busybox", "false")
  60. if err != nil && !strings.Contains("exit status 1", fmt.Sprintf("%s", err)) {
  61. c.Fatal(err)
  62. }
  63. if exitCode != 1 {
  64. c.Errorf("container should've exited with exit code 1")
  65. }
  66. }
  67. // it should be possible to pipe in data via stdin to a process running in a container
  68. // some versions of lxc might make this test fail
  69. func (s *DockerSuite) TestRunStdinPipe(c *check.C) {
  70. runCmd := exec.Command(dockerBinary, "run", "-i", "-a", "stdin", "busybox", "cat")
  71. runCmd.Stdin = strings.NewReader("blahblah")
  72. out, _, _, err := runCommandWithStdoutStderr(runCmd)
  73. if err != nil {
  74. c.Fatalf("failed to run container: %v, output: %q", err, out)
  75. }
  76. out = strings.TrimSpace(out)
  77. dockerCmd(c, "wait", out)
  78. logsOut, _ := dockerCmd(c, "logs", out)
  79. containerLogs := strings.TrimSpace(logsOut)
  80. if containerLogs != "blahblah" {
  81. c.Errorf("logs didn't print the container's logs %s", containerLogs)
  82. }
  83. dockerCmd(c, "rm", out)
  84. }
  85. // the container's ID should be printed when starting a container in detached mode
  86. func (s *DockerSuite) TestRunDetachedContainerIDPrinting(c *check.C) {
  87. out, _ := dockerCmd(c, "run", "-d", "busybox", "true")
  88. out = strings.TrimSpace(out)
  89. dockerCmd(c, "wait", out)
  90. rmOut, _ := dockerCmd(c, "rm", out)
  91. rmOut = strings.TrimSpace(rmOut)
  92. if rmOut != out {
  93. c.Errorf("rm didn't print the container ID %s %s", out, rmOut)
  94. }
  95. }
  96. // the working directory should be set correctly
  97. func (s *DockerSuite) TestRunWorkingDirectory(c *check.C) {
  98. out, _ := dockerCmd(c, "run", "-w", "/root", "busybox", "pwd")
  99. out = strings.TrimSpace(out)
  100. if out != "/root" {
  101. c.Errorf("-w failed to set working directory")
  102. }
  103. out, _ = dockerCmd(c, "run", "--workdir", "/root", "busybox", "pwd")
  104. out = strings.TrimSpace(out)
  105. if out != "/root" {
  106. c.Errorf("--workdir failed to set working directory")
  107. }
  108. }
  109. // pinging Google's DNS resolver should fail when we disable the networking
  110. func (s *DockerSuite) TestRunWithoutNetworking(c *check.C) {
  111. out, exitCode, err := dockerCmdWithError("run", "--net=none", "busybox", "ping", "-c", "1", "8.8.8.8")
  112. if err != nil && exitCode != 1 {
  113. c.Fatal(out, err)
  114. }
  115. if exitCode != 1 {
  116. c.Errorf("--net=none should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
  117. }
  118. out, exitCode, err = dockerCmdWithError("run", "-n=false", "busybox", "ping", "-c", "1", "8.8.8.8")
  119. if err != nil && exitCode != 1 {
  120. c.Fatal(out, err)
  121. }
  122. if exitCode != 1 {
  123. c.Errorf("-n=false should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
  124. }
  125. }
  126. //test --link use container name to link target
  127. func (s *DockerSuite) TestRunLinksContainerWithContainerName(c *check.C) {
  128. dockerCmd(c, "run", "-i", "-t", "-d", "--name", "parent", "busybox")
  129. ip, err := inspectField("parent", "NetworkSettings.IPAddress")
  130. c.Assert(err, check.IsNil)
  131. out, _ := dockerCmd(c, "run", "--link", "parent:test", "busybox", "/bin/cat", "/etc/hosts")
  132. if !strings.Contains(out, ip+" test") {
  133. c.Fatalf("use a container name to link target failed")
  134. }
  135. }
  136. //test --link use container id to link target
  137. func (s *DockerSuite) TestRunLinksContainerWithContainerId(c *check.C) {
  138. cID, _ := dockerCmd(c, "run", "-i", "-t", "-d", "busybox")
  139. cID = strings.TrimSpace(cID)
  140. ip, err := inspectField(cID, "NetworkSettings.IPAddress")
  141. c.Assert(err, check.IsNil)
  142. out, _ := dockerCmd(c, "run", "--link", cID+":test", "busybox", "/bin/cat", "/etc/hosts")
  143. if !strings.Contains(out, ip+" test") {
  144. c.Fatalf("use a container id to link target failed")
  145. }
  146. }
  147. // Issue 9677.
  148. func (s *DockerSuite) TestRunWithDaemonFlags(c *check.C) {
  149. out, _, err := dockerCmdWithError("--selinux-enabled", "run", "-i", "-t", "busybox", "true")
  150. if err != nil {
  151. if !strings.Contains(out, "must follow the 'docker daemon' command") && // daemon
  152. !strings.Contains(out, "flag provided but not defined: --selinux-enabled") { // no daemon (client-only)
  153. c.Fatal(err, out)
  154. }
  155. }
  156. }
  157. // Regression test for #4979
  158. func (s *DockerSuite) TestRunWithVolumesFromExited(c *check.C) {
  159. out, exitCode := dockerCmd(c, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file")
  160. if exitCode != 0 {
  161. c.Fatal("1", out, exitCode)
  162. }
  163. out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file")
  164. if exitCode != 0 {
  165. c.Fatal("2", out, exitCode)
  166. }
  167. }
  168. // Volume path is a symlink which also exists on the host, and the host side is a file not a dir
  169. // But the volume call is just a normal volume, not a bind mount
  170. func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir(c *check.C) {
  171. testRequires(c, SameHostDaemon)
  172. testRequires(c, NativeExecDriver)
  173. name := "test-volume-symlink"
  174. dir, err := ioutil.TempDir("", name)
  175. if err != nil {
  176. c.Fatal(err)
  177. }
  178. defer os.RemoveAll(dir)
  179. f, err := os.OpenFile(filepath.Join(dir, "test"), os.O_CREATE, 0700)
  180. if err != nil {
  181. c.Fatal(err)
  182. }
  183. f.Close()
  184. dockerFile := fmt.Sprintf("FROM busybox\nRUN mkdir -p %s\nRUN ln -s %s /test", dir, dir)
  185. if _, err := buildImage(name, dockerFile, false); err != nil {
  186. c.Fatal(err)
  187. }
  188. dockerCmd(c, "run", "-v", "/test/test", name)
  189. }
  190. func (s *DockerSuite) TestRunVolumesMountedAsReadonly(c *check.C) {
  191. if _, code, err := dockerCmdWithError("run", "-v", "/test:/test:ro", "busybox", "touch", "/test/somefile"); err == nil || code == 0 {
  192. c.Fatalf("run should fail because volume is ro: exit code %d", code)
  193. }
  194. }
  195. func (s *DockerSuite) TestRunVolumesFromInReadonlyMode(c *check.C) {
  196. dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true")
  197. if _, code, err := dockerCmdWithError("run", "--volumes-from", "parent:ro", "busybox", "touch", "/test/file"); err == nil || code == 0 {
  198. c.Fatalf("run should fail because volume is ro: exit code %d", code)
  199. }
  200. }
  201. // Regression test for #1201
  202. func (s *DockerSuite) TestRunVolumesFromInReadWriteMode(c *check.C) {
  203. dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true")
  204. dockerCmd(c, "run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file")
  205. if out, _, err := dockerCmdWithError("run", "--volumes-from", "parent:bar", "busybox", "touch", "/test/file"); err == nil || !strings.Contains(out, "invalid mode for volumes-from: bar") {
  206. c.Fatalf("running --volumes-from foo:bar should have failed with invalid mount mode: %q", out)
  207. }
  208. dockerCmd(c, "run", "--volumes-from", "parent", "busybox", "touch", "/test/file")
  209. }
  210. func (s *DockerSuite) TestVolumesFromGetsProperMode(c *check.C) {
  211. dockerCmd(c, "run", "--name", "parent", "-v", "/test:/test:ro", "busybox", "true")
  212. // Expect this "rw" mode to be be ignored since the inherited volume is "ro"
  213. if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file"); err == nil {
  214. c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `rw`")
  215. }
  216. dockerCmd(c, "run", "--name", "parent2", "-v", "/test:/test:ro", "busybox", "true")
  217. // Expect this to be read-only since both are "ro"
  218. if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent2:ro", "busybox", "touch", "/test/file"); err == nil {
  219. c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `ro`")
  220. }
  221. }
  222. // Test for GH#10618
  223. func (s *DockerSuite) TestRunNoDupVolumes(c *check.C) {
  224. mountstr1 := randomUnixTmpDirPath("test1") + ":/someplace"
  225. mountstr2 := randomUnixTmpDirPath("test2") + ":/someplace"
  226. if out, _, err := dockerCmdWithError("run", "-v", mountstr1, "-v", mountstr2, "busybox", "true"); err == nil {
  227. c.Fatal("Expected error about duplicate volume definitions")
  228. } else {
  229. if !strings.Contains(out, "Duplicate bind mount") {
  230. c.Fatalf("Expected 'duplicate volume' error, got %v", err)
  231. }
  232. }
  233. }
  234. // Test for #1351
  235. func (s *DockerSuite) TestRunApplyVolumesFromBeforeVolumes(c *check.C) {
  236. dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "touch", "/test/foo")
  237. dockerCmd(c, "run", "--volumes-from", "parent", "-v", "/test", "busybox", "cat", "/test/foo")
  238. }
  239. func (s *DockerSuite) TestRunMultipleVolumesFrom(c *check.C) {
  240. dockerCmd(c, "run", "--name", "parent1", "-v", "/test", "busybox", "touch", "/test/foo")
  241. dockerCmd(c, "run", "--name", "parent2", "-v", "/other", "busybox", "touch", "/other/bar")
  242. dockerCmd(c, "run", "--volumes-from", "parent1", "--volumes-from", "parent2", "busybox", "sh", "-c", "cat /test/foo && cat /other/bar")
  243. }
  244. // this tests verifies the ID format for the container
  245. func (s *DockerSuite) TestRunVerifyContainerID(c *check.C) {
  246. out, exit, err := dockerCmdWithError("run", "-d", "busybox", "true")
  247. if err != nil {
  248. c.Fatal(err)
  249. }
  250. if exit != 0 {
  251. c.Fatalf("expected exit code 0 received %d", exit)
  252. }
  253. match, err := regexp.MatchString("^[0-9a-f]{64}$", strings.TrimSuffix(out, "\n"))
  254. if err != nil {
  255. c.Fatal(err)
  256. }
  257. if !match {
  258. c.Fatalf("Invalid container ID: %s", out)
  259. }
  260. }
  261. // Test that creating a container with a volume doesn't crash. Regression test for #995.
  262. func (s *DockerSuite) TestRunCreateVolume(c *check.C) {
  263. dockerCmd(c, "run", "-v", "/var/lib/data", "busybox", "true")
  264. }
  265. // Test that creating a volume with a symlink in its path works correctly. Test for #5152.
  266. // Note that this bug happens only with symlinks with a target that starts with '/'.
  267. func (s *DockerSuite) TestRunCreateVolumeWithSymlink(c *check.C) {
  268. image := "docker-test-createvolumewithsymlink"
  269. buildCmd := exec.Command(dockerBinary, "build", "-t", image, "-")
  270. buildCmd.Stdin = strings.NewReader(`FROM busybox
  271. RUN ln -s home /bar`)
  272. buildCmd.Dir = workingDirectory
  273. err := buildCmd.Run()
  274. if err != nil {
  275. c.Fatalf("could not build '%s': %v", image, err)
  276. }
  277. _, exitCode, err := dockerCmdWithError("run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", image, "sh", "-c", "mount | grep -q /home/foo")
  278. if err != nil || exitCode != 0 {
  279. c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
  280. }
  281. volPath, err := inspectMountSourceField("test-createvolumewithsymlink", "/bar/foo")
  282. if err != nil {
  283. c.Fatalf("[inspect] err: %v", err)
  284. }
  285. _, exitCode, err = dockerCmdWithError("rm", "-v", "test-createvolumewithsymlink")
  286. if err != nil || exitCode != 0 {
  287. c.Fatalf("[rm] err: %v, exitcode: %d", err, exitCode)
  288. }
  289. _, err = os.Stat(volPath)
  290. if !os.IsNotExist(err) {
  291. c.Fatalf("[open] (expecting 'file does not exist' error) err: %v, volPath: %s", err, volPath)
  292. }
  293. }
  294. // Tests that a volume path that has a symlink exists in a container mounting it with `--volumes-from`.
  295. func (s *DockerSuite) TestRunVolumesFromSymlinkPath(c *check.C) {
  296. name := "docker-test-volumesfromsymlinkpath"
  297. buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-")
  298. buildCmd.Stdin = strings.NewReader(`FROM busybox
  299. RUN ln -s home /foo
  300. VOLUME ["/foo/bar"]`)
  301. buildCmd.Dir = workingDirectory
  302. err := buildCmd.Run()
  303. if err != nil {
  304. c.Fatalf("could not build 'docker-test-volumesfromsymlinkpath': %v", err)
  305. }
  306. _, exitCode, err := dockerCmdWithError("run", "--name", "test-volumesfromsymlinkpath", name)
  307. if err != nil || exitCode != 0 {
  308. c.Fatalf("[run] (volume) err: %v, exitcode: %d", err, exitCode)
  309. }
  310. _, exitCode, err = dockerCmdWithError("run", "--volumes-from", "test-volumesfromsymlinkpath", "busybox", "sh", "-c", "ls /foo | grep -q bar")
  311. if err != nil || exitCode != 0 {
  312. c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
  313. }
  314. }
  315. func (s *DockerSuite) TestRunExitCode(c *check.C) {
  316. _, exit, err := dockerCmdWithError("run", "busybox", "/bin/sh", "-c", "exit 72")
  317. if err == nil {
  318. c.Fatal("should not have a non nil error")
  319. }
  320. if exit != 72 {
  321. c.Fatalf("expected exit code 72 received %d", exit)
  322. }
  323. }
  324. func (s *DockerSuite) TestRunUserDefaultsToRoot(c *check.C) {
  325. out, _ := dockerCmd(c, "run", "busybox", "id")
  326. if !strings.Contains(out, "uid=0(root) gid=0(root)") {
  327. c.Fatalf("expected root user got %s", out)
  328. }
  329. }
  330. func (s *DockerSuite) TestRunUserByName(c *check.C) {
  331. out, _ := dockerCmd(c, "run", "-u", "root", "busybox", "id")
  332. if !strings.Contains(out, "uid=0(root) gid=0(root)") {
  333. c.Fatalf("expected root user got %s", out)
  334. }
  335. }
  336. func (s *DockerSuite) TestRunUserByID(c *check.C) {
  337. out, _ := dockerCmd(c, "run", "-u", "1", "busybox", "id")
  338. if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") {
  339. c.Fatalf("expected daemon user got %s", out)
  340. }
  341. }
  342. func (s *DockerSuite) TestRunUserByIDBig(c *check.C) {
  343. out, _, err := dockerCmdWithError("run", "-u", "2147483648", "busybox", "id")
  344. if err == nil {
  345. c.Fatal("No error, but must be.", out)
  346. }
  347. if !strings.Contains(out, "Uids and gids must be in range") {
  348. c.Fatalf("expected error about uids range, got %s", out)
  349. }
  350. }
  351. func (s *DockerSuite) TestRunUserByIDNegative(c *check.C) {
  352. out, _, err := dockerCmdWithError("run", "-u", "-1", "busybox", "id")
  353. if err == nil {
  354. c.Fatal("No error, but must be.", out)
  355. }
  356. if !strings.Contains(out, "Uids and gids must be in range") {
  357. c.Fatalf("expected error about uids range, got %s", out)
  358. }
  359. }
  360. func (s *DockerSuite) TestRunUserByIDZero(c *check.C) {
  361. out, _, err := dockerCmdWithError("run", "-u", "0", "busybox", "id")
  362. if err != nil {
  363. c.Fatal(err, out)
  364. }
  365. if !strings.Contains(out, "uid=0(root) gid=0(root) groups=10(wheel)") {
  366. c.Fatalf("expected daemon user got %s", out)
  367. }
  368. }
  369. func (s *DockerSuite) TestRunUserNotFound(c *check.C) {
  370. _, _, err := dockerCmdWithError("run", "-u", "notme", "busybox", "id")
  371. if err == nil {
  372. c.Fatal("unknown user should cause container to fail")
  373. }
  374. }
  375. func (s *DockerSuite) TestRunTwoConcurrentContainers(c *check.C) {
  376. group := sync.WaitGroup{}
  377. group.Add(2)
  378. errChan := make(chan error, 2)
  379. for i := 0; i < 2; i++ {
  380. go func() {
  381. defer group.Done()
  382. _, _, err := dockerCmdWithError("run", "busybox", "sleep", "2")
  383. errChan <- err
  384. }()
  385. }
  386. group.Wait()
  387. close(errChan)
  388. for err := range errChan {
  389. c.Assert(err, check.IsNil)
  390. }
  391. }
  392. func (s *DockerSuite) TestRunEnvironment(c *check.C) {
  393. cmd := exec.Command(dockerBinary, "run", "-h", "testing", "-e=FALSE=true", "-e=TRUE", "-e=TRICKY", "-e=HOME=", "busybox", "env")
  394. cmd.Env = append(os.Environ(),
  395. "TRUE=false",
  396. "TRICKY=tri\ncky\n",
  397. )
  398. out, _, err := runCommandWithOutput(cmd)
  399. if err != nil {
  400. c.Fatal(err, out)
  401. }
  402. actualEnvLxc := strings.Split(strings.TrimSpace(out), "\n")
  403. actualEnv := []string{}
  404. for i := range actualEnvLxc {
  405. if actualEnvLxc[i] != "container=lxc" {
  406. actualEnv = append(actualEnv, actualEnvLxc[i])
  407. }
  408. }
  409. sort.Strings(actualEnv)
  410. goodEnv := []string{
  411. "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  412. "HOSTNAME=testing",
  413. "FALSE=true",
  414. "TRUE=false",
  415. "TRICKY=tri",
  416. "cky",
  417. "",
  418. "HOME=/root",
  419. }
  420. sort.Strings(goodEnv)
  421. if len(goodEnv) != len(actualEnv) {
  422. c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", "))
  423. }
  424. for i := range goodEnv {
  425. if actualEnv[i] != goodEnv[i] {
  426. c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
  427. }
  428. }
  429. }
  430. func (s *DockerSuite) TestRunEnvironmentErase(c *check.C) {
  431. // Test to make sure that when we use -e on env vars that are
  432. // not set in our local env that they're removed (if present) in
  433. // the container
  434. cmd := exec.Command(dockerBinary, "run", "-e", "FOO", "-e", "HOSTNAME", "busybox", "env")
  435. cmd.Env = appendBaseEnv([]string{})
  436. out, _, err := runCommandWithOutput(cmd)
  437. if err != nil {
  438. c.Fatal(err, out)
  439. }
  440. actualEnvLxc := strings.Split(strings.TrimSpace(out), "\n")
  441. actualEnv := []string{}
  442. for i := range actualEnvLxc {
  443. if actualEnvLxc[i] != "container=lxc" {
  444. actualEnv = append(actualEnv, actualEnvLxc[i])
  445. }
  446. }
  447. sort.Strings(actualEnv)
  448. goodEnv := []string{
  449. "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  450. "HOME=/root",
  451. }
  452. sort.Strings(goodEnv)
  453. if len(goodEnv) != len(actualEnv) {
  454. c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", "))
  455. }
  456. for i := range goodEnv {
  457. if actualEnv[i] != goodEnv[i] {
  458. c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
  459. }
  460. }
  461. }
  462. func (s *DockerSuite) TestRunEnvironmentOverride(c *check.C) {
  463. // Test to make sure that when we use -e on env vars that are
  464. // already in the env that we're overriding them
  465. cmd := exec.Command(dockerBinary, "run", "-e", "HOSTNAME", "-e", "HOME=/root2", "busybox", "env")
  466. cmd.Env = appendBaseEnv([]string{"HOSTNAME=bar"})
  467. out, _, err := runCommandWithOutput(cmd)
  468. if err != nil {
  469. c.Fatal(err, out)
  470. }
  471. actualEnvLxc := strings.Split(strings.TrimSpace(out), "\n")
  472. actualEnv := []string{}
  473. for i := range actualEnvLxc {
  474. if actualEnvLxc[i] != "container=lxc" {
  475. actualEnv = append(actualEnv, actualEnvLxc[i])
  476. }
  477. }
  478. sort.Strings(actualEnv)
  479. goodEnv := []string{
  480. "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  481. "HOME=/root2",
  482. "HOSTNAME=bar",
  483. }
  484. sort.Strings(goodEnv)
  485. if len(goodEnv) != len(actualEnv) {
  486. c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", "))
  487. }
  488. for i := range goodEnv {
  489. if actualEnv[i] != goodEnv[i] {
  490. c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
  491. }
  492. }
  493. }
  494. func (s *DockerSuite) TestRunContainerNetwork(c *check.C) {
  495. dockerCmd(c, "run", "busybox", "ping", "-c", "1", "127.0.0.1")
  496. }
  497. func (s *DockerSuite) TestRunNetHostNotAllowedWithLinks(c *check.C) {
  498. dockerCmd(c, "run", "--name", "linked", "busybox", "true")
  499. _, _, err := dockerCmdWithError("run", "--net=host", "--link", "linked:linked", "busybox", "true")
  500. if err == nil {
  501. c.Fatal("Expected error")
  502. }
  503. }
  504. // #7851 hostname outside container shows FQDN, inside only shortname
  505. // For testing purposes it is not required to set host's hostname directly
  506. // and use "--net=host" (as the original issue submitter did), as the same
  507. // codepath is executed with "docker run -h <hostname>". Both were manually
  508. // tested, but this testcase takes the simpler path of using "run -h .."
  509. func (s *DockerSuite) TestRunFullHostnameSet(c *check.C) {
  510. out, _ := dockerCmd(c, "run", "-h", "foo.bar.baz", "busybox", "hostname")
  511. if actual := strings.Trim(out, "\r\n"); actual != "foo.bar.baz" {
  512. c.Fatalf("expected hostname 'foo.bar.baz', received %s", actual)
  513. }
  514. }
  515. func (s *DockerSuite) TestRunPrivilegedCanMknod(c *check.C) {
  516. out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  517. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  518. c.Fatalf("expected output ok received %s", actual)
  519. }
  520. }
  521. func (s *DockerSuite) TestRunUnprivilegedCanMknod(c *check.C) {
  522. out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  523. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  524. c.Fatalf("expected output ok received %s", actual)
  525. }
  526. }
  527. func (s *DockerSuite) TestRunCapDropInvalid(c *check.C) {
  528. out, _, err := dockerCmdWithError("run", "--cap-drop=CHPASS", "busybox", "ls")
  529. if err == nil {
  530. c.Fatal(err, out)
  531. }
  532. }
  533. func (s *DockerSuite) TestRunCapDropCannotMknod(c *check.C) {
  534. out, _, err := dockerCmdWithError("run", "--cap-drop=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  535. if err == nil {
  536. c.Fatal(err, out)
  537. }
  538. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  539. c.Fatalf("expected output not ok received %s", actual)
  540. }
  541. }
  542. func (s *DockerSuite) TestRunCapDropCannotMknodLowerCase(c *check.C) {
  543. out, _, err := dockerCmdWithError("run", "--cap-drop=mknod", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  544. if err == nil {
  545. c.Fatal(err, out)
  546. }
  547. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  548. c.Fatalf("expected output not ok received %s", actual)
  549. }
  550. }
  551. func (s *DockerSuite) TestRunCapDropALLCannotMknod(c *check.C) {
  552. out, _, err := dockerCmdWithError("run", "--cap-drop=ALL", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  553. if err == nil {
  554. c.Fatal(err, out)
  555. }
  556. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  557. c.Fatalf("expected output not ok received %s", actual)
  558. }
  559. }
  560. func (s *DockerSuite) TestRunCapDropALLAddMknodCanMknod(c *check.C) {
  561. out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
  562. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  563. c.Fatalf("expected output ok received %s", actual)
  564. }
  565. }
  566. func (s *DockerSuite) TestRunCapAddInvalid(c *check.C) {
  567. out, _, err := dockerCmdWithError("run", "--cap-add=CHPASS", "busybox", "ls")
  568. if err == nil {
  569. c.Fatal(err, out)
  570. }
  571. }
  572. func (s *DockerSuite) TestRunCapAddCanDownInterface(c *check.C) {
  573. out, _ := dockerCmd(c, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  574. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  575. c.Fatalf("expected output ok received %s", actual)
  576. }
  577. }
  578. func (s *DockerSuite) TestRunCapAddALLCanDownInterface(c *check.C) {
  579. out, _ := dockerCmd(c, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  580. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  581. c.Fatalf("expected output ok received %s", actual)
  582. }
  583. }
  584. func (s *DockerSuite) TestRunCapAddALLDropNetAdminCanDownInterface(c *check.C) {
  585. out, _, err := dockerCmdWithError("run", "--cap-add=ALL", "--cap-drop=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  586. if err == nil {
  587. c.Fatal(err, out)
  588. }
  589. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  590. c.Fatalf("expected output not ok received %s", actual)
  591. }
  592. }
  593. func (s *DockerSuite) TestRunGroupAdd(c *check.C) {
  594. testRequires(c, NativeExecDriver)
  595. out, _ := dockerCmd(c, "run", "--group-add=audio", "--group-add=dbus", "--group-add=777", "busybox", "sh", "-c", "id")
  596. groupsList := "uid=0(root) gid=0(root) groups=10(wheel),29(audio),81(dbus),777"
  597. if actual := strings.Trim(out, "\r\n"); actual != groupsList {
  598. c.Fatalf("expected output %s received %s", groupsList, actual)
  599. }
  600. }
  601. func (s *DockerSuite) TestRunPrivilegedCanMount(c *check.C) {
  602. out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
  603. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  604. c.Fatalf("expected output ok received %s", actual)
  605. }
  606. }
  607. func (s *DockerSuite) TestRunUnprivilegedCannotMount(c *check.C) {
  608. out, _, err := dockerCmdWithError("run", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
  609. if err == nil {
  610. c.Fatal(err, out)
  611. }
  612. if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  613. c.Fatalf("expected output not ok received %s", actual)
  614. }
  615. }
  616. func (s *DockerSuite) TestRunSysNotWritableInNonPrivilegedContainers(c *check.C) {
  617. if _, code, err := dockerCmdWithError("run", "busybox", "touch", "/sys/kernel/profiling"); err == nil || code == 0 {
  618. c.Fatal("sys should not be writable in a non privileged container")
  619. }
  620. }
  621. func (s *DockerSuite) TestRunSysWritableInPrivilegedContainers(c *check.C) {
  622. if _, code, err := dockerCmdWithError("run", "--privileged", "busybox", "touch", "/sys/kernel/profiling"); err != nil || code != 0 {
  623. c.Fatalf("sys should be writable in privileged container")
  624. }
  625. }
  626. func (s *DockerSuite) TestRunProcNotWritableInNonPrivilegedContainers(c *check.C) {
  627. if _, code, err := dockerCmdWithError("run", "busybox", "touch", "/proc/sysrq-trigger"); err == nil || code == 0 {
  628. c.Fatal("proc should not be writable in a non privileged container")
  629. }
  630. }
  631. func (s *DockerSuite) TestRunProcWritableInPrivilegedContainers(c *check.C) {
  632. if _, code := dockerCmd(c, "run", "--privileged", "busybox", "touch", "/proc/sysrq-trigger"); code != 0 {
  633. c.Fatalf("proc should be writable in privileged container")
  634. }
  635. }
  636. func (s *DockerSuite) TestRunDeviceNumbers(c *check.C) {
  637. out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "ls -l /dev/null")
  638. deviceLineFields := strings.Fields(out)
  639. deviceLineFields[6] = ""
  640. deviceLineFields[7] = ""
  641. deviceLineFields[8] = ""
  642. expected := []string{"crw-rw-rw-", "1", "root", "root", "1,", "3", "", "", "", "/dev/null"}
  643. if !(reflect.DeepEqual(deviceLineFields, expected)) {
  644. c.Fatalf("expected output\ncrw-rw-rw- 1 root root 1, 3 May 24 13:29 /dev/null\n received\n %s\n", out)
  645. }
  646. }
  647. func (s *DockerSuite) TestRunThatCharacterDevicesActLikeCharacterDevices(c *check.C) {
  648. out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero")
  649. if actual := strings.Trim(out, "\r\n"); actual[0] == '0' {
  650. c.Fatalf("expected a new file called /zero to be create that is greater than 0 bytes long, but du says: %s", actual)
  651. }
  652. }
  653. func (s *DockerSuite) TestRunUnprivilegedWithChroot(c *check.C) {
  654. dockerCmd(c, "run", "busybox", "chroot", "/", "true")
  655. }
  656. func (s *DockerSuite) TestRunAddingOptionalDevices(c *check.C) {
  657. out, _ := dockerCmd(c, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo")
  658. if actual := strings.Trim(out, "\r\n"); actual != "/dev/nulo" {
  659. c.Fatalf("expected output /dev/nulo, received %s", actual)
  660. }
  661. }
  662. func (s *DockerSuite) TestRunModeHostname(c *check.C) {
  663. testRequires(c, SameHostDaemon)
  664. out, _ := dockerCmd(c, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname")
  665. if actual := strings.Trim(out, "\r\n"); actual != "testhostname" {
  666. c.Fatalf("expected 'testhostname', but says: %q", actual)
  667. }
  668. out, _ = dockerCmd(c, "run", "--net=host", "busybox", "cat", "/etc/hostname")
  669. hostname, err := os.Hostname()
  670. if err != nil {
  671. c.Fatal(err)
  672. }
  673. if actual := strings.Trim(out, "\r\n"); actual != hostname {
  674. c.Fatalf("expected %q, but says: %q", hostname, actual)
  675. }
  676. }
  677. func (s *DockerSuite) TestRunRootWorkdir(c *check.C) {
  678. out, _ := dockerCmd(c, "run", "--workdir", "/", "busybox", "pwd")
  679. if out != "/\n" {
  680. c.Fatalf("pwd returned %q (expected /\\n)", s)
  681. }
  682. }
  683. func (s *DockerSuite) TestRunAllowBindMountingRoot(c *check.C) {
  684. dockerCmd(c, "run", "-v", "/:/host", "busybox", "ls", "/host")
  685. }
  686. func (s *DockerSuite) TestRunDisallowBindMountingRootToRoot(c *check.C) {
  687. out, _, err := dockerCmdWithError("run", "-v", "/:/", "busybox", "ls", "/host")
  688. if err == nil {
  689. c.Fatal(out, err)
  690. }
  691. }
  692. // Verify that a container gets default DNS when only localhost resolvers exist
  693. func (s *DockerSuite) TestRunDnsDefaultOptions(c *check.C) {
  694. testRequires(c, SameHostDaemon)
  695. // preserve original resolv.conf for restoring after test
  696. origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  697. if os.IsNotExist(err) {
  698. c.Fatalf("/etc/resolv.conf does not exist")
  699. }
  700. // defer restored original conf
  701. defer func() {
  702. if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil {
  703. c.Fatal(err)
  704. }
  705. }()
  706. // test 3 cases: standard IPv4 localhost, commented out localhost, and IPv6 localhost
  707. // 2 are removed from the file at container start, and the 3rd (commented out) one is ignored by
  708. // GetNameservers(), leading to a replacement of nameservers with the default set
  709. tmpResolvConf := []byte("nameserver 127.0.0.1\n#nameserver 127.0.2.1\nnameserver ::1")
  710. if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
  711. c.Fatal(err)
  712. }
  713. actual, _ := dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf")
  714. // check that the actual defaults are appended to the commented out
  715. // localhost resolver (which should be preserved)
  716. // NOTE: if we ever change the defaults from google dns, this will break
  717. expected := "#nameserver 127.0.2.1\n\nnameserver 8.8.8.8\nnameserver 8.8.4.4"
  718. if actual != expected {
  719. c.Fatalf("expected resolv.conf be: %q, but was: %q", expected, actual)
  720. }
  721. }
  722. func (s *DockerSuite) TestRunDnsOptions(c *check.C) {
  723. out, stderr, _ := dockerCmdWithStdoutStderr(c, "run", "--dns=127.0.0.1", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
  724. // The client will get a warning on stderr when setting DNS to a localhost address; verify this:
  725. if !strings.Contains(stderr, "Localhost DNS setting") {
  726. c.Fatalf("Expected warning on stderr about localhost resolver, but got %q", stderr)
  727. }
  728. actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1)
  729. if actual != "nameserver 127.0.0.1 search mydomain" {
  730. c.Fatalf("expected 'nameserver 127.0.0.1 search mydomain', but says: %q", actual)
  731. }
  732. out, stderr, _ = dockerCmdWithStdoutStderr(c, "run", "--dns=127.0.0.1", "--dns-search=.", "busybox", "cat", "/etc/resolv.conf")
  733. actual = strings.Replace(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ", -1)
  734. if actual != "nameserver 127.0.0.1" {
  735. c.Fatalf("expected 'nameserver 127.0.0.1', but says: %q", actual)
  736. }
  737. }
  738. func (s *DockerSuite) TestRunDnsOptionsBasedOnHostResolvConf(c *check.C) {
  739. testRequires(c, SameHostDaemon)
  740. origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  741. if os.IsNotExist(err) {
  742. c.Fatalf("/etc/resolv.conf does not exist")
  743. }
  744. hostNamservers := resolvconf.GetNameservers(origResolvConf)
  745. hostSearch := resolvconf.GetSearchDomains(origResolvConf)
  746. var out string
  747. out, _ = dockerCmd(c, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf")
  748. if actualNameservers := resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "127.0.0.1" {
  749. c.Fatalf("expected '127.0.0.1', but says: %q", string(actualNameservers[0]))
  750. }
  751. actualSearch := resolvconf.GetSearchDomains([]byte(out))
  752. if len(actualSearch) != len(hostSearch) {
  753. c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch))
  754. }
  755. for i := range actualSearch {
  756. if actualSearch[i] != hostSearch[i] {
  757. c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i])
  758. }
  759. }
  760. out, _ = dockerCmd(c, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
  761. actualNameservers := resolvconf.GetNameservers([]byte(out))
  762. if len(actualNameservers) != len(hostNamservers) {
  763. c.Fatalf("expected %q nameserver(s), but it has: %q", len(hostNamservers), len(actualNameservers))
  764. }
  765. for i := range actualNameservers {
  766. if actualNameservers[i] != hostNamservers[i] {
  767. c.Fatalf("expected %q nameserver, but says: %q", actualNameservers[i], hostNamservers[i])
  768. }
  769. }
  770. if actualSearch = resolvconf.GetSearchDomains([]byte(out)); string(actualSearch[0]) != "mydomain" {
  771. c.Fatalf("expected 'mydomain', but says: %q", string(actualSearch[0]))
  772. }
  773. // test with file
  774. tmpResolvConf := []byte("search example.com\nnameserver 12.34.56.78\nnameserver 127.0.0.1")
  775. if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
  776. c.Fatal(err)
  777. }
  778. // put the old resolvconf back
  779. defer func() {
  780. if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil {
  781. c.Fatal(err)
  782. }
  783. }()
  784. resolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  785. if os.IsNotExist(err) {
  786. c.Fatalf("/etc/resolv.conf does not exist")
  787. }
  788. hostNamservers = resolvconf.GetNameservers(resolvConf)
  789. hostSearch = resolvconf.GetSearchDomains(resolvConf)
  790. out, _ = dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf")
  791. if actualNameservers = resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "12.34.56.78" || len(actualNameservers) != 1 {
  792. c.Fatalf("expected '12.34.56.78', but has: %v", actualNameservers)
  793. }
  794. actualSearch = resolvconf.GetSearchDomains([]byte(out))
  795. if len(actualSearch) != len(hostSearch) {
  796. c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch))
  797. }
  798. for i := range actualSearch {
  799. if actualSearch[i] != hostSearch[i] {
  800. c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i])
  801. }
  802. }
  803. }
  804. // Test to see if a non-root user can resolve a DNS name and reach out to it. Also
  805. // check if the container resolv.conf file has at least 0644 perm.
  806. func (s *DockerSuite) TestRunNonRootUserResolvName(c *check.C) {
  807. testRequires(c, SameHostDaemon, Network)
  808. dockerCmd(c, "run", "--name=testperm", "--user=default", "busybox", "ping", "-c", "1", "apt.dockerproject.org")
  809. cID, err := getIDByName("testperm")
  810. if err != nil {
  811. c.Fatal(err)
  812. }
  813. fmode := (os.FileMode)(0644)
  814. finfo, err := os.Stat(containerStorageFile(cID, "resolv.conf"))
  815. if err != nil {
  816. c.Fatal(err)
  817. }
  818. if (finfo.Mode() & fmode) != fmode {
  819. c.Fatalf("Expected container resolv.conf mode to be at least %s, instead got %s", fmode.String(), finfo.Mode().String())
  820. }
  821. }
  822. // Test if container resolv.conf gets updated the next time it restarts
  823. // if host /etc/resolv.conf has changed. This only applies if the container
  824. // uses the host's /etc/resolv.conf and does not have any dns options provided.
  825. func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) {
  826. testRequires(c, SameHostDaemon)
  827. tmpResolvConf := []byte("search pommesfrites.fr\nnameserver 12.34.56.78")
  828. tmpLocalhostResolvConf := []byte("nameserver 127.0.0.1")
  829. //take a copy of resolv.conf for restoring after test completes
  830. resolvConfSystem, err := ioutil.ReadFile("/etc/resolv.conf")
  831. if err != nil {
  832. c.Fatal(err)
  833. }
  834. // This test case is meant to test monitoring resolv.conf when it is
  835. // a regular file not a bind mounc. So we unmount resolv.conf and replace
  836. // it with a file containing the original settings.
  837. cmd := exec.Command("umount", "/etc/resolv.conf")
  838. if _, err = runCommand(cmd); err != nil {
  839. c.Fatal(err)
  840. }
  841. //cleanup
  842. defer func() {
  843. if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  844. c.Fatal(err)
  845. }
  846. }()
  847. //1. test that a restarting container gets an updated resolv.conf
  848. dockerCmd(c, "run", "--name='first'", "busybox", "true")
  849. containerID1, err := getIDByName("first")
  850. if err != nil {
  851. c.Fatal(err)
  852. }
  853. // replace resolv.conf with our temporary copy
  854. bytesResolvConf := []byte(tmpResolvConf)
  855. if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  856. c.Fatal(err)
  857. }
  858. // start the container again to pickup changes
  859. dockerCmd(c, "start", "first")
  860. // check for update in container
  861. containerResolv, err := readContainerFile(containerID1, "resolv.conf")
  862. if err != nil {
  863. c.Fatal(err)
  864. }
  865. if !bytes.Equal(containerResolv, bytesResolvConf) {
  866. c.Fatalf("Restarted container does not have updated resolv.conf; expected %q, got %q", tmpResolvConf, string(containerResolv))
  867. }
  868. /* //make a change to resolv.conf (in this case replacing our tmp copy with orig copy)
  869. if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  870. c.Fatal(err)
  871. } */
  872. //2. test that a restarting container does not receive resolv.conf updates
  873. // if it modified the container copy of the starting point resolv.conf
  874. dockerCmd(c, "run", "--name='second'", "busybox", "sh", "-c", "echo 'search mylittlepony.com' >>/etc/resolv.conf")
  875. containerID2, err := getIDByName("second")
  876. if err != nil {
  877. c.Fatal(err)
  878. }
  879. //make a change to resolv.conf (in this case replacing our tmp copy with orig copy)
  880. if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  881. c.Fatal(err)
  882. }
  883. // start the container again
  884. dockerCmd(c, "start", "second")
  885. // check for update in container
  886. containerResolv, err = readContainerFile(containerID2, "resolv.conf")
  887. if err != nil {
  888. c.Fatal(err)
  889. }
  890. if bytes.Equal(containerResolv, resolvConfSystem) {
  891. c.Fatalf("Restarting a container after container updated resolv.conf should not pick up host changes; expected %q, got %q", string(containerResolv), string(resolvConfSystem))
  892. }
  893. //3. test that a running container's resolv.conf is not modified while running
  894. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  895. runningContainerID := strings.TrimSpace(out)
  896. // replace resolv.conf
  897. if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  898. c.Fatal(err)
  899. }
  900. // check for update in container
  901. containerResolv, err = readContainerFile(runningContainerID, "resolv.conf")
  902. if err != nil {
  903. c.Fatal(err)
  904. }
  905. if bytes.Equal(containerResolv, bytesResolvConf) {
  906. c.Fatalf("Running container should not have updated resolv.conf; expected %q, got %q", string(resolvConfSystem), string(containerResolv))
  907. }
  908. //4. test that a running container's resolv.conf is updated upon restart
  909. // (the above container is still running..)
  910. dockerCmd(c, "restart", runningContainerID)
  911. // check for update in container
  912. containerResolv, err = readContainerFile(runningContainerID, "resolv.conf")
  913. if err != nil {
  914. c.Fatal(err)
  915. }
  916. if !bytes.Equal(containerResolv, bytesResolvConf) {
  917. c.Fatalf("Restarted container should have updated resolv.conf; expected %q, got %q", string(bytesResolvConf), string(containerResolv))
  918. }
  919. //5. test that additions of a localhost resolver are cleaned from
  920. // host resolv.conf before updating container's resolv.conf copies
  921. // replace resolv.conf with a localhost-only nameserver copy
  922. bytesResolvConf = []byte(tmpLocalhostResolvConf)
  923. if err = ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  924. c.Fatal(err)
  925. }
  926. // start the container again to pickup changes
  927. dockerCmd(c, "start", "first")
  928. // our first exited container ID should have been updated, but with default DNS
  929. // after the cleanup of resolv.conf found only a localhost nameserver:
  930. containerResolv, err = readContainerFile(containerID1, "resolv.conf")
  931. if err != nil {
  932. c.Fatal(err)
  933. }
  934. expected := "\nnameserver 8.8.8.8\nnameserver 8.8.4.4"
  935. if !bytes.Equal(containerResolv, []byte(expected)) {
  936. c.Fatalf("Container does not have cleaned/replaced DNS in resolv.conf; expected %q, got %q", expected, string(containerResolv))
  937. }
  938. //6. Test that replacing (as opposed to modifying) resolv.conf triggers an update
  939. // of containers' resolv.conf.
  940. // Restore the original resolv.conf
  941. if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  942. c.Fatal(err)
  943. }
  944. // Run the container so it picks up the old settings
  945. dockerCmd(c, "run", "--name='third'", "busybox", "true")
  946. containerID3, err := getIDByName("third")
  947. if err != nil {
  948. c.Fatal(err)
  949. }
  950. // Create a modified resolv.conf.aside and override resolv.conf with it
  951. bytesResolvConf = []byte(tmpResolvConf)
  952. if err := ioutil.WriteFile("/etc/resolv.conf.aside", bytesResolvConf, 0644); err != nil {
  953. c.Fatal(err)
  954. }
  955. err = os.Rename("/etc/resolv.conf.aside", "/etc/resolv.conf")
  956. if err != nil {
  957. c.Fatal(err)
  958. }
  959. // start the container again to pickup changes
  960. dockerCmd(c, "start", "third")
  961. // check for update in container
  962. containerResolv, err = readContainerFile(containerID3, "resolv.conf")
  963. if err != nil {
  964. c.Fatal(err)
  965. }
  966. if !bytes.Equal(containerResolv, bytesResolvConf) {
  967. c.Fatalf("Stopped container does not have updated resolv.conf; expected\n%q\n got\n%q", tmpResolvConf, string(containerResolv))
  968. }
  969. //cleanup, restore original resolv.conf happens in defer func()
  970. }
  971. func (s *DockerSuite) TestRunAddHost(c *check.C) {
  972. out, _ := dockerCmd(c, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts")
  973. actual := strings.Trim(out, "\r\n")
  974. if actual != "86.75.30.9\textra" {
  975. c.Fatalf("expected '86.75.30.9\textra', but says: %q", actual)
  976. }
  977. }
  978. // Regression test for #6983
  979. func (s *DockerSuite) TestRunAttachStdErrOnlyTTYMode(c *check.C) {
  980. _, exitCode := dockerCmd(c, "run", "-t", "-a", "stderr", "busybox", "true")
  981. if exitCode != 0 {
  982. c.Fatalf("Container should have exited with error code 0")
  983. }
  984. }
  985. // Regression test for #6983
  986. func (s *DockerSuite) TestRunAttachStdOutOnlyTTYMode(c *check.C) {
  987. _, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "busybox", "true")
  988. if exitCode != 0 {
  989. c.Fatalf("Container should have exited with error code 0")
  990. }
  991. }
  992. // Regression test for #6983
  993. func (s *DockerSuite) TestRunAttachStdOutAndErrTTYMode(c *check.C) {
  994. _, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true")
  995. if exitCode != 0 {
  996. c.Fatalf("Container should have exited with error code 0")
  997. }
  998. }
  999. // Test for #10388 - this will run the same test as TestRunAttachStdOutAndErrTTYMode
  1000. // but using --attach instead of -a to make sure we read the flag correctly
  1001. func (s *DockerSuite) TestRunAttachWithDetach(c *check.C) {
  1002. cmd := exec.Command(dockerBinary, "run", "-d", "--attach", "stdout", "busybox", "true")
  1003. _, stderr, _, err := runCommandWithStdoutStderr(cmd)
  1004. if err == nil {
  1005. c.Fatal("Container should have exited with error code different than 0")
  1006. } else if !strings.Contains(stderr, "Conflicting options: -a and -d") {
  1007. c.Fatal("Should have been returned an error with conflicting options -a and -d")
  1008. }
  1009. }
  1010. func (s *DockerSuite) TestRunState(c *check.C) {
  1011. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1012. id := strings.TrimSpace(out)
  1013. state, err := inspectField(id, "State.Running")
  1014. c.Assert(err, check.IsNil)
  1015. if state != "true" {
  1016. c.Fatal("Container state is 'not running'")
  1017. }
  1018. pid1, err := inspectField(id, "State.Pid")
  1019. c.Assert(err, check.IsNil)
  1020. if pid1 == "0" {
  1021. c.Fatal("Container state Pid 0")
  1022. }
  1023. dockerCmd(c, "stop", id)
  1024. state, err = inspectField(id, "State.Running")
  1025. c.Assert(err, check.IsNil)
  1026. if state != "false" {
  1027. c.Fatal("Container state is 'running'")
  1028. }
  1029. pid2, err := inspectField(id, "State.Pid")
  1030. c.Assert(err, check.IsNil)
  1031. if pid2 == pid1 {
  1032. c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1033. }
  1034. dockerCmd(c, "start", id)
  1035. state, err = inspectField(id, "State.Running")
  1036. c.Assert(err, check.IsNil)
  1037. if state != "true" {
  1038. c.Fatal("Container state is 'not running'")
  1039. }
  1040. pid3, err := inspectField(id, "State.Pid")
  1041. c.Assert(err, check.IsNil)
  1042. if pid3 == pid1 {
  1043. c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1044. }
  1045. }
  1046. // Test for #1737
  1047. func (s *DockerSuite) TestRunCopyVolumeUidGid(c *check.C) {
  1048. name := "testrunvolumesuidgid"
  1049. _, err := buildImage(name,
  1050. `FROM busybox
  1051. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1052. RUN echo 'dockerio:x:1001:' >> /etc/group
  1053. RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`,
  1054. true)
  1055. if err != nil {
  1056. c.Fatal(err)
  1057. }
  1058. // Test that the uid and gid is copied from the image to the volume
  1059. out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'")
  1060. out = strings.TrimSpace(out)
  1061. if out != "dockerio:dockerio" {
  1062. c.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out)
  1063. }
  1064. }
  1065. // Test for #1582
  1066. func (s *DockerSuite) TestRunCopyVolumeContent(c *check.C) {
  1067. name := "testruncopyvolumecontent"
  1068. _, err := buildImage(name,
  1069. `FROM busybox
  1070. RUN mkdir -p /hello/local && echo hello > /hello/local/world`,
  1071. true)
  1072. if err != nil {
  1073. c.Fatal(err)
  1074. }
  1075. // Test that the content is copied from the image to the volume
  1076. out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "find", "/hello")
  1077. if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) {
  1078. c.Fatal("Container failed to transfer content to volume")
  1079. }
  1080. }
  1081. func (s *DockerSuite) TestRunCleanupCmdOnEntrypoint(c *check.C) {
  1082. name := "testrunmdcleanuponentrypoint"
  1083. if _, err := buildImage(name,
  1084. `FROM busybox
  1085. ENTRYPOINT ["echo"]
  1086. CMD ["testingpoint"]`,
  1087. true); err != nil {
  1088. c.Fatal(err)
  1089. }
  1090. out, exit := dockerCmd(c, "run", "--entrypoint", "whoami", name)
  1091. if exit != 0 {
  1092. c.Fatalf("expected exit code 0 received %d, out: %q", exit, out)
  1093. }
  1094. out = strings.TrimSpace(out)
  1095. if out != "root" {
  1096. c.Fatalf("Expected output root, got %q", out)
  1097. }
  1098. }
  1099. // TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected
  1100. func (s *DockerSuite) TestRunWorkdirExistsAndIsFile(c *check.C) {
  1101. out, exit, err := dockerCmdWithError("run", "-w", "/bin/cat", "busybox")
  1102. if !(err != nil && exit == 1 && strings.Contains(out, "Cannot mkdir: /bin/cat is not a directory")) {
  1103. c.Fatalf("Docker must complains about making dir, but we got out: %s, exit: %d, err: %s", out, exit, err)
  1104. }
  1105. }
  1106. func (s *DockerSuite) TestRunExitOnStdinClose(c *check.C) {
  1107. name := "testrunexitonstdinclose"
  1108. runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", "/bin/cat")
  1109. stdin, err := runCmd.StdinPipe()
  1110. if err != nil {
  1111. c.Fatal(err)
  1112. }
  1113. stdout, err := runCmd.StdoutPipe()
  1114. if err != nil {
  1115. c.Fatal(err)
  1116. }
  1117. if err := runCmd.Start(); err != nil {
  1118. c.Fatal(err)
  1119. }
  1120. if _, err := stdin.Write([]byte("hello\n")); err != nil {
  1121. c.Fatal(err)
  1122. }
  1123. r := bufio.NewReader(stdout)
  1124. line, err := r.ReadString('\n')
  1125. if err != nil {
  1126. c.Fatal(err)
  1127. }
  1128. line = strings.TrimSpace(line)
  1129. if line != "hello" {
  1130. c.Fatalf("Output should be 'hello', got '%q'", line)
  1131. }
  1132. if err := stdin.Close(); err != nil {
  1133. c.Fatal(err)
  1134. }
  1135. finish := make(chan error)
  1136. go func() {
  1137. finish <- runCmd.Wait()
  1138. close(finish)
  1139. }()
  1140. select {
  1141. case err := <-finish:
  1142. c.Assert(err, check.IsNil)
  1143. case <-time.After(1 * time.Second):
  1144. c.Fatal("docker run failed to exit on stdin close")
  1145. }
  1146. state, err := inspectField(name, "State.Running")
  1147. c.Assert(err, check.IsNil)
  1148. if state != "false" {
  1149. c.Fatal("Container must be stopped after stdin closing")
  1150. }
  1151. }
  1152. // Test for #2267
  1153. func (s *DockerSuite) TestRunWriteHostsFileAndNotCommit(c *check.C) {
  1154. name := "writehosts"
  1155. out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hosts && cat /etc/hosts")
  1156. if !strings.Contains(out, "test2267") {
  1157. c.Fatal("/etc/hosts should contain 'test2267'")
  1158. }
  1159. out, _ = dockerCmd(c, "diff", name)
  1160. if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1161. c.Fatal("diff should be empty")
  1162. }
  1163. }
  1164. func eqToBaseDiff(out string, c *check.C) bool {
  1165. out1, _ := dockerCmd(c, "run", "-d", "busybox", "echo", "hello")
  1166. cID := strings.TrimSpace(out1)
  1167. baseDiff, _ := dockerCmd(c, "diff", cID)
  1168. baseArr := strings.Split(baseDiff, "\n")
  1169. sort.Strings(baseArr)
  1170. outArr := strings.Split(out, "\n")
  1171. sort.Strings(outArr)
  1172. return sliceEq(baseArr, outArr)
  1173. }
  1174. func sliceEq(a, b []string) bool {
  1175. if len(a) != len(b) {
  1176. return false
  1177. }
  1178. for i := range a {
  1179. if a[i] != b[i] {
  1180. return false
  1181. }
  1182. }
  1183. return true
  1184. }
  1185. // Test for #2267
  1186. func (s *DockerSuite) TestRunWriteHostnameFileAndNotCommit(c *check.C) {
  1187. name := "writehostname"
  1188. out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hostname && cat /etc/hostname")
  1189. if !strings.Contains(out, "test2267") {
  1190. c.Fatal("/etc/hostname should contain 'test2267'")
  1191. }
  1192. out, _ = dockerCmd(c, "diff", name)
  1193. if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1194. c.Fatal("diff should be empty")
  1195. }
  1196. }
  1197. // Test for #2267
  1198. func (s *DockerSuite) TestRunWriteResolvFileAndNotCommit(c *check.C) {
  1199. name := "writeresolv"
  1200. out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/resolv.conf && cat /etc/resolv.conf")
  1201. if !strings.Contains(out, "test2267") {
  1202. c.Fatal("/etc/resolv.conf should contain 'test2267'")
  1203. }
  1204. out, _ = dockerCmd(c, "diff", name)
  1205. if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1206. c.Fatal("diff should be empty")
  1207. }
  1208. }
  1209. func (s *DockerSuite) TestRunWithBadDevice(c *check.C) {
  1210. name := "baddevice"
  1211. out, _, err := dockerCmdWithError("run", "--name", name, "--device", "/etc", "busybox", "true")
  1212. if err == nil {
  1213. c.Fatal("Run should fail with bad device")
  1214. }
  1215. expected := `"/etc": not a device node`
  1216. if !strings.Contains(out, expected) {
  1217. c.Fatalf("Output should contain %q, actual out: %q", expected, out)
  1218. }
  1219. }
  1220. func (s *DockerSuite) TestRunEntrypoint(c *check.C) {
  1221. name := "entrypoint"
  1222. out, _ := dockerCmd(c, "run", "--name", name, "--entrypoint", "/bin/echo", "busybox", "-n", "foobar")
  1223. expected := "foobar"
  1224. if out != expected {
  1225. c.Fatalf("Output should be %q, actual out: %q", expected, out)
  1226. }
  1227. }
  1228. func (s *DockerSuite) TestRunBindMounts(c *check.C) {
  1229. testRequires(c, SameHostDaemon)
  1230. tmpDir, err := ioutil.TempDir("", "docker-test-container")
  1231. if err != nil {
  1232. c.Fatal(err)
  1233. }
  1234. defer os.RemoveAll(tmpDir)
  1235. writeFile(path.Join(tmpDir, "touch-me"), "", c)
  1236. // Test reading from a read-only bind mount
  1237. out, _ := dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox", "ls", "/tmp")
  1238. if !strings.Contains(out, "touch-me") {
  1239. c.Fatal("Container failed to read from bind mount")
  1240. }
  1241. // test writing to bind mount
  1242. dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla")
  1243. readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist
  1244. // test mounting to an illegal destination directory
  1245. _, _, err = dockerCmdWithError("run", "-v", fmt.Sprintf("%s:.", tmpDir), "busybox", "ls", ".")
  1246. if err == nil {
  1247. c.Fatal("Container bind mounted illegal directory")
  1248. }
  1249. // test mount a file
  1250. dockerCmd(c, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla")
  1251. content := readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist
  1252. expected := "yotta"
  1253. if content != expected {
  1254. c.Fatalf("Output should be %q, actual out: %q", expected, content)
  1255. }
  1256. }
  1257. // Ensure that CIDFile gets deleted if it's empty
  1258. // Perform this test by making `docker run` fail
  1259. func (s *DockerSuite) TestRunCidFileCleanupIfEmpty(c *check.C) {
  1260. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1261. if err != nil {
  1262. c.Fatal(err)
  1263. }
  1264. defer os.RemoveAll(tmpDir)
  1265. tmpCidFile := path.Join(tmpDir, "cid")
  1266. out, _, err := dockerCmdWithError("run", "--cidfile", tmpCidFile, "emptyfs")
  1267. if err == nil {
  1268. c.Fatalf("Run without command must fail. out=%s", out)
  1269. } else if !strings.Contains(out, "No command specified") {
  1270. c.Fatalf("Run without command failed with wrong output. out=%s\nerr=%v", out, err)
  1271. }
  1272. if _, err := os.Stat(tmpCidFile); err == nil {
  1273. c.Fatalf("empty CIDFile %q should've been deleted", tmpCidFile)
  1274. }
  1275. }
  1276. // #2098 - Docker cidFiles only contain short version of the containerId
  1277. //sudo docker run --cidfile /tmp/docker_tesc.cid ubuntu echo "test"
  1278. // TestRunCidFile tests that run --cidfile returns the longid
  1279. func (s *DockerSuite) TestRunCidFileCheckIDLength(c *check.C) {
  1280. tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1281. if err != nil {
  1282. c.Fatal(err)
  1283. }
  1284. tmpCidFile := path.Join(tmpDir, "cid")
  1285. defer os.RemoveAll(tmpDir)
  1286. out, _ := dockerCmd(c, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true")
  1287. id := strings.TrimSpace(out)
  1288. buffer, err := ioutil.ReadFile(tmpCidFile)
  1289. if err != nil {
  1290. c.Fatal(err)
  1291. }
  1292. cid := string(buffer)
  1293. if len(cid) != 64 {
  1294. c.Fatalf("--cidfile should be a long id, not %q", id)
  1295. }
  1296. if cid != id {
  1297. c.Fatalf("cid must be equal to %s, got %s", id, cid)
  1298. }
  1299. }
  1300. func (s *DockerSuite) TestRunSetMacAddress(c *check.C) {
  1301. mac := "12:34:56:78:9a:bc"
  1302. out, _ := dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "/bin/sh", "-c", "ip link show eth0 | tail -1 | awk '{print $2}'")
  1303. actualMac := strings.TrimSpace(out)
  1304. if actualMac != mac {
  1305. c.Fatalf("Set MAC address with --mac-address failed. The container has an incorrect MAC address: %q, expected: %q", actualMac, mac)
  1306. }
  1307. }
  1308. func (s *DockerSuite) TestRunInspectMacAddress(c *check.C) {
  1309. mac := "12:34:56:78:9a:bc"
  1310. out, _ := dockerCmd(c, "run", "-d", "--mac-address="+mac, "busybox", "top")
  1311. id := strings.TrimSpace(out)
  1312. inspectedMac, err := inspectField(id, "NetworkSettings.MacAddress")
  1313. c.Assert(err, check.IsNil)
  1314. if inspectedMac != mac {
  1315. c.Fatalf("docker inspect outputs wrong MAC address: %q, should be: %q", inspectedMac, mac)
  1316. }
  1317. }
  1318. // test docker run use a invalid mac address
  1319. func (s *DockerSuite) TestRunWithInvalidMacAddress(c *check.C) {
  1320. out, _, err := dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29", "busybox")
  1321. //use a invalid mac address should with a error out
  1322. if err == nil || !strings.Contains(out, "is not a valid mac address") {
  1323. c.Fatalf("run with an invalid --mac-address should with error out")
  1324. }
  1325. }
  1326. func (s *DockerSuite) TestRunDeallocatePortOnMissingIptablesRule(c *check.C) {
  1327. testRequires(c, SameHostDaemon)
  1328. out, _ := dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top")
  1329. id := strings.TrimSpace(out)
  1330. ip, err := inspectField(id, "NetworkSettings.IPAddress")
  1331. c.Assert(err, check.IsNil)
  1332. iptCmd := exec.Command("iptables", "-D", "DOCKER", "-d", fmt.Sprintf("%s/32", ip),
  1333. "!", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-m", "tcp", "--dport", "23", "-j", "ACCEPT")
  1334. out, _, err = runCommandWithOutput(iptCmd)
  1335. if err != nil {
  1336. c.Fatal(err, out)
  1337. }
  1338. if err := deleteContainer(id); err != nil {
  1339. c.Fatal(err)
  1340. }
  1341. dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top")
  1342. }
  1343. func (s *DockerSuite) TestRunPortInUse(c *check.C) {
  1344. testRequires(c, SameHostDaemon)
  1345. port := "1234"
  1346. dockerCmd(c, "run", "-d", "-p", port+":80", "busybox", "top")
  1347. out, _, err := dockerCmdWithError("run", "-d", "-p", port+":80", "busybox", "top")
  1348. if err == nil {
  1349. c.Fatalf("Binding on used port must fail")
  1350. }
  1351. if !strings.Contains(out, "port is already allocated") {
  1352. c.Fatalf("Out must be about \"port is already allocated\", got %s", out)
  1353. }
  1354. }
  1355. // https://github.com/docker/docker/issues/12148
  1356. func (s *DockerSuite) TestRunAllocatePortInReservedRange(c *check.C) {
  1357. // allocate a dynamic port to get the most recent
  1358. out, _ := dockerCmd(c, "run", "-d", "-P", "-p", "80", "busybox", "top")
  1359. id := strings.TrimSpace(out)
  1360. out, _ = dockerCmd(c, "port", id, "80")
  1361. strPort := strings.Split(strings.TrimSpace(out), ":")[1]
  1362. port, err := strconv.ParseInt(strPort, 10, 64)
  1363. if err != nil {
  1364. c.Fatalf("invalid port, got: %s, error: %s", strPort, err)
  1365. }
  1366. // allocate a static port and a dynamic port together, with static port
  1367. // takes the next recent port in dynamic port range.
  1368. dockerCmd(c, "run", "-d", "-P", "-p", "80", "-p", fmt.Sprintf("%d:8080", port+1), "busybox", "top")
  1369. }
  1370. // Regression test for #7792
  1371. func (s *DockerSuite) TestRunMountOrdering(c *check.C) {
  1372. testRequires(c, SameHostDaemon)
  1373. tmpDir, err := ioutil.TempDir("", "docker_nested_mount_test")
  1374. if err != nil {
  1375. c.Fatal(err)
  1376. }
  1377. defer os.RemoveAll(tmpDir)
  1378. tmpDir2, err := ioutil.TempDir("", "docker_nested_mount_test2")
  1379. if err != nil {
  1380. c.Fatal(err)
  1381. }
  1382. defer os.RemoveAll(tmpDir2)
  1383. // Create a temporary tmpfs mounc.
  1384. fooDir := filepath.Join(tmpDir, "foo")
  1385. if err := os.MkdirAll(filepath.Join(tmpDir, "foo"), 0755); err != nil {
  1386. c.Fatalf("failed to mkdir at %s - %s", fooDir, err)
  1387. }
  1388. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", fooDir), []byte{}, 0644); err != nil {
  1389. c.Fatal(err)
  1390. }
  1391. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir), []byte{}, 0644); err != nil {
  1392. c.Fatal(err)
  1393. }
  1394. if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir2), []byte{}, 0644); err != nil {
  1395. c.Fatal(err)
  1396. }
  1397. dockerCmd(c, "run",
  1398. "-v", fmt.Sprintf("%s:/tmp", tmpDir),
  1399. "-v", fmt.Sprintf("%s:/tmp/foo", fooDir),
  1400. "-v", fmt.Sprintf("%s:/tmp/tmp2", tmpDir2),
  1401. "-v", fmt.Sprintf("%s:/tmp/tmp2/foo", fooDir),
  1402. "busybox:latest", "sh", "-c",
  1403. "ls /tmp/touch-me && ls /tmp/foo/touch-me && ls /tmp/tmp2/touch-me && ls /tmp/tmp2/foo/touch-me")
  1404. }
  1405. // Regression test for https://github.com/docker/docker/issues/8259
  1406. func (s *DockerSuite) TestRunReuseBindVolumeThatIsSymlink(c *check.C) {
  1407. testRequires(c, SameHostDaemon)
  1408. tmpDir, err := ioutil.TempDir(os.TempDir(), "testlink")
  1409. if err != nil {
  1410. c.Fatal(err)
  1411. }
  1412. defer os.RemoveAll(tmpDir)
  1413. linkPath := os.TempDir() + "/testlink2"
  1414. if err := os.Symlink(tmpDir, linkPath); err != nil {
  1415. c.Fatal(err)
  1416. }
  1417. defer os.RemoveAll(linkPath)
  1418. // Create first container
  1419. dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
  1420. // Create second container with same symlinked path
  1421. // This will fail if the referenced issue is hit with a "Volume exists" error
  1422. dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
  1423. }
  1424. //GH#10604: Test an "/etc" volume doesn't overlay special bind mounts in container
  1425. func (s *DockerSuite) TestRunCreateVolumeEtc(c *check.C) {
  1426. out, _ := dockerCmd(c, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf")
  1427. if !strings.Contains(out, "nameserver 127.0.0.1") {
  1428. c.Fatal("/etc volume mount hides /etc/resolv.conf")
  1429. }
  1430. out, _ = dockerCmd(c, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname")
  1431. if !strings.Contains(out, "test123") {
  1432. c.Fatal("/etc volume mount hides /etc/hostname")
  1433. }
  1434. out, _ = dockerCmd(c, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts")
  1435. out = strings.Replace(out, "\n", " ", -1)
  1436. if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") {
  1437. c.Fatal("/etc volume mount hides /etc/hosts")
  1438. }
  1439. }
  1440. func (s *DockerSuite) TestVolumesNoCopyData(c *check.C) {
  1441. if _, err := buildImage("dataimage",
  1442. `FROM busybox
  1443. RUN mkdir -p /foo
  1444. RUN touch /foo/bar`,
  1445. true); err != nil {
  1446. c.Fatal(err)
  1447. }
  1448. dockerCmd(c, "run", "--name", "test", "-v", "/foo", "busybox")
  1449. if out, _, err := dockerCmdWithError("run", "--volumes-from", "test", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") {
  1450. c.Fatalf("Data was copied on volumes-from but shouldn't be:\n%q", out)
  1451. }
  1452. tmpDir := randomUnixTmpDirPath("docker_test_bind_mount_copy_data")
  1453. if out, _, err := dockerCmdWithError("run", "-v", tmpDir+":/foo", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") {
  1454. c.Fatalf("Data was copied on bind-mount but shouldn't be:\n%q", out)
  1455. }
  1456. }
  1457. func (s *DockerSuite) TestRunNoOutputFromPullInStdout(c *check.C) {
  1458. // just run with unknown image
  1459. cmd := exec.Command(dockerBinary, "run", "asdfsg")
  1460. stdout := bytes.NewBuffer(nil)
  1461. cmd.Stdout = stdout
  1462. if err := cmd.Run(); err == nil {
  1463. c.Fatal("Run with unknown image should fail")
  1464. }
  1465. if stdout.Len() != 0 {
  1466. c.Fatalf("Stdout contains output from pull: %s", stdout)
  1467. }
  1468. }
  1469. func (s *DockerSuite) TestRunVolumesCleanPaths(c *check.C) {
  1470. if _, err := buildImage("run_volumes_clean_paths",
  1471. `FROM busybox
  1472. VOLUME /foo/`,
  1473. true); err != nil {
  1474. c.Fatal(err)
  1475. }
  1476. dockerCmd(c, "run", "-v", "/foo", "-v", "/bar/", "--name", "dark_helmet", "run_volumes_clean_paths")
  1477. out, err := inspectMountSourceField("dark_helmet", "/foo/")
  1478. if err != errMountNotFound {
  1479. c.Fatalf("Found unexpected volume entry for '/foo/' in volumes\n%q", out)
  1480. }
  1481. out, err = inspectMountSourceField("dark_helmet", "/foo")
  1482. c.Assert(err, check.IsNil)
  1483. if !strings.Contains(out, volumesConfigPath) {
  1484. c.Fatalf("Volume was not defined for /foo\n%q", out)
  1485. }
  1486. out, err = inspectMountSourceField("dark_helmet", "/bar/")
  1487. if err != errMountNotFound {
  1488. c.Fatalf("Found unexpected volume entry for '/bar/' in volumes\n%q", out)
  1489. }
  1490. out, err = inspectMountSourceField("dark_helmet", "/bar")
  1491. c.Assert(err, check.IsNil)
  1492. if !strings.Contains(out, volumesConfigPath) {
  1493. c.Fatalf("Volume was not defined for /bar\n%q", out)
  1494. }
  1495. }
  1496. // Regression test for #3631
  1497. func (s *DockerSuite) TestRunSlowStdoutConsumer(c *check.C) {
  1498. cont := exec.Command(dockerBinary, "run", "--rm", "busybox", "/bin/sh", "-c", "dd if=/dev/zero of=/dev/stdout bs=1024 count=2000 | catv")
  1499. stdout, err := cont.StdoutPipe()
  1500. if err != nil {
  1501. c.Fatal(err)
  1502. }
  1503. if err := cont.Start(); err != nil {
  1504. c.Fatal(err)
  1505. }
  1506. n, err := consumeWithSpeed(stdout, 10000, 5*time.Millisecond, nil)
  1507. if err != nil {
  1508. c.Fatal(err)
  1509. }
  1510. expected := 2 * 1024 * 2000
  1511. if n != expected {
  1512. c.Fatalf("Expected %d, got %d", expected, n)
  1513. }
  1514. }
  1515. func (s *DockerSuite) TestRunAllowPortRangeThroughExpose(c *check.C) {
  1516. out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top")
  1517. id := strings.TrimSpace(out)
  1518. portstr, err := inspectFieldJSON(id, "NetworkSettings.Ports")
  1519. c.Assert(err, check.IsNil)
  1520. var ports nat.PortMap
  1521. if err = unmarshalJSON([]byte(portstr), &ports); err != nil {
  1522. c.Fatal(err)
  1523. }
  1524. for port, binding := range ports {
  1525. portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  1526. if portnum < 3000 || portnum > 3003 {
  1527. c.Fatalf("Port %d is out of range ", portnum)
  1528. }
  1529. if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  1530. c.Fatalf("Port is not mapped for the port %s", port)
  1531. }
  1532. }
  1533. }
  1534. // test docker run expose a invalid port
  1535. func (s *DockerSuite) TestRunExposePort(c *check.C) {
  1536. out, _, err := dockerCmdWithError("run", "--expose", "80000", "busybox")
  1537. //expose a invalid port should with a error out
  1538. if err == nil || !strings.Contains(out, "Invalid range format for --expose") {
  1539. c.Fatalf("run --expose a invalid port should with error out")
  1540. }
  1541. }
  1542. func (s *DockerSuite) TestRunUnknownCommand(c *check.C) {
  1543. testRequires(c, NativeExecDriver)
  1544. out, _, _ := dockerCmdWithStdoutStderr(c, "create", "busybox", "/bin/nada")
  1545. cID := strings.TrimSpace(out)
  1546. _, _, err := dockerCmdWithError("start", cID)
  1547. c.Assert(err, check.NotNil)
  1548. rc, err := inspectField(cID, "State.ExitCode")
  1549. c.Assert(err, check.IsNil)
  1550. if rc == "0" {
  1551. c.Fatalf("ExitCode(%v) cannot be 0", rc)
  1552. }
  1553. }
  1554. func (s *DockerSuite) TestRunModeIpcHost(c *check.C) {
  1555. testRequires(c, SameHostDaemon)
  1556. hostIpc, err := os.Readlink("/proc/1/ns/ipc")
  1557. if err != nil {
  1558. c.Fatal(err)
  1559. }
  1560. out, _ := dockerCmd(c, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc")
  1561. out = strings.Trim(out, "\n")
  1562. if hostIpc != out {
  1563. c.Fatalf("IPC different with --ipc=host %s != %s\n", hostIpc, out)
  1564. }
  1565. out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/ipc")
  1566. out = strings.Trim(out, "\n")
  1567. if hostIpc == out {
  1568. c.Fatalf("IPC should be different without --ipc=host %s == %s\n", hostIpc, out)
  1569. }
  1570. }
  1571. func (s *DockerSuite) TestRunModeIpcContainer(c *check.C) {
  1572. testRequires(c, SameHostDaemon)
  1573. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1574. id := strings.TrimSpace(out)
  1575. state, err := inspectField(id, "State.Running")
  1576. c.Assert(err, check.IsNil)
  1577. if state != "true" {
  1578. c.Fatal("Container state is 'not running'")
  1579. }
  1580. pid1, err := inspectField(id, "State.Pid")
  1581. c.Assert(err, check.IsNil)
  1582. parentContainerIpc, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/ipc", pid1))
  1583. if err != nil {
  1584. c.Fatal(err)
  1585. }
  1586. out, _ = dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "readlink", "/proc/self/ns/ipc")
  1587. out = strings.Trim(out, "\n")
  1588. if parentContainerIpc != out {
  1589. c.Fatalf("IPC different with --ipc=container:%s %s != %s\n", id, parentContainerIpc, out)
  1590. }
  1591. }
  1592. func (s *DockerSuite) TestRunModeIpcContainerNotExists(c *check.C) {
  1593. out, _, err := dockerCmdWithError("run", "-d", "--ipc", "container:abcd1234", "busybox", "top")
  1594. if !strings.Contains(out, "abcd1234") || err == nil {
  1595. c.Fatalf("run IPC from a non exists container should with correct error out")
  1596. }
  1597. }
  1598. func (s *DockerSuite) TestRunModeIpcContainerNotRunning(c *check.C) {
  1599. testRequires(c, SameHostDaemon)
  1600. out, _ := dockerCmd(c, "create", "busybox")
  1601. id := strings.TrimSpace(out)
  1602. out, _, err := dockerCmdWithError("run", fmt.Sprintf("--ipc=container:%s", id), "busybox")
  1603. if err == nil {
  1604. c.Fatalf("Run container with ipc mode container should fail with non running container: %s\n%s", out, err)
  1605. }
  1606. }
  1607. func (s *DockerSuite) TestContainerNetworkMode(c *check.C) {
  1608. testRequires(c, SameHostDaemon)
  1609. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1610. id := strings.TrimSpace(out)
  1611. c.Assert(waitRun(id), check.IsNil)
  1612. pid1, err := inspectField(id, "State.Pid")
  1613. c.Assert(err, check.IsNil)
  1614. parentContainerNet, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
  1615. if err != nil {
  1616. c.Fatal(err)
  1617. }
  1618. out, _ = dockerCmd(c, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net")
  1619. out = strings.Trim(out, "\n")
  1620. if parentContainerNet != out {
  1621. c.Fatalf("NET different with --net=container:%s %s != %s\n", id, parentContainerNet, out)
  1622. }
  1623. }
  1624. func (s *DockerSuite) TestRunModePidHost(c *check.C) {
  1625. testRequires(c, NativeExecDriver, SameHostDaemon)
  1626. hostPid, err := os.Readlink("/proc/1/ns/pid")
  1627. if err != nil {
  1628. c.Fatal(err)
  1629. }
  1630. out, _ := dockerCmd(c, "run", "--pid=host", "busybox", "readlink", "/proc/self/ns/pid")
  1631. out = strings.Trim(out, "\n")
  1632. if hostPid != out {
  1633. c.Fatalf("PID different with --pid=host %s != %s\n", hostPid, out)
  1634. }
  1635. out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/pid")
  1636. out = strings.Trim(out, "\n")
  1637. if hostPid == out {
  1638. c.Fatalf("PID should be different without --pid=host %s == %s\n", hostPid, out)
  1639. }
  1640. }
  1641. func (s *DockerSuite) TestRunModeUTSHost(c *check.C) {
  1642. testRequires(c, NativeExecDriver, SameHostDaemon)
  1643. hostUTS, err := os.Readlink("/proc/1/ns/uts")
  1644. if err != nil {
  1645. c.Fatal(err)
  1646. }
  1647. out, _ := dockerCmd(c, "run", "--uts=host", "busybox", "readlink", "/proc/self/ns/uts")
  1648. out = strings.Trim(out, "\n")
  1649. if hostUTS != out {
  1650. c.Fatalf("UTS different with --uts=host %s != %s\n", hostUTS, out)
  1651. }
  1652. out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/uts")
  1653. out = strings.Trim(out, "\n")
  1654. if hostUTS == out {
  1655. c.Fatalf("UTS should be different without --uts=host %s == %s\n", hostUTS, out)
  1656. }
  1657. }
  1658. func (s *DockerSuite) TestRunTLSverify(c *check.C) {
  1659. if out, code, err := dockerCmdWithError("ps"); err != nil || code != 0 {
  1660. c.Fatalf("Should have worked: %v:\n%v", err, out)
  1661. }
  1662. // Regardless of whether we specify true or false we need to
  1663. // test to make sure tls is turned on if --tlsverify is specified at all
  1664. out, code, err := dockerCmdWithError("--tlsverify=false", "ps")
  1665. if err == nil || code == 0 || !strings.Contains(out, "trying to connect") {
  1666. c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err)
  1667. }
  1668. out, code, err = dockerCmdWithError("--tlsverify=true", "ps")
  1669. if err == nil || code == 0 || !strings.Contains(out, "cert") {
  1670. c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err)
  1671. }
  1672. }
  1673. func (s *DockerSuite) TestRunPortFromDockerRangeInUse(c *check.C) {
  1674. // first find allocator current position
  1675. out, _ := dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
  1676. id := strings.TrimSpace(out)
  1677. out, _ = dockerCmd(c, "port", id)
  1678. out = strings.TrimSpace(out)
  1679. if out == "" {
  1680. c.Fatal("docker port command output is empty")
  1681. }
  1682. out = strings.Split(out, ":")[1]
  1683. lastPort, err := strconv.Atoi(out)
  1684. if err != nil {
  1685. c.Fatal(err)
  1686. }
  1687. port := lastPort + 1
  1688. l, err := net.Listen("tcp", ":"+strconv.Itoa(port))
  1689. if err != nil {
  1690. c.Fatal(err)
  1691. }
  1692. defer l.Close()
  1693. out, _ = dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
  1694. id = strings.TrimSpace(out)
  1695. dockerCmd(c, "port", id)
  1696. }
  1697. func (s *DockerSuite) TestRunTtyWithPipe(c *check.C) {
  1698. errChan := make(chan error)
  1699. go func() {
  1700. defer close(errChan)
  1701. cmd := exec.Command(dockerBinary, "run", "-ti", "busybox", "true")
  1702. if _, err := cmd.StdinPipe(); err != nil {
  1703. errChan <- err
  1704. return
  1705. }
  1706. expected := "cannot enable tty mode"
  1707. if out, _, err := runCommandWithOutput(cmd); err == nil {
  1708. errChan <- fmt.Errorf("run should have failed")
  1709. return
  1710. } else if !strings.Contains(out, expected) {
  1711. errChan <- fmt.Errorf("run failed with error %q: expected %q", out, expected)
  1712. return
  1713. }
  1714. }()
  1715. select {
  1716. case err := <-errChan:
  1717. c.Assert(err, check.IsNil)
  1718. case <-time.After(3 * time.Second):
  1719. c.Fatal("container is running but should have failed")
  1720. }
  1721. }
  1722. func (s *DockerSuite) TestRunNonLocalMacAddress(c *check.C) {
  1723. addr := "00:16:3E:08:00:50"
  1724. if out, _ := dockerCmd(c, "run", "--mac-address", addr, "busybox", "ifconfig"); !strings.Contains(out, addr) {
  1725. c.Fatalf("Output should have contained %q: %s", addr, out)
  1726. }
  1727. }
  1728. func (s *DockerSuite) TestRunNetHost(c *check.C) {
  1729. testRequires(c, SameHostDaemon)
  1730. hostNet, err := os.Readlink("/proc/1/ns/net")
  1731. if err != nil {
  1732. c.Fatal(err)
  1733. }
  1734. out, _ := dockerCmd(c, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net")
  1735. out = strings.Trim(out, "\n")
  1736. if hostNet != out {
  1737. c.Fatalf("Net namespace different with --net=host %s != %s\n", hostNet, out)
  1738. }
  1739. out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/net")
  1740. out = strings.Trim(out, "\n")
  1741. if hostNet == out {
  1742. c.Fatalf("Net namespace should be different without --net=host %s == %s\n", hostNet, out)
  1743. }
  1744. }
  1745. func (s *DockerSuite) TestRunNetHostTwiceSameName(c *check.C) {
  1746. testRequires(c, SameHostDaemon)
  1747. dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
  1748. dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
  1749. }
  1750. func (s *DockerSuite) TestRunNetContainerWhichHost(c *check.C) {
  1751. testRequires(c, SameHostDaemon)
  1752. hostNet, err := os.Readlink("/proc/1/ns/net")
  1753. if err != nil {
  1754. c.Fatal(err)
  1755. }
  1756. dockerCmd(c, "run", "-d", "--net=host", "--name=test", "busybox", "top")
  1757. out, _ := dockerCmd(c, "run", "--net=container:test", "busybox", "readlink", "/proc/self/ns/net")
  1758. out = strings.Trim(out, "\n")
  1759. if hostNet != out {
  1760. c.Fatalf("Container should have host network namespace")
  1761. }
  1762. }
  1763. func (s *DockerSuite) TestRunAllowPortRangeThroughPublish(c *check.C) {
  1764. out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top")
  1765. id := strings.TrimSpace(out)
  1766. portstr, err := inspectFieldJSON(id, "NetworkSettings.Ports")
  1767. c.Assert(err, check.IsNil)
  1768. var ports nat.PortMap
  1769. err = unmarshalJSON([]byte(portstr), &ports)
  1770. for port, binding := range ports {
  1771. portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  1772. if portnum < 3000 || portnum > 3003 {
  1773. c.Fatalf("Port %d is out of range ", portnum)
  1774. }
  1775. if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  1776. c.Fatal("Port is not mapped for the port "+port, out)
  1777. }
  1778. }
  1779. }
  1780. func (s *DockerSuite) TestRunSetDefaultRestartPolicy(c *check.C) {
  1781. dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")
  1782. out, err := inspectField("test", "HostConfig.RestartPolicy.Name")
  1783. c.Assert(err, check.IsNil)
  1784. if out != "no" {
  1785. c.Fatalf("Set default restart policy failed")
  1786. }
  1787. }
  1788. func (s *DockerSuite) TestRunRestartMaxRetries(c *check.C) {
  1789. out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false")
  1790. id := strings.TrimSpace(string(out))
  1791. if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", 10); err != nil {
  1792. c.Fatal(err)
  1793. }
  1794. count, err := inspectField(id, "RestartCount")
  1795. c.Assert(err, check.IsNil)
  1796. if count != "3" {
  1797. c.Fatalf("Container was restarted %s times, expected %d", count, 3)
  1798. }
  1799. MaximumRetryCount, err := inspectField(id, "HostConfig.RestartPolicy.MaximumRetryCount")
  1800. c.Assert(err, check.IsNil)
  1801. if MaximumRetryCount != "3" {
  1802. c.Fatalf("Container Maximum Retry Count is %s, expected %s", MaximumRetryCount, "3")
  1803. }
  1804. }
  1805. func (s *DockerSuite) TestRunContainerWithWritableRootfs(c *check.C) {
  1806. dockerCmd(c, "run", "--rm", "busybox", "touch", "/file")
  1807. }
  1808. func (s *DockerSuite) TestRunContainerWithReadonlyRootfs(c *check.C) {
  1809. testRequires(c, NativeExecDriver)
  1810. for _, f := range []string{"/file", "/etc/hosts", "/etc/resolv.conf", "/etc/hostname", "/sys/kernel", "/dev/.dont.touch.me"} {
  1811. testReadOnlyFile(f, c)
  1812. }
  1813. }
  1814. func (s *DockerSuite) TestPermissionsPtsReadonlyRootfs(c *check.C) {
  1815. testRequires(c, NativeExecDriver)
  1816. // Ensure we have not broken writing /dev/pts
  1817. out, status := dockerCmd(c, "run", "--read-only", "--rm", "busybox", "mount")
  1818. if status != 0 {
  1819. c.Fatal("Could not obtain mounts when checking /dev/pts mntpnt.")
  1820. }
  1821. expected := "type devpts (rw,"
  1822. if !strings.Contains(string(out), expected) {
  1823. c.Fatalf("expected output to contain %s but contains %s", expected, out)
  1824. }
  1825. }
  1826. func testReadOnlyFile(filename string, c *check.C) {
  1827. testRequires(c, NativeExecDriver)
  1828. out, _, err := dockerCmdWithError("run", "--read-only", "--rm", "busybox", "touch", filename)
  1829. if err == nil {
  1830. c.Fatal("expected container to error on run with read only error")
  1831. }
  1832. expected := "Read-only file system"
  1833. if !strings.Contains(string(out), expected) {
  1834. c.Fatalf("expected output from failure to contain %s but contains %s", expected, out)
  1835. }
  1836. out, _, err = dockerCmdWithError("run", "--read-only", "--privileged", "--rm", "busybox", "touch", filename)
  1837. if err == nil {
  1838. c.Fatal("expected container to error on run with read only error")
  1839. }
  1840. expected = "Read-only file system"
  1841. if !strings.Contains(string(out), expected) {
  1842. c.Fatalf("expected output from failure to contain %s but contains %s", expected, out)
  1843. }
  1844. }
  1845. func (s *DockerSuite) TestRunContainerWithReadonlyEtcHostsAndLinkedContainer(c *check.C) {
  1846. testRequires(c, NativeExecDriver)
  1847. dockerCmd(c, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top")
  1848. out, _ := dockerCmd(c, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts")
  1849. if !strings.Contains(string(out), "testlinked") {
  1850. c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled")
  1851. }
  1852. }
  1853. func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithDnsFlag(c *check.C) {
  1854. testRequires(c, NativeExecDriver)
  1855. out, _ := dockerCmd(c, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf")
  1856. if !strings.Contains(string(out), "1.1.1.1") {
  1857. c.Fatal("Expected /etc/resolv.conf to be updated even if --read-only enabled and --dns flag used")
  1858. }
  1859. }
  1860. func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithAddHostFlag(c *check.C) {
  1861. testRequires(c, NativeExecDriver)
  1862. out, _ := dockerCmd(c, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts")
  1863. if !strings.Contains(string(out), "testreadonly") {
  1864. c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled and --add-host flag used")
  1865. }
  1866. }
  1867. func (s *DockerSuite) TestRunVolumesFromRestartAfterRemoved(c *check.C) {
  1868. dockerCmd(c, "run", "-d", "--name", "voltest", "-v", "/foo", "busybox")
  1869. dockerCmd(c, "run", "-d", "--name", "restarter", "--volumes-from", "voltest", "busybox", "top")
  1870. // Remove the main volume container and restart the consuming container
  1871. dockerCmd(c, "rm", "-f", "voltest")
  1872. // This should not fail since the volumes-from were already applied
  1873. dockerCmd(c, "restart", "restarter")
  1874. }
  1875. // run container with --rm should remove container if exit code != 0
  1876. func (s *DockerSuite) TestRunContainerWithRmFlagExitCodeNotEqualToZero(c *check.C) {
  1877. name := "flowers"
  1878. out, _, err := dockerCmdWithError("run", "--name", name, "--rm", "busybox", "ls", "/notexists")
  1879. if err == nil {
  1880. c.Fatal("Expected docker run to fail", out, err)
  1881. }
  1882. out, err = getAllContainers()
  1883. if err != nil {
  1884. c.Fatal(out, err)
  1885. }
  1886. if out != "" {
  1887. c.Fatal("Expected not to have containers", out)
  1888. }
  1889. }
  1890. func (s *DockerSuite) TestRunContainerWithRmFlagCannotStartContainer(c *check.C) {
  1891. name := "sparkles"
  1892. out, _, err := dockerCmdWithError("run", "--name", name, "--rm", "busybox", "commandNotFound")
  1893. if err == nil {
  1894. c.Fatal("Expected docker run to fail", out, err)
  1895. }
  1896. out, err = getAllContainers()
  1897. if err != nil {
  1898. c.Fatal(out, err)
  1899. }
  1900. if out != "" {
  1901. c.Fatal("Expected not to have containers", out)
  1902. }
  1903. }
  1904. func (s *DockerSuite) TestRunPidHostWithChildIsKillable(c *check.C) {
  1905. name := "ibuildthecloud"
  1906. dockerCmd(c, "run", "-d", "--pid=host", "--name", name, "busybox", "sh", "-c", "sleep 30; echo hi")
  1907. c.Assert(waitRun(name), check.IsNil)
  1908. errchan := make(chan error)
  1909. go func() {
  1910. if out, _, err := dockerCmdWithError("kill", name); err != nil {
  1911. errchan <- fmt.Errorf("%v:\n%s", err, out)
  1912. }
  1913. close(errchan)
  1914. }()
  1915. select {
  1916. case err := <-errchan:
  1917. c.Assert(err, check.IsNil)
  1918. case <-time.After(5 * time.Second):
  1919. c.Fatal("Kill container timed out")
  1920. }
  1921. }
  1922. func (s *DockerSuite) TestRunWithTooSmallMemoryLimit(c *check.C) {
  1923. // this memory limit is 1 byte less than the min, which is 4MB
  1924. // https://github.com/docker/docker/blob/v1.5.0/daemon/create.go#L22
  1925. out, _, err := dockerCmdWithError("run", "-m", "4194303", "busybox")
  1926. if err == nil || !strings.Contains(out, "Minimum memory limit allowed is 4MB") {
  1927. c.Fatalf("expected run to fail when using too low a memory limit: %q", out)
  1928. }
  1929. }
  1930. func (s *DockerSuite) TestRunWriteToProcAsound(c *check.C) {
  1931. _, code, err := dockerCmdWithError("run", "busybox", "sh", "-c", "echo 111 >> /proc/asound/version")
  1932. if err == nil || code == 0 {
  1933. c.Fatal("standard container should not be able to write to /proc/asound")
  1934. }
  1935. }
  1936. func (s *DockerSuite) TestRunReadProcTimer(c *check.C) {
  1937. testRequires(c, NativeExecDriver)
  1938. out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/timer_stats")
  1939. if code != 0 {
  1940. return
  1941. }
  1942. if err != nil {
  1943. c.Fatal(err)
  1944. }
  1945. if strings.Trim(out, "\n ") != "" {
  1946. c.Fatalf("expected to receive no output from /proc/timer_stats but received %q", out)
  1947. }
  1948. }
  1949. func (s *DockerSuite) TestRunReadProcLatency(c *check.C) {
  1950. testRequires(c, NativeExecDriver)
  1951. // some kernels don't have this configured so skip the test if this file is not found
  1952. // on the host running the tests.
  1953. if _, err := os.Stat("/proc/latency_stats"); err != nil {
  1954. c.Skip("kernel doesnt have latency_stats configured")
  1955. return
  1956. }
  1957. out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/latency_stats")
  1958. if code != 0 {
  1959. return
  1960. }
  1961. if err != nil {
  1962. c.Fatal(err)
  1963. }
  1964. if strings.Trim(out, "\n ") != "" {
  1965. c.Fatalf("expected to receive no output from /proc/latency_stats but received %q", out)
  1966. }
  1967. }
  1968. func (s *DockerSuite) TestRunReadFilteredProc(c *check.C) {
  1969. testRequires(c, Apparmor)
  1970. testReadPaths := []string{
  1971. "/proc/latency_stats",
  1972. "/proc/timer_stats",
  1973. "/proc/kcore",
  1974. }
  1975. for i, filePath := range testReadPaths {
  1976. name := fmt.Sprintf("procsieve-%d", i)
  1977. shellCmd := fmt.Sprintf("exec 3<%s", filePath)
  1978. out, exitCode, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor:docker-default", "--name", name, "busybox", "sh", "-c", shellCmd)
  1979. if exitCode != 0 {
  1980. return
  1981. }
  1982. if err != nil {
  1983. c.Fatalf("Open FD for read should have failed with permission denied, got: %s, %v", out, err)
  1984. }
  1985. }
  1986. }
  1987. func (s *DockerSuite) TestMountIntoProc(c *check.C) {
  1988. testRequires(c, NativeExecDriver)
  1989. _, code, err := dockerCmdWithError("run", "-v", "/proc//sys", "busybox", "true")
  1990. if err == nil || code == 0 {
  1991. c.Fatal("container should not be able to mount into /proc")
  1992. }
  1993. }
  1994. func (s *DockerSuite) TestMountIntoSys(c *check.C) {
  1995. testRequires(c, NativeExecDriver)
  1996. dockerCmd(c, "run", "-v", "/sys/fs/cgroup", "busybox", "true")
  1997. }
  1998. func (s *DockerSuite) TestRunUnshareProc(c *check.C) {
  1999. testRequires(c, Apparmor, NativeExecDriver)
  2000. name := "acidburn"
  2001. if out, _, err := dockerCmdWithError("run", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "--mount-proc=/proc", "mount"); err == nil || !strings.Contains(out, "Permission denied") {
  2002. c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err)
  2003. }
  2004. name = "cereal"
  2005. if out, _, err := dockerCmdWithError("run", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc"); err == nil || !strings.Contains(out, "Permission denied") {
  2006. c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err)
  2007. }
  2008. /* Ensure still fails if running privileged with the default policy */
  2009. name = "crashoverride"
  2010. if out, _, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor:docker-default", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc"); err == nil || !strings.Contains(out, "Permission denied") {
  2011. c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err)
  2012. }
  2013. }
  2014. func (s *DockerSuite) TestRunPublishPort(c *check.C) {
  2015. dockerCmd(c, "run", "-d", "--name", "test", "--expose", "8080", "busybox", "top")
  2016. out, _ := dockerCmd(c, "port", "test")
  2017. out = strings.Trim(out, "\r\n")
  2018. if out != "" {
  2019. c.Fatalf("run without --publish-all should not publish port, out should be nil, but got: %s", out)
  2020. }
  2021. }
  2022. // Issue #10184.
  2023. func (s *DockerSuite) TestDevicePermissions(c *check.C) {
  2024. testRequires(c, NativeExecDriver)
  2025. const permissions = "crw-rw-rw-"
  2026. out, status := dockerCmd(c, "run", "--device", "/dev/fuse:/dev/fuse:mrw", "busybox:latest", "ls", "-l", "/dev/fuse")
  2027. if status != 0 {
  2028. c.Fatalf("expected status 0, got %d", status)
  2029. }
  2030. if !strings.HasPrefix(out, permissions) {
  2031. c.Fatalf("output should begin with %q, got %q", permissions, out)
  2032. }
  2033. }
  2034. func (s *DockerSuite) TestRunCapAddCHOWN(c *check.C) {
  2035. testRequires(c, NativeExecDriver)
  2036. out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok")
  2037. if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  2038. c.Fatalf("expected output ok received %s", actual)
  2039. }
  2040. }
  2041. // https://github.com/docker/docker/pull/14498
  2042. func (s *DockerSuite) TestVolumeFromMixedRWOptions(c *check.C) {
  2043. dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true")
  2044. dockerCmd(c, "run", "--volumes-from", "parent:ro", "--name", "test-volumes-1", "busybox", "true")
  2045. dockerCmd(c, "run", "--volumes-from", "parent:rw", "--name", "test-volumes-2", "busybox", "true")
  2046. mRO, err := inspectMountPoint("test-volumes-1", "/test")
  2047. c.Assert(err, check.IsNil)
  2048. if mRO.RW {
  2049. c.Fatalf("Expected RO volume was RW")
  2050. }
  2051. mRW, err := inspectMountPoint("test-volumes-2", "/test")
  2052. c.Assert(err, check.IsNil)
  2053. if !mRW.RW {
  2054. c.Fatalf("Expected RW volume was RO")
  2055. }
  2056. }
  2057. func (s *DockerSuite) TestRunWriteFilteredProc(c *check.C) {
  2058. testRequires(c, Apparmor, NativeExecDriver)
  2059. testWritePaths := []string{
  2060. /* modprobe and core_pattern should both be denied by generic
  2061. * policy of denials for /proc/sys/kernel. These files have been
  2062. * picked to be checked as they are particularly sensitive to writes */
  2063. "/proc/sys/kernel/modprobe",
  2064. "/proc/sys/kernel/core_pattern",
  2065. "/proc/sysrq-trigger",
  2066. "/proc/kcore",
  2067. }
  2068. for i, filePath := range testWritePaths {
  2069. name := fmt.Sprintf("writeprocsieve-%d", i)
  2070. shellCmd := fmt.Sprintf("exec 3>%s", filePath)
  2071. out, code, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor:docker-default", "--name", name, "busybox", "sh", "-c", shellCmd)
  2072. if code != 0 {
  2073. return
  2074. }
  2075. if err != nil {
  2076. c.Fatalf("Open FD for write should have failed with permission denied, got: %s, %v", out, err)
  2077. }
  2078. }
  2079. }
  2080. func (s *DockerSuite) TestRunNetworkFilesBindMount(c *check.C) {
  2081. testRequires(c, SameHostDaemon)
  2082. expected := "test123"
  2083. filename := createTmpFile(c, expected)
  2084. defer os.Remove(filename)
  2085. nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  2086. for i := range nwfiles {
  2087. actual, _ := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "busybox", "cat", nwfiles[i])
  2088. if actual != expected {
  2089. c.Fatalf("expected %s be: %q, but was: %q", nwfiles[i], expected, actual)
  2090. }
  2091. }
  2092. }
  2093. func (s *DockerSuite) TestRunNetworkFilesBindMountRO(c *check.C) {
  2094. testRequires(c, SameHostDaemon)
  2095. filename := createTmpFile(c, "test123")
  2096. defer os.Remove(filename)
  2097. nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  2098. for i := range nwfiles {
  2099. _, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "busybox", "touch", nwfiles[i])
  2100. if err == nil || exitCode == 0 {
  2101. c.Fatalf("run should fail because bind mount of %s is ro: exit code %d", nwfiles[i], exitCode)
  2102. }
  2103. }
  2104. }
  2105. func (s *DockerSuite) TestRunNetworkFilesBindMountROFilesystem(c *check.C) {
  2106. testRequires(c, SameHostDaemon)
  2107. filename := createTmpFile(c, "test123")
  2108. defer os.Remove(filename)
  2109. nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  2110. for i := range nwfiles {
  2111. _, exitCode := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "--read-only", "busybox", "touch", nwfiles[i])
  2112. if exitCode != 0 {
  2113. c.Fatalf("run should not fail because %s is mounted writable on read-only root filesystem: exit code %d", nwfiles[i], exitCode)
  2114. }
  2115. }
  2116. for i := range nwfiles {
  2117. _, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "--read-only", "busybox", "touch", nwfiles[i])
  2118. if err == nil || exitCode == 0 {
  2119. c.Fatalf("run should fail because %s is mounted read-only on read-only root filesystem: exit code %d", nwfiles[i], exitCode)
  2120. }
  2121. }
  2122. }
  2123. func (s *DockerTrustSuite) TestTrustedRun(c *check.C) {
  2124. repoName := s.setupTrustedImage(c, "trusted-run")
  2125. // Try run
  2126. runCmd := exec.Command(dockerBinary, "run", repoName)
  2127. s.trustedCmd(runCmd)
  2128. out, _, err := runCommandWithOutput(runCmd)
  2129. if err != nil {
  2130. c.Fatalf("Error running trusted run: %s\n%s\n", err, out)
  2131. }
  2132. if !strings.Contains(string(out), "Tagging") {
  2133. c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2134. }
  2135. dockerCmd(c, "rmi", repoName)
  2136. // Try untrusted run to ensure we pushed the tag to the registry
  2137. runCmd = exec.Command(dockerBinary, "run", "--disable-content-trust=true", repoName)
  2138. s.trustedCmd(runCmd)
  2139. out, _, err = runCommandWithOutput(runCmd)
  2140. if err != nil {
  2141. c.Fatalf("Error running trusted run: %s\n%s", err, out)
  2142. }
  2143. if !strings.Contains(string(out), "Status: Downloaded") {
  2144. c.Fatalf("Missing expected output on trusted run with --disable-content-trust:\n%s", out)
  2145. }
  2146. }
  2147. func (s *DockerTrustSuite) TestUntrustedRun(c *check.C) {
  2148. repoName := fmt.Sprintf("%v/dockercli/trusted:latest", privateRegistryURL)
  2149. // tag the image and upload it to the private registry
  2150. dockerCmd(c, "tag", "busybox", repoName)
  2151. dockerCmd(c, "push", repoName)
  2152. dockerCmd(c, "rmi", repoName)
  2153. // Try trusted run on untrusted tag
  2154. runCmd := exec.Command(dockerBinary, "run", repoName)
  2155. s.trustedCmd(runCmd)
  2156. out, _, err := runCommandWithOutput(runCmd)
  2157. if err == nil {
  2158. c.Fatalf("Error expected when running trusted run with:\n%s", out)
  2159. }
  2160. if !strings.Contains(string(out), "no trust data available") {
  2161. c.Fatalf("Missing expected output on trusted run:\n%s", out)
  2162. }
  2163. }
  2164. func (s *DockerTrustSuite) TestRunWhenCertExpired(c *check.C) {
  2165. c.Skip("Currently changes system time, causing instability")
  2166. repoName := s.setupTrustedImage(c, "trusted-run-expired")
  2167. // Certificates have 10 years of expiration
  2168. elevenYearsFromNow := time.Now().Add(time.Hour * 24 * 365 * 11)
  2169. runAtDifferentDate(elevenYearsFromNow, func() {
  2170. // Try run
  2171. runCmd := exec.Command(dockerBinary, "run", repoName)
  2172. s.trustedCmd(runCmd)
  2173. out, _, err := runCommandWithOutput(runCmd)
  2174. if err == nil {
  2175. c.Fatalf("Error running trusted run in the distant future: %s\n%s", err, out)
  2176. }
  2177. if !strings.Contains(string(out), "could not validate the path to a trusted root") {
  2178. c.Fatalf("Missing expected output on trusted run in the distant future:\n%s", out)
  2179. }
  2180. })
  2181. runAtDifferentDate(elevenYearsFromNow, func() {
  2182. // Try run
  2183. runCmd := exec.Command(dockerBinary, "run", "--disable-content-trust", repoName)
  2184. s.trustedCmd(runCmd)
  2185. out, _, err := runCommandWithOutput(runCmd)
  2186. if err != nil {
  2187. c.Fatalf("Error running untrusted run in the distant future: %s\n%s", err, out)
  2188. }
  2189. if !strings.Contains(string(out), "Status: Downloaded") {
  2190. c.Fatalf("Missing expected output on untrusted run in the distant future:\n%s", out)
  2191. }
  2192. })
  2193. }
  2194. func (s *DockerTrustSuite) TestTrustedRunFromBadTrustServer(c *check.C) {
  2195. repoName := fmt.Sprintf("%v/dockerclievilrun/trusted:latest", privateRegistryURL)
  2196. evilLocalConfigDir, err := ioutil.TempDir("", "evil-local-config-dir")
  2197. if err != nil {
  2198. c.Fatalf("Failed to create local temp dir")
  2199. }
  2200. // tag the image and upload it to the private registry
  2201. dockerCmd(c, "tag", "busybox", repoName)
  2202. pushCmd := exec.Command(dockerBinary, "push", repoName)
  2203. s.trustedCmd(pushCmd)
  2204. out, _, err := runCommandWithOutput(pushCmd)
  2205. if err != nil {
  2206. c.Fatalf("Error running trusted push: %s\n%s", err, out)
  2207. }
  2208. if !strings.Contains(string(out), "Signing and pushing trust metadata") {
  2209. c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2210. }
  2211. dockerCmd(c, "rmi", repoName)
  2212. // Try run
  2213. runCmd := exec.Command(dockerBinary, "run", repoName)
  2214. s.trustedCmd(runCmd)
  2215. out, _, err = runCommandWithOutput(runCmd)
  2216. if err != nil {
  2217. c.Fatalf("Error running trusted run: %s\n%s", err, out)
  2218. }
  2219. if !strings.Contains(string(out), "Tagging") {
  2220. c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2221. }
  2222. dockerCmd(c, "rmi", repoName)
  2223. // Kill the notary server, start a new "evil" one.
  2224. s.not.Close()
  2225. s.not, err = newTestNotary(c)
  2226. if err != nil {
  2227. c.Fatalf("Restarting notary server failed.")
  2228. }
  2229. // In order to make an evil server, lets re-init a client (with a different trust dir) and push new data.
  2230. // tag an image and upload it to the private registry
  2231. dockerCmd(c, "--config", evilLocalConfigDir, "tag", "busybox", repoName)
  2232. // Push up to the new server
  2233. pushCmd = exec.Command(dockerBinary, "--config", evilLocalConfigDir, "push", repoName)
  2234. s.trustedCmd(pushCmd)
  2235. out, _, err = runCommandWithOutput(pushCmd)
  2236. if err != nil {
  2237. c.Fatalf("Error running trusted push: %s\n%s", err, out)
  2238. }
  2239. if !strings.Contains(string(out), "Signing and pushing trust metadata") {
  2240. c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2241. }
  2242. // Now, try running with the original client from this new trust server. This should fail.
  2243. runCmd = exec.Command(dockerBinary, "run", repoName)
  2244. s.trustedCmd(runCmd)
  2245. out, _, err = runCommandWithOutput(runCmd)
  2246. if err == nil {
  2247. c.Fatalf("Expected to fail on this run due to different remote data: %s\n%s", err, out)
  2248. }
  2249. if !strings.Contains(string(out), "failed to validate data with current trusted certificates") {
  2250. c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2251. }
  2252. }
  2253. func (s *DockerSuite) TestPtraceContainerProcsFromHost(c *check.C) {
  2254. testRequires(c, SameHostDaemon)
  2255. out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  2256. id := strings.TrimSpace(out)
  2257. c.Assert(waitRun(id), check.IsNil)
  2258. pid1, err := inspectField(id, "State.Pid")
  2259. c.Assert(err, check.IsNil)
  2260. _, err = os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
  2261. if err != nil {
  2262. c.Fatal(err)
  2263. }
  2264. }
  2265. func (s *DockerSuite) TestAppArmorDeniesPtrace(c *check.C) {
  2266. testRequires(c, SameHostDaemon, NativeExecDriver, Apparmor)
  2267. // Run through 'sh' so we are NOT pid 1. Pid 1 may be able to trace
  2268. // itself, but pid>1 should not be able to trace pid1.
  2269. _, exitCode, _ := dockerCmdWithError("run", "busybox", "sh", "-c", "readlink /proc/1/ns/net")
  2270. if exitCode == 0 {
  2271. c.Fatal("ptrace was not successfully restricted by AppArmor")
  2272. }
  2273. }
  2274. func (s *DockerSuite) TestAppArmorTraceSelf(c *check.C) {
  2275. testRequires(c, SameHostDaemon)
  2276. testRequires(c, Apparmor)
  2277. _, exitCode, _ := dockerCmdWithError("run", "busybox", "readlink", "/proc/1/ns/net")
  2278. if exitCode != 0 {
  2279. c.Fatal("ptrace of self failed.")
  2280. }
  2281. }
  2282. func (s *DockerSuite) TestAppArmorDeniesChmodProc(c *check.C) {
  2283. testRequires(c, SameHostDaemon, NativeExecDriver, Apparmor)
  2284. _, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "744", "/proc/cpuinfo")
  2285. if exitCode == 0 {
  2286. // If our test failed, attempt to repair the host system...
  2287. _, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "444", "/proc/cpuinfo")
  2288. if exitCode == 0 {
  2289. c.Fatal("AppArmor was unsuccessful in prohibiting chmod of /proc/* files.")
  2290. }
  2291. }
  2292. }
  2293. func (s *DockerSuite) TestRunCapAddSYSTIME(c *check.C) {
  2294. testRequires(c, NativeExecDriver)
  2295. dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=SYS_TIME", "busybox", "sh", "-c", "grep ^CapEff /proc/self/status | sed 's/^CapEff:\t//' | grep ^0000000002000000$")
  2296. }
  2297. // run create container failed should clean up the container
  2298. func (s *DockerSuite) TestRunCreateContainerFailedCleanUp(c *check.C) {
  2299. name := "unique_name"
  2300. _, _, err := dockerCmdWithError("run", "--name", name, "--link", "nothing:nothing", "busybox")
  2301. c.Assert(err, check.Not(check.IsNil), check.Commentf("Expected docker run to fail!"))
  2302. containerID, err := inspectField(name, "Id")
  2303. c.Assert(containerID, check.Equals, "", check.Commentf("Expected not to have this container: %s!", containerID))
  2304. }