buildfile_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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, err := newTestRuntime()
  213. if err != nil {
  214. t.Fatal(err)
  215. }
  216. defer nuke(runtime)
  217. srv = &Server{
  218. runtime: runtime,
  219. pullingPool: make(map[string]struct{}),
  220. pushingPool: make(map[string]struct{}),
  221. }
  222. }
  223. httpServer, err := mkTestingFileServer(context.remoteFiles)
  224. if err != nil {
  225. t.Fatal(err)
  226. }
  227. defer httpServer.Close()
  228. idx := strings.LastIndex(httpServer.URL, ":")
  229. if idx < 0 {
  230. t.Fatalf("could not get port from test http server address %s", httpServer.URL)
  231. }
  232. port := httpServer.URL[idx+1:]
  233. ip := srv.runtime.networkManager.bridgeNetwork.IP
  234. dockerfile := constructDockerfile(context.dockerfile, ip, port)
  235. buildfile := NewBuildFile(srv, ioutil.Discard, false, useCache)
  236. id, err := buildfile.Build(mkTestContext(dockerfile, context.files, t))
  237. if err != nil {
  238. t.Fatal(err)
  239. }
  240. img, err := srv.ImageInspect(id)
  241. if err != nil {
  242. t.Fatal(err)
  243. }
  244. return img
  245. }
  246. func TestVolume(t *testing.T) {
  247. img := buildImage(testContextTemplate{`
  248. from {IMAGE}
  249. volume /test
  250. cmd Hello world
  251. `, nil, nil}, t, nil, true)
  252. if len(img.Config.Volumes) == 0 {
  253. t.Fail()
  254. }
  255. for key := range img.Config.Volumes {
  256. if key != "/test" {
  257. t.Fail()
  258. }
  259. }
  260. }
  261. func TestBuildMaintainer(t *testing.T) {
  262. img := buildImage(testContextTemplate{`
  263. from {IMAGE}
  264. maintainer dockerio
  265. `, nil, nil}, t, nil, true)
  266. if img.Author != "dockerio" {
  267. t.Fail()
  268. }
  269. }
  270. func TestBuildUser(t *testing.T) {
  271. img := buildImage(testContextTemplate{`
  272. from {IMAGE}
  273. user dockerio
  274. `, nil, nil}, t, nil, true)
  275. if img.Config.User != "dockerio" {
  276. t.Fail()
  277. }
  278. }
  279. func TestBuildEnv(t *testing.T) {
  280. img := buildImage(testContextTemplate{`
  281. from {IMAGE}
  282. env port 4243
  283. `,
  284. nil, nil}, t, nil, true)
  285. hasEnv := false
  286. for _, envVar := range img.Config.Env {
  287. if envVar == "port=4243" {
  288. hasEnv = true
  289. break
  290. }
  291. }
  292. if !hasEnv {
  293. t.Fail()
  294. }
  295. }
  296. func TestBuildCmd(t *testing.T) {
  297. img := buildImage(testContextTemplate{`
  298. from {IMAGE}
  299. cmd ["/bin/echo", "Hello World"]
  300. `,
  301. nil, nil}, t, nil, true)
  302. if img.Config.Cmd[0] != "/bin/echo" {
  303. t.Log(img.Config.Cmd[0])
  304. t.Fail()
  305. }
  306. if img.Config.Cmd[1] != "Hello World" {
  307. t.Log(img.Config.Cmd[1])
  308. t.Fail()
  309. }
  310. }
  311. func TestBuildExpose(t *testing.T) {
  312. img := buildImage(testContextTemplate{`
  313. from {IMAGE}
  314. expose 4243
  315. `,
  316. nil, nil}, t, nil, true)
  317. if img.Config.PortSpecs[0] != "4243" {
  318. t.Fail()
  319. }
  320. }
  321. func TestBuildEntrypoint(t *testing.T) {
  322. img := buildImage(testContextTemplate{`
  323. from {IMAGE}
  324. entrypoint ["/bin/echo"]
  325. `,
  326. nil, nil}, t, nil, true)
  327. if img.Config.Entrypoint[0] != "/bin/echo" {
  328. }
  329. }
  330. // testing #1405 - config.Cmd does not get cleaned up if
  331. // utilizing cache
  332. func TestBuildEntrypointRunCleanup(t *testing.T) {
  333. runtime, err := newTestRuntime()
  334. if err != nil {
  335. t.Fatal(err)
  336. }
  337. defer nuke(runtime)
  338. srv := &Server{
  339. runtime: runtime,
  340. pullingPool: make(map[string]struct{}),
  341. pushingPool: make(map[string]struct{}),
  342. }
  343. img := buildImage(testContextTemplate{`
  344. from {IMAGE}
  345. run echo "hello"
  346. `,
  347. nil, nil}, t, srv, true)
  348. img = buildImage(testContextTemplate{`
  349. from {IMAGE}
  350. run echo "hello"
  351. add foo /foo
  352. entrypoint ["/bin/echo"]
  353. `,
  354. [][2]string{{"foo", "HEYO"}}, nil}, t, srv, true)
  355. if len(img.Config.Cmd) != 0 {
  356. t.Fail()
  357. }
  358. }
  359. func TestBuildImageWithCache(t *testing.T) {
  360. runtime, err := newTestRuntime()
  361. if err != nil {
  362. t.Fatal(err)
  363. }
  364. defer nuke(runtime)
  365. srv := &Server{
  366. runtime: runtime,
  367. pullingPool: make(map[string]struct{}),
  368. pushingPool: make(map[string]struct{}),
  369. }
  370. template := testContextTemplate{`
  371. from {IMAGE}
  372. maintainer dockerio
  373. `,
  374. nil, nil}
  375. img := buildImage(template, t, srv, true)
  376. imageId := img.ID
  377. img = nil
  378. img = buildImage(template, t, srv, true)
  379. if imageId != img.ID {
  380. t.Logf("Image ids should match: %s != %s", imageId, img.ID)
  381. t.Fail()
  382. }
  383. }
  384. func TestBuildImageWithoutCache(t *testing.T) {
  385. runtime, err := newTestRuntime()
  386. if err != nil {
  387. t.Fatal(err)
  388. }
  389. defer nuke(runtime)
  390. srv := &Server{
  391. runtime: runtime,
  392. pullingPool: make(map[string]struct{}),
  393. pushingPool: make(map[string]struct{}),
  394. }
  395. template := testContextTemplate{`
  396. from {IMAGE}
  397. maintainer dockerio
  398. `,
  399. nil, nil}
  400. img := buildImage(template, t, srv, true)
  401. imageId := img.ID
  402. img = nil
  403. img = buildImage(template, t, srv, false)
  404. if imageId == img.ID {
  405. t.Logf("Image ids should not match: %s == %s", imageId, img.ID)
  406. t.Fail()
  407. }
  408. }
  409. func TestForbiddenContextPath(t *testing.T) {
  410. runtime, err := newTestRuntime()
  411. if err != nil {
  412. t.Fatal(err)
  413. }
  414. defer nuke(runtime)
  415. srv := &Server{
  416. runtime: runtime,
  417. pullingPool: make(map[string]struct{}),
  418. pushingPool: make(map[string]struct{}),
  419. }
  420. context := testContextTemplate{`
  421. from {IMAGE}
  422. maintainer dockerio
  423. add ../../ test/
  424. `,
  425. [][2]string{{"test.txt", "test1"}, {"other.txt", "other"}}, nil}
  426. httpServer, err := mkTestingFileServer(context.remoteFiles)
  427. if err != nil {
  428. t.Fatal(err)
  429. }
  430. defer httpServer.Close()
  431. idx := strings.LastIndex(httpServer.URL, ":")
  432. if idx < 0 {
  433. t.Fatalf("could not get port from test http server address %s", httpServer.URL)
  434. }
  435. port := httpServer.URL[idx+1:]
  436. ip := srv.runtime.networkManager.bridgeNetwork.IP
  437. dockerfile := constructDockerfile(context.dockerfile, ip, port)
  438. buildfile := NewBuildFile(srv, ioutil.Discard, false, true)
  439. _, err = buildfile.Build(mkTestContext(dockerfile, context.files, t))
  440. if err == nil {
  441. t.Log("Error should not be nil")
  442. t.Fail()
  443. }
  444. if err.Error() != "Forbidden path: /" {
  445. t.Logf("Error message is not expected: %s", err.Error())
  446. t.Fail()
  447. }
  448. }
  449. func TestBuildADDFileNotFound(t *testing.T) {
  450. runtime, err := newTestRuntime()
  451. if err != nil {
  452. t.Fatal(err)
  453. }
  454. defer nuke(runtime)
  455. srv := &Server{
  456. runtime: runtime,
  457. pullingPool: make(map[string]struct{}),
  458. pushingPool: make(map[string]struct{}),
  459. }
  460. context := testContextTemplate{`
  461. from {IMAGE}
  462. add foo /usr/local/bar
  463. `,
  464. nil, nil}
  465. httpServer, err := mkTestingFileServer(context.remoteFiles)
  466. if err != nil {
  467. t.Fatal(err)
  468. }
  469. defer httpServer.Close()
  470. idx := strings.LastIndex(httpServer.URL, ":")
  471. if idx < 0 {
  472. t.Fatalf("could not get port from test http server address %s", httpServer.URL)
  473. }
  474. port := httpServer.URL[idx+1:]
  475. ip := srv.runtime.networkManager.bridgeNetwork.IP
  476. dockerfile := constructDockerfile(context.dockerfile, ip, port)
  477. buildfile := NewBuildFile(srv, ioutil.Discard, false, true)
  478. _, err = buildfile.Build(mkTestContext(dockerfile, context.files, t))
  479. if err == nil {
  480. t.Log("Error should not be nil")
  481. t.Fail()
  482. }
  483. if err.Error() != "foo: no such file or directory" {
  484. t.Logf("Error message is not expected: %s", err.Error())
  485. t.Fail()
  486. }
  487. }