buildfile_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. package docker
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net"
  6. "net/http"
  7. "net/http/httptest"
  8. "strings"
  9. "testing"
  10. )
  11. // mkTestContext generates a build context from the contents of the provided dockerfile.
  12. // This context is suitable for use as an argument to BuildFile.Build()
  13. func mkTestContext(dockerfile string, files [][2]string, t *testing.T) Archive {
  14. context, err := mkBuildContext(dockerfile, files)
  15. if err != nil {
  16. t.Fatal(err)
  17. }
  18. return context
  19. }
  20. // A testContextTemplate describes a build context and how to test it
  21. type testContextTemplate struct {
  22. // Contents of the Dockerfile
  23. dockerfile string
  24. // Additional files in the context, eg [][2]string{"./passwd", "gordon"}
  25. files [][2]string
  26. // Additional remote files to host on a local HTTP server.
  27. remoteFiles [][2]string
  28. }
  29. // A table of all the contexts to build and test.
  30. // A new docker runtime will be created and torn down for each context.
  31. var testContexts = []testContextTemplate{
  32. {
  33. `
  34. from {IMAGE}
  35. run sh -c 'echo root:testpass > /tmp/passwd'
  36. run mkdir -p /var/run/sshd
  37. run [ "$(cat /tmp/passwd)" = "root:testpass" ]
  38. run [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]
  39. `,
  40. nil,
  41. nil,
  42. },
  43. // Exactly the same as above, except uses a line split with a \ to test
  44. // multiline support.
  45. {
  46. `
  47. from {IMAGE}
  48. run sh -c 'echo root:testpass \
  49. > /tmp/passwd'
  50. run mkdir -p /var/run/sshd
  51. run [ "$(cat /tmp/passwd)" = "root:testpass" ]
  52. run [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]
  53. `,
  54. nil,
  55. nil,
  56. },
  57. // Line containing literal "\n"
  58. {
  59. `
  60. from {IMAGE}
  61. run sh -c 'echo root:testpass > /tmp/passwd'
  62. run echo "foo \n bar"; echo "baz"
  63. run mkdir -p /var/run/sshd
  64. run [ "$(cat /tmp/passwd)" = "root:testpass" ]
  65. run [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]
  66. `,
  67. nil,
  68. nil,
  69. },
  70. {
  71. `
  72. from {IMAGE}
  73. add foo /usr/lib/bla/bar
  74. run [ "$(cat /usr/lib/bla/bar)" = 'hello' ]
  75. add http://{SERVERADDR}/baz /usr/lib/baz/quux
  76. run [ "$(cat /usr/lib/baz/quux)" = 'world!' ]
  77. `,
  78. [][2]string{{"foo", "hello"}},
  79. [][2]string{{"/baz", "world!"}},
  80. },
  81. {
  82. `
  83. from {IMAGE}
  84. add f /
  85. run [ "$(cat /f)" = "hello" ]
  86. add f /abc
  87. run [ "$(cat /abc)" = "hello" ]
  88. add f /x/y/z
  89. run [ "$(cat /x/y/z)" = "hello" ]
  90. add f /x/y/d/
  91. run [ "$(cat /x/y/d/f)" = "hello" ]
  92. add d /
  93. run [ "$(cat /ga)" = "bu" ]
  94. add d /somewhere
  95. run [ "$(cat /somewhere/ga)" = "bu" ]
  96. add d /anotherplace/
  97. run [ "$(cat /anotherplace/ga)" = "bu" ]
  98. add d /somewheeeere/over/the/rainbooow
  99. run [ "$(cat /somewheeeere/over/the/rainbooow/ga)" = "bu" ]
  100. `,
  101. [][2]string{
  102. {"f", "hello"},
  103. {"d/ga", "bu"},
  104. },
  105. nil,
  106. },
  107. {
  108. `
  109. from {IMAGE}
  110. add http://{SERVERADDR}/x /a/b/c
  111. run [ "$(cat /a/b/c)" = "hello" ]
  112. add http://{SERVERADDR}/x?foo=bar /
  113. run [ "$(cat /x)" = "hello" ]
  114. add http://{SERVERADDR}/x /d/
  115. run [ "$(cat /d/x)" = "hello" ]
  116. add http://{SERVERADDR} /e
  117. run [ "$(cat /e)" = "blah" ]
  118. `,
  119. nil,
  120. [][2]string{{"/x", "hello"}, {"/", "blah"}},
  121. },
  122. {
  123. `
  124. from {IMAGE}
  125. env FOO BAR
  126. run [ "$FOO" = "BAR" ]
  127. `,
  128. nil,
  129. nil,
  130. },
  131. {
  132. `
  133. from {IMAGE}
  134. ENTRYPOINT /bin/echo
  135. CMD Hello world
  136. `,
  137. nil,
  138. nil,
  139. },
  140. {
  141. `
  142. from {IMAGE}
  143. VOLUME /test
  144. CMD Hello world
  145. `,
  146. nil,
  147. nil,
  148. },
  149. {
  150. `
  151. from {IMAGE}
  152. env FOO /foo/baz
  153. env BAR /bar
  154. env BAZ $BAR
  155. env FOOPATH $PATH:$FOO
  156. run [ "$BAR" = "$BAZ" ]
  157. run [ "$FOOPATH" = "$PATH:/foo/baz" ]
  158. `,
  159. nil,
  160. nil,
  161. },
  162. {
  163. `
  164. from {IMAGE}
  165. env FOO /bar
  166. env TEST testdir
  167. env BAZ /foobar
  168. add testfile $BAZ/
  169. add $TEST $FOO
  170. run [ "$(cat /foobar/testfile)" = "test1" ]
  171. run [ "$(cat /bar/withfile)" = "test2" ]
  172. `,
  173. [][2]string{
  174. {"testfile", "test1"},
  175. {"testdir/withfile", "test2"},
  176. },
  177. nil,
  178. },
  179. }
  180. // FIXME: test building with 2 successive overlapping ADD commands
  181. func constructDockerfile(template string, ip net.IP, port string) string {
  182. serverAddr := fmt.Sprintf("%s:%s", ip, port)
  183. replacer := strings.NewReplacer("{IMAGE}", unitTestImageID, "{SERVERADDR}", serverAddr)
  184. return replacer.Replace(template)
  185. }
  186. func mkTestingFileServer(files [][2]string) (*httptest.Server, error) {
  187. mux := http.NewServeMux()
  188. for _, file := range files {
  189. name, contents := file[0], file[1]
  190. mux.HandleFunc(name, func(w http.ResponseWriter, r *http.Request) {
  191. w.Write([]byte(contents))
  192. })
  193. }
  194. // This is how httptest.NewServer sets up a net.Listener, except that our listener must accept remote
  195. // connections (from the container).
  196. listener, err := net.Listen("tcp", ":0")
  197. if err != nil {
  198. return nil, err
  199. }
  200. s := httptest.NewUnstartedServer(mux)
  201. s.Listener = listener
  202. s.Start()
  203. return s, nil
  204. }
  205. func TestBuild(t *testing.T) {
  206. for _, ctx := range testContexts {
  207. buildImage(ctx, t, nil, true)
  208. }
  209. }
  210. func buildImage(context testContextTemplate, t *testing.T, srv *Server, useCache bool) *Image {
  211. if srv == nil {
  212. runtime := mkRuntime(t)
  213. defer nuke(runtime)
  214. srv = &Server{
  215. runtime: runtime,
  216. pullingPool: make(map[string]struct{}),
  217. pushingPool: make(map[string]struct{}),
  218. }
  219. }
  220. httpServer, err := mkTestingFileServer(context.remoteFiles)
  221. if err != nil {
  222. t.Fatal(err)
  223. }
  224. defer httpServer.Close()
  225. idx := strings.LastIndex(httpServer.URL, ":")
  226. if idx < 0 {
  227. t.Fatalf("could not get port from test http server address %s", httpServer.URL)
  228. }
  229. port := httpServer.URL[idx+1:]
  230. ip := srv.runtime.networkManager.bridgeNetwork.IP
  231. dockerfile := constructDockerfile(context.dockerfile, ip, port)
  232. buildfile := NewBuildFile(srv, ioutil.Discard, false, useCache, false)
  233. id, err := buildfile.Build(mkTestContext(dockerfile, context.files, t))
  234. if err != nil {
  235. t.Fatal(err)
  236. }
  237. img, err := srv.ImageInspect(id)
  238. if err != nil {
  239. t.Fatal(err)
  240. }
  241. return img
  242. }
  243. func TestVolume(t *testing.T) {
  244. img := buildImage(testContextTemplate{`
  245. from {IMAGE}
  246. volume /test
  247. cmd Hello world
  248. `, nil, nil}, t, nil, true)
  249. if len(img.Config.Volumes) == 0 {
  250. t.Fail()
  251. }
  252. for key := range img.Config.Volumes {
  253. if key != "/test" {
  254. t.Fail()
  255. }
  256. }
  257. }
  258. func TestBuildMaintainer(t *testing.T) {
  259. img := buildImage(testContextTemplate{`
  260. from {IMAGE}
  261. maintainer dockerio
  262. `, nil, nil}, t, nil, true)
  263. if img.Author != "dockerio" {
  264. t.Fail()
  265. }
  266. }
  267. func TestBuildUser(t *testing.T) {
  268. img := buildImage(testContextTemplate{`
  269. from {IMAGE}
  270. user dockerio
  271. `, nil, nil}, t, nil, true)
  272. if img.Config.User != "dockerio" {
  273. t.Fail()
  274. }
  275. }
  276. func TestBuildEnv(t *testing.T) {
  277. img := buildImage(testContextTemplate{`
  278. from {IMAGE}
  279. env port 4243
  280. `,
  281. nil, nil}, t, nil, true)
  282. hasEnv := false
  283. for _, envVar := range img.Config.Env {
  284. if envVar == "port=4243" {
  285. hasEnv = true
  286. break
  287. }
  288. }
  289. if !hasEnv {
  290. t.Fail()
  291. }
  292. }
  293. func TestBuildCmd(t *testing.T) {
  294. img := buildImage(testContextTemplate{`
  295. from {IMAGE}
  296. cmd ["/bin/echo", "Hello World"]
  297. `,
  298. nil, nil}, t, nil, true)
  299. if img.Config.Cmd[0] != "/bin/echo" {
  300. t.Log(img.Config.Cmd[0])
  301. t.Fail()
  302. }
  303. if img.Config.Cmd[1] != "Hello World" {
  304. t.Log(img.Config.Cmd[1])
  305. t.Fail()
  306. }
  307. }
  308. func TestBuildExpose(t *testing.T) {
  309. img := buildImage(testContextTemplate{`
  310. from {IMAGE}
  311. expose 4243
  312. `,
  313. nil, nil}, t, nil, true)
  314. if img.Config.PortSpecs[0] != "4243" {
  315. t.Fail()
  316. }
  317. }
  318. func TestBuildEntrypoint(t *testing.T) {
  319. img := buildImage(testContextTemplate{`
  320. from {IMAGE}
  321. entrypoint ["/bin/echo"]
  322. `,
  323. nil, nil}, t, nil, true)
  324. if img.Config.Entrypoint[0] != "/bin/echo" {
  325. }
  326. }
  327. // testing #1405 - config.Cmd does not get cleaned up if
  328. // utilizing cache
  329. func TestBuildEntrypointRunCleanup(t *testing.T) {
  330. runtime := mkRuntime(t)
  331. defer nuke(runtime)
  332. srv := &Server{
  333. runtime: runtime,
  334. pullingPool: make(map[string]struct{}),
  335. pushingPool: make(map[string]struct{}),
  336. }
  337. img := buildImage(testContextTemplate{`
  338. from {IMAGE}
  339. run echo "hello"
  340. `,
  341. nil, nil}, t, srv, true)
  342. img = buildImage(testContextTemplate{`
  343. from {IMAGE}
  344. run echo "hello"
  345. add foo /foo
  346. entrypoint ["/bin/echo"]
  347. `,
  348. [][2]string{{"foo", "HEYO"}}, nil}, t, srv, true)
  349. if len(img.Config.Cmd) != 0 {
  350. t.Fail()
  351. }
  352. }
  353. func TestBuildImageWithCache(t *testing.T) {
  354. runtime := mkRuntime(t)
  355. defer nuke(runtime)
  356. srv := &Server{
  357. runtime: runtime,
  358. pullingPool: make(map[string]struct{}),
  359. pushingPool: make(map[string]struct{}),
  360. }
  361. template := testContextTemplate{`
  362. from {IMAGE}
  363. maintainer dockerio
  364. `,
  365. nil, nil}
  366. img := buildImage(template, t, srv, true)
  367. imageId := img.ID
  368. img = nil
  369. img = buildImage(template, t, srv, true)
  370. if imageId != img.ID {
  371. t.Logf("Image ids should match: %s != %s", imageId, img.ID)
  372. t.Fail()
  373. }
  374. }
  375. func TestBuildImageWithoutCache(t *testing.T) {
  376. runtime := mkRuntime(t)
  377. defer nuke(runtime)
  378. srv := &Server{
  379. runtime: runtime,
  380. pullingPool: make(map[string]struct{}),
  381. pushingPool: make(map[string]struct{}),
  382. }
  383. template := testContextTemplate{`
  384. from {IMAGE}
  385. maintainer dockerio
  386. `,
  387. nil, nil}
  388. img := buildImage(template, t, srv, true)
  389. imageId := img.ID
  390. img = nil
  391. img = buildImage(template, t, srv, false)
  392. if imageId == img.ID {
  393. t.Logf("Image ids should not match: %s == %s", imageId, img.ID)
  394. t.Fail()
  395. }
  396. }
  397. func TestForbiddenContextPath(t *testing.T) {
  398. runtime := mkRuntime(t)
  399. defer nuke(runtime)
  400. srv := &Server{
  401. runtime: runtime,
  402. pullingPool: make(map[string]struct{}),
  403. pushingPool: make(map[string]struct{}),
  404. }
  405. context := testContextTemplate{`
  406. from {IMAGE}
  407. maintainer dockerio
  408. add ../../ test/
  409. `,
  410. [][2]string{{"test.txt", "test1"}, {"other.txt", "other"}}, nil}
  411. httpServer, err := mkTestingFileServer(context.remoteFiles)
  412. if err != nil {
  413. t.Fatal(err)
  414. }
  415. defer httpServer.Close()
  416. idx := strings.LastIndex(httpServer.URL, ":")
  417. if idx < 0 {
  418. t.Fatalf("could not get port from test http server address %s", httpServer.URL)
  419. }
  420. port := httpServer.URL[idx+1:]
  421. ip := srv.runtime.networkManager.bridgeNetwork.IP
  422. dockerfile := constructDockerfile(context.dockerfile, ip, port)
  423. buildfile := NewBuildFile(srv, ioutil.Discard, false, true, false)
  424. _, err = buildfile.Build(mkTestContext(dockerfile, context.files, t))
  425. if err == nil {
  426. t.Log("Error should not be nil")
  427. t.Fail()
  428. }
  429. if err.Error() != "Forbidden path: /" {
  430. t.Logf("Error message is not expected: %s", err.Error())
  431. t.Fail()
  432. }
  433. }
  434. func TestBuildADDFileNotFound(t *testing.T) {
  435. runtime := mkRuntime(t)
  436. defer nuke(runtime)
  437. srv := &Server{
  438. runtime: runtime,
  439. pullingPool: make(map[string]struct{}),
  440. pushingPool: make(map[string]struct{}),
  441. }
  442. context := testContextTemplate{`
  443. from {IMAGE}
  444. add foo /usr/local/bar
  445. `,
  446. nil, nil}
  447. httpServer, err := mkTestingFileServer(context.remoteFiles)
  448. if err != nil {
  449. t.Fatal(err)
  450. }
  451. defer httpServer.Close()
  452. idx := strings.LastIndex(httpServer.URL, ":")
  453. if idx < 0 {
  454. t.Fatalf("could not get port from test http server address %s", httpServer.URL)
  455. }
  456. port := httpServer.URL[idx+1:]
  457. ip := srv.runtime.networkManager.bridgeNetwork.IP
  458. dockerfile := constructDockerfile(context.dockerfile, ip, port)
  459. buildfile := NewBuildFile(srv, ioutil.Discard, false, true, false)
  460. _, err = buildfile.Build(mkTestContext(dockerfile, context.files, t))
  461. if err == nil {
  462. t.Log("Error should not be nil")
  463. t.Fail()
  464. }
  465. if err.Error() != "foo: no such file or directory" {
  466. t.Logf("Error message is not expected: %s", err.Error())
  467. t.Fail()
  468. }
  469. }