api_test.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  1. package docker
  2. import (
  3. "archive/tar"
  4. "bufio"
  5. "bytes"
  6. "encoding/json"
  7. "github.com/dotcloud/docker/auth"
  8. "github.com/dotcloud/docker/registry"
  9. "github.com/dotcloud/docker/utils"
  10. "io"
  11. "net"
  12. "net/http"
  13. "net/http/httptest"
  14. "os"
  15. "path"
  16. "testing"
  17. "time"
  18. )
  19. func TestGetAuth(t *testing.T) {
  20. runtime, err := newTestRuntime()
  21. if err != nil {
  22. t.Fatal(err)
  23. }
  24. defer nuke(runtime)
  25. srv := &Server{
  26. runtime: runtime,
  27. }
  28. r := httptest.NewRecorder()
  29. authConfig := &auth.AuthConfig{
  30. Username: "utest",
  31. Password: "utest",
  32. Email: "utest@yopmail.com",
  33. }
  34. authConfigJSON, err := json.Marshal(authConfig)
  35. if err != nil {
  36. t.Fatal(err)
  37. }
  38. req, err := http.NewRequest("POST", "/auth", bytes.NewReader(authConfigJSON))
  39. if err != nil {
  40. t.Fatal(err)
  41. }
  42. if err := postAuth(srv, APIVERSION, r, req, nil); err != nil {
  43. t.Fatal(err)
  44. }
  45. if r.Code != http.StatusOK && r.Code != 0 {
  46. t.Fatalf("%d OK or 0 expected, received %d\n", http.StatusOK, r.Code)
  47. }
  48. newAuthConfig := registry.NewRegistry(runtime.root).GetAuthConfig(false)
  49. if newAuthConfig.Username != authConfig.Username ||
  50. newAuthConfig.Email != authConfig.Email {
  51. t.Fatalf("The auth configuration hasn't been set correctly")
  52. }
  53. }
  54. func TestGetVersion(t *testing.T) {
  55. runtime, err := newTestRuntime()
  56. if err != nil {
  57. t.Fatal(err)
  58. }
  59. defer nuke(runtime)
  60. srv := &Server{runtime: runtime}
  61. r := httptest.NewRecorder()
  62. if err := getVersion(srv, APIVERSION, r, nil, nil); err != nil {
  63. t.Fatal(err)
  64. }
  65. v := &APIVersion{}
  66. if err = json.Unmarshal(r.Body.Bytes(), v); err != nil {
  67. t.Fatal(err)
  68. }
  69. if v.Version != VERSION {
  70. t.Errorf("Excepted version %s, %s found", VERSION, v.Version)
  71. }
  72. }
  73. func TestGetInfo(t *testing.T) {
  74. runtime, err := newTestRuntime()
  75. if err != nil {
  76. t.Fatal(err)
  77. }
  78. defer nuke(runtime)
  79. srv := &Server{runtime: runtime}
  80. r := httptest.NewRecorder()
  81. if err := getInfo(srv, APIVERSION, r, nil, nil); err != nil {
  82. t.Fatal(err)
  83. }
  84. infos := &APIInfo{}
  85. err = json.Unmarshal(r.Body.Bytes(), infos)
  86. if err != nil {
  87. t.Fatal(err)
  88. }
  89. if infos.Images != 1 {
  90. t.Errorf("Excepted images: %d, %d found", 1, infos.Images)
  91. }
  92. }
  93. func TestGetImagesJSON(t *testing.T) {
  94. runtime, err := newTestRuntime()
  95. if err != nil {
  96. t.Fatal(err)
  97. }
  98. defer nuke(runtime)
  99. srv := &Server{runtime: runtime}
  100. // all=0
  101. req, err := http.NewRequest("GET", "/images/json?all=0", nil)
  102. if err != nil {
  103. t.Fatal(err)
  104. }
  105. r := httptest.NewRecorder()
  106. if err := getImagesJSON(srv, APIVERSION, r, req, nil); err != nil {
  107. t.Fatal(err)
  108. }
  109. images := []APIImages{}
  110. if err := json.Unmarshal(r.Body.Bytes(), &images); err != nil {
  111. t.Fatal(err)
  112. }
  113. if len(images) != 1 {
  114. t.Errorf("Excepted 1 image, %d found", len(images))
  115. }
  116. if images[0].Repository != unitTestImageName {
  117. t.Errorf("Excepted image %s, %s found", unitTestImageName, images[0].Repository)
  118. }
  119. r2 := httptest.NewRecorder()
  120. // all=1
  121. req2, err := http.NewRequest("GET", "/images/json?all=true", nil)
  122. if err != nil {
  123. t.Fatal(err)
  124. }
  125. if err := getImagesJSON(srv, APIVERSION, r2, req2, nil); err != nil {
  126. t.Fatal(err)
  127. }
  128. images2 := []APIImages{}
  129. if err := json.Unmarshal(r2.Body.Bytes(), &images2); err != nil {
  130. t.Fatal(err)
  131. }
  132. if len(images2) != 1 {
  133. t.Errorf("Excepted 1 image, %d found", len(images2))
  134. }
  135. if images2[0].ID != GetTestImage(runtime).ID {
  136. t.Errorf("Retrieved image Id differs, expected %s, received %s", GetTestImage(runtime).ID, images2[0].ID)
  137. }
  138. r3 := httptest.NewRecorder()
  139. // filter=a
  140. req3, err := http.NewRequest("GET", "/images/json?filter=a", nil)
  141. if err != nil {
  142. t.Fatal(err)
  143. }
  144. if err := getImagesJSON(srv, APIVERSION, r3, req3, nil); err != nil {
  145. t.Fatal(err)
  146. }
  147. images3 := []APIImages{}
  148. if err := json.Unmarshal(r3.Body.Bytes(), &images3); err != nil {
  149. t.Fatal(err)
  150. }
  151. if len(images3) != 0 {
  152. t.Errorf("Excepted 1 image, %d found", len(images3))
  153. }
  154. r4 := httptest.NewRecorder()
  155. // all=foobar
  156. req4, err := http.NewRequest("GET", "/images/json?all=foobar", nil)
  157. if err != nil {
  158. t.Fatal(err)
  159. }
  160. err = getImagesJSON(srv, APIVERSION, r4, req4, nil)
  161. if err == nil {
  162. t.Fatalf("Error expected, received none")
  163. }
  164. httpError(r4, err)
  165. if r4.Code != http.StatusBadRequest {
  166. t.Fatalf("%d Bad Request expected, received %d\n", http.StatusBadRequest, r4.Code)
  167. }
  168. }
  169. func TestGetImagesViz(t *testing.T) {
  170. runtime, err := newTestRuntime()
  171. if err != nil {
  172. t.Fatal(err)
  173. }
  174. defer nuke(runtime)
  175. srv := &Server{runtime: runtime}
  176. r := httptest.NewRecorder()
  177. if err := getImagesViz(srv, APIVERSION, r, nil, nil); err != nil {
  178. t.Fatal(err)
  179. }
  180. if r.Code != http.StatusOK {
  181. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  182. }
  183. reader := bufio.NewReader(r.Body)
  184. line, err := reader.ReadString('\n')
  185. if err != nil {
  186. t.Fatal(err)
  187. }
  188. if line != "digraph docker {\n" {
  189. t.Errorf("Excepted digraph docker {\n, %s found", line)
  190. }
  191. }
  192. func TestGetImagesSearch(t *testing.T) {
  193. runtime, err := newTestRuntime()
  194. if err != nil {
  195. t.Fatal(err)
  196. }
  197. defer nuke(runtime)
  198. srv := &Server{
  199. runtime: runtime,
  200. }
  201. r := httptest.NewRecorder()
  202. req, err := http.NewRequest("GET", "/images/search?term=redis", nil)
  203. if err != nil {
  204. t.Fatal(err)
  205. }
  206. if err := getImagesSearch(srv, APIVERSION, r, req, nil); err != nil {
  207. t.Fatal(err)
  208. }
  209. results := []APISearch{}
  210. if err := json.Unmarshal(r.Body.Bytes(), &results); err != nil {
  211. t.Fatal(err)
  212. }
  213. if len(results) < 2 {
  214. t.Errorf("Excepted at least 2 lines, %d found", len(results))
  215. }
  216. }
  217. func TestGetImagesHistory(t *testing.T) {
  218. runtime, err := newTestRuntime()
  219. if err != nil {
  220. t.Fatal(err)
  221. }
  222. defer nuke(runtime)
  223. srv := &Server{runtime: runtime}
  224. r := httptest.NewRecorder()
  225. if err := getImagesHistory(srv, APIVERSION, r, nil, map[string]string{"name": unitTestImageName}); err != nil {
  226. t.Fatal(err)
  227. }
  228. history := []APIHistory{}
  229. if err := json.Unmarshal(r.Body.Bytes(), &history); err != nil {
  230. t.Fatal(err)
  231. }
  232. if len(history) != 1 {
  233. t.Errorf("Excepted 1 line, %d found", len(history))
  234. }
  235. }
  236. func TestGetImagesByName(t *testing.T) {
  237. runtime, err := newTestRuntime()
  238. if err != nil {
  239. t.Fatal(err)
  240. }
  241. defer nuke(runtime)
  242. srv := &Server{runtime: runtime}
  243. r := httptest.NewRecorder()
  244. if err := getImagesByName(srv, APIVERSION, r, nil, map[string]string{"name": unitTestImageName}); err != nil {
  245. t.Fatal(err)
  246. }
  247. img := &Image{}
  248. if err := json.Unmarshal(r.Body.Bytes(), img); err != nil {
  249. t.Fatal(err)
  250. }
  251. if img.ID != GetTestImage(runtime).ID || img.Comment != "Imported from http://get.docker.io/images/busybox" {
  252. t.Errorf("Error inspecting image")
  253. }
  254. }
  255. func TestGetContainersJSON(t *testing.T) {
  256. runtime, err := newTestRuntime()
  257. if err != nil {
  258. t.Fatal(err)
  259. }
  260. defer nuke(runtime)
  261. srv := &Server{runtime: runtime}
  262. container, err := NewBuilder(runtime).Create(&Config{
  263. Image: GetTestImage(runtime).ID,
  264. Cmd: []string{"echo", "test"},
  265. })
  266. if err != nil {
  267. t.Fatal(err)
  268. }
  269. defer runtime.Destroy(container)
  270. req, err := http.NewRequest("GET", "/containers/json?all=1", nil)
  271. if err != nil {
  272. t.Fatal(err)
  273. }
  274. r := httptest.NewRecorder()
  275. if err := getContainersJSON(srv, APIVERSION, r, req, nil); err != nil {
  276. t.Fatal(err)
  277. }
  278. containers := []APIContainers{}
  279. if err := json.Unmarshal(r.Body.Bytes(), &containers); err != nil {
  280. t.Fatal(err)
  281. }
  282. if len(containers) != 1 {
  283. t.Fatalf("Excepted %d container, %d found", 1, len(containers))
  284. }
  285. if containers[0].ID != container.ID {
  286. t.Fatalf("Container ID mismatch. Expected: %s, received: %s\n", container.ID, containers[0].ID)
  287. }
  288. }
  289. func TestGetContainersExport(t *testing.T) {
  290. runtime, err := newTestRuntime()
  291. if err != nil {
  292. t.Fatal(err)
  293. }
  294. defer nuke(runtime)
  295. srv := &Server{runtime: runtime}
  296. builder := NewBuilder(runtime)
  297. // Create a container and remove a file
  298. container, err := builder.Create(
  299. &Config{
  300. Image: GetTestImage(runtime).ID,
  301. Cmd: []string{"touch", "/test"},
  302. },
  303. )
  304. if err != nil {
  305. t.Fatal(err)
  306. }
  307. defer runtime.Destroy(container)
  308. if err := container.Run(); err != nil {
  309. t.Fatal(err)
  310. }
  311. r := httptest.NewRecorder()
  312. if err = getContainersExport(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  313. t.Fatal(err)
  314. }
  315. if r.Code != http.StatusOK {
  316. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  317. }
  318. found := false
  319. for tarReader := tar.NewReader(r.Body); ; {
  320. h, err := tarReader.Next()
  321. if err != nil {
  322. if err == io.EOF {
  323. break
  324. }
  325. t.Fatal(err)
  326. }
  327. if h.Name == "./test" {
  328. found = true
  329. break
  330. }
  331. }
  332. if !found {
  333. t.Fatalf("The created test file has not been found in the exported image")
  334. }
  335. }
  336. func TestGetContainersChanges(t *testing.T) {
  337. runtime, err := newTestRuntime()
  338. if err != nil {
  339. t.Fatal(err)
  340. }
  341. defer nuke(runtime)
  342. srv := &Server{runtime: runtime}
  343. builder := NewBuilder(runtime)
  344. // Create a container and remove a file
  345. container, err := builder.Create(
  346. &Config{
  347. Image: GetTestImage(runtime).ID,
  348. Cmd: []string{"/bin/rm", "/etc/passwd"},
  349. },
  350. )
  351. if err != nil {
  352. t.Fatal(err)
  353. }
  354. defer runtime.Destroy(container)
  355. if err := container.Run(); err != nil {
  356. t.Fatal(err)
  357. }
  358. r := httptest.NewRecorder()
  359. if err := getContainersChanges(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  360. t.Fatal(err)
  361. }
  362. changes := []Change{}
  363. if err := json.Unmarshal(r.Body.Bytes(), &changes); err != nil {
  364. t.Fatal(err)
  365. }
  366. // Check the changelog
  367. success := false
  368. for _, elem := range changes {
  369. if elem.Path == "/etc/passwd" && elem.Kind == 2 {
  370. success = true
  371. }
  372. }
  373. if !success {
  374. t.Fatalf("/etc/passwd as been removed but is not present in the diff")
  375. }
  376. }
  377. func TestGetContainersByName(t *testing.T) {
  378. runtime, err := newTestRuntime()
  379. if err != nil {
  380. t.Fatal(err)
  381. }
  382. defer nuke(runtime)
  383. srv := &Server{runtime: runtime}
  384. builder := NewBuilder(runtime)
  385. // Create a container and remove a file
  386. container, err := builder.Create(
  387. &Config{
  388. Image: GetTestImage(runtime).ID,
  389. Cmd: []string{"echo", "test"},
  390. },
  391. )
  392. if err != nil {
  393. t.Fatal(err)
  394. }
  395. defer runtime.Destroy(container)
  396. r := httptest.NewRecorder()
  397. if err := getContainersByName(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  398. t.Fatal(err)
  399. }
  400. outContainer := &Container{}
  401. if err := json.Unmarshal(r.Body.Bytes(), outContainer); err != nil {
  402. t.Fatal(err)
  403. }
  404. if outContainer.ID != container.ID {
  405. t.Fatalf("Wrong containers retrieved. Expected %s, recieved %s", container.ID, outContainer.ID)
  406. }
  407. }
  408. func TestPostAuth(t *testing.T) {
  409. runtime, err := newTestRuntime()
  410. if err != nil {
  411. t.Fatal(err)
  412. }
  413. defer nuke(runtime)
  414. srv := &Server{
  415. runtime: runtime,
  416. }
  417. config := &auth.AuthConfig{
  418. Username: "utest",
  419. Email: "utest@yopmail.com",
  420. }
  421. authStr := auth.EncodeAuth(config)
  422. auth.SaveConfig(runtime.root, authStr, config.Email)
  423. r := httptest.NewRecorder()
  424. if err := getAuth(srv, APIVERSION, r, nil, nil); err != nil {
  425. t.Fatal(err)
  426. }
  427. authConfig := &auth.AuthConfig{}
  428. if err := json.Unmarshal(r.Body.Bytes(), authConfig); err != nil {
  429. t.Fatal(err)
  430. }
  431. if authConfig.Username != config.Username || authConfig.Email != config.Email {
  432. t.Errorf("The retrieve auth mismatch with the one set.")
  433. }
  434. }
  435. func TestPostCommit(t *testing.T) {
  436. runtime, err := newTestRuntime()
  437. if err != nil {
  438. t.Fatal(err)
  439. }
  440. defer nuke(runtime)
  441. srv := &Server{runtime: runtime}
  442. builder := NewBuilder(runtime)
  443. // Create a container and remove a file
  444. container, err := builder.Create(
  445. &Config{
  446. Image: GetTestImage(runtime).ID,
  447. Cmd: []string{"touch", "/test"},
  448. },
  449. )
  450. if err != nil {
  451. t.Fatal(err)
  452. }
  453. defer runtime.Destroy(container)
  454. if err := container.Run(); err != nil {
  455. t.Fatal(err)
  456. }
  457. req, err := http.NewRequest("POST", "/commit?repo=testrepo&testtag=tag&container="+container.ID, bytes.NewReader([]byte{}))
  458. if err != nil {
  459. t.Fatal(err)
  460. }
  461. r := httptest.NewRecorder()
  462. if err := postCommit(srv, APIVERSION, r, req, nil); err != nil {
  463. t.Fatal(err)
  464. }
  465. if r.Code != http.StatusCreated {
  466. t.Fatalf("%d Created expected, received %d\n", http.StatusCreated, r.Code)
  467. }
  468. apiID := &APIID{}
  469. if err := json.Unmarshal(r.Body.Bytes(), apiID); err != nil {
  470. t.Fatal(err)
  471. }
  472. if _, err := runtime.graph.Get(apiID.ID); err != nil {
  473. t.Fatalf("The image has not been commited")
  474. }
  475. }
  476. func TestPostImagesCreate(t *testing.T) {
  477. // FIXME: Use the staging in order to perform tests
  478. // runtime, err := newTestRuntime()
  479. // if err != nil {
  480. // t.Fatal(err)
  481. // }
  482. // defer nuke(runtime)
  483. // srv := &Server{runtime: runtime}
  484. // stdin, stdinPipe := io.Pipe()
  485. // stdout, stdoutPipe := io.Pipe()
  486. // c1 := make(chan struct{})
  487. // go func() {
  488. // defer close(c1)
  489. // r := &hijackTester{
  490. // ResponseRecorder: httptest.NewRecorder(),
  491. // in: stdin,
  492. // out: stdoutPipe,
  493. // }
  494. // req, err := http.NewRequest("POST", "/images/create?fromImage="+unitTestImageName, bytes.NewReader([]byte{}))
  495. // if err != nil {
  496. // t.Fatal(err)
  497. // }
  498. // body, err := postImagesCreate(srv, r, req, nil)
  499. // if err != nil {
  500. // t.Fatal(err)
  501. // }
  502. // if body != nil {
  503. // t.Fatalf("No body expected, received: %s\n", body)
  504. // }
  505. // }()
  506. // // Acknowledge hijack
  507. // setTimeout(t, "hijack acknowledge timed out", 2*time.Second, func() {
  508. // stdout.Read([]byte{})
  509. // stdout.Read(make([]byte, 4096))
  510. // })
  511. // setTimeout(t, "Waiting for imagesCreate output", 5*time.Second, func() {
  512. // reader := bufio.NewReader(stdout)
  513. // line, err := reader.ReadString('\n')
  514. // if err != nil {
  515. // t.Fatal(err)
  516. // }
  517. // if !strings.HasPrefix(line, "Pulling repository d from") {
  518. // t.Fatalf("Expected Pulling repository docker-ut from..., found %s", line)
  519. // }
  520. // })
  521. // // Close pipes (client disconnects)
  522. // if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  523. // t.Fatal(err)
  524. // }
  525. // // Wait for imagesCreate to finish, the client disconnected, therefore, Create finished his job
  526. // setTimeout(t, "Waiting for imagesCreate timed out", 10*time.Second, func() {
  527. // <-c1
  528. // })
  529. }
  530. func TestPostImagesInsert(t *testing.T) {
  531. // runtime, err := newTestRuntime()
  532. // if err != nil {
  533. // t.Fatal(err)
  534. // }
  535. // defer nuke(runtime)
  536. // srv := &Server{runtime: runtime}
  537. // stdin, stdinPipe := io.Pipe()
  538. // stdout, stdoutPipe := io.Pipe()
  539. // // Attach to it
  540. // c1 := make(chan struct{})
  541. // go func() {
  542. // defer close(c1)
  543. // r := &hijackTester{
  544. // ResponseRecorder: httptest.NewRecorder(),
  545. // in: stdin,
  546. // out: stdoutPipe,
  547. // }
  548. // req, err := http.NewRequest("POST", "/images/"+unitTestImageName+"/insert?path=%2Ftest&url=https%3A%2F%2Fraw.github.com%2Fdotcloud%2Fdocker%2Fmaster%2FREADME.md", bytes.NewReader([]byte{}))
  549. // if err != nil {
  550. // t.Fatal(err)
  551. // }
  552. // if err := postContainersCreate(srv, r, req, nil); err != nil {
  553. // t.Fatal(err)
  554. // }
  555. // }()
  556. // // Acknowledge hijack
  557. // setTimeout(t, "hijack acknowledge timed out", 5*time.Second, func() {
  558. // stdout.Read([]byte{})
  559. // stdout.Read(make([]byte, 4096))
  560. // })
  561. // id := ""
  562. // setTimeout(t, "Waiting for imagesInsert output", 10*time.Second, func() {
  563. // for {
  564. // reader := bufio.NewReader(stdout)
  565. // id, err = reader.ReadString('\n')
  566. // if err != nil {
  567. // t.Fatal(err)
  568. // }
  569. // }
  570. // })
  571. // // Close pipes (client disconnects)
  572. // if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  573. // t.Fatal(err)
  574. // }
  575. // // Wait for attach to finish, the client disconnected, therefore, Attach finished his job
  576. // setTimeout(t, "Waiting for CmdAttach timed out", 2*time.Second, func() {
  577. // <-c1
  578. // })
  579. // img, err := srv.runtime.repositories.LookupImage(id)
  580. // if err != nil {
  581. // t.Fatalf("New image %s expected but not found", id)
  582. // }
  583. // layer, err := img.layer()
  584. // if err != nil {
  585. // t.Fatal(err)
  586. // }
  587. // if _, err := os.Stat(path.Join(layer, "test")); err != nil {
  588. // t.Fatalf("The test file has not been found")
  589. // }
  590. // if err := srv.runtime.graph.Delete(img.ID); err != nil {
  591. // t.Fatal(err)
  592. // }
  593. }
  594. func TestPostImagesPush(t *testing.T) {
  595. //FIXME: Use staging in order to perform tests
  596. // runtime, err := newTestRuntime()
  597. // if err != nil {
  598. // t.Fatal(err)
  599. // }
  600. // defer nuke(runtime)
  601. // srv := &Server{runtime: runtime}
  602. // stdin, stdinPipe := io.Pipe()
  603. // stdout, stdoutPipe := io.Pipe()
  604. // c1 := make(chan struct{})
  605. // go func() {
  606. // r := &hijackTester{
  607. // ResponseRecorder: httptest.NewRecorder(),
  608. // in: stdin,
  609. // out: stdoutPipe,
  610. // }
  611. // req, err := http.NewRequest("POST", "/images/docker-ut/push", bytes.NewReader([]byte{}))
  612. // if err != nil {
  613. // t.Fatal(err)
  614. // }
  615. // body, err := postImagesPush(srv, r, req, map[string]string{"name": "docker-ut"})
  616. // close(c1)
  617. // if err != nil {
  618. // t.Fatal(err)
  619. // }
  620. // if body != nil {
  621. // t.Fatalf("No body expected, received: %s\n", body)
  622. // }
  623. // }()
  624. // // Acknowledge hijack
  625. // setTimeout(t, "hijack acknowledge timed out", 2*time.Second, func() {
  626. // stdout.Read([]byte{})
  627. // stdout.Read(make([]byte, 4096))
  628. // })
  629. // setTimeout(t, "Waiting for imagesCreate output", 5*time.Second, func() {
  630. // reader := bufio.NewReader(stdout)
  631. // line, err := reader.ReadString('\n')
  632. // if err != nil {
  633. // t.Fatal(err)
  634. // }
  635. // if !strings.HasPrefix(line, "Processing checksum") {
  636. // t.Fatalf("Processing checksum..., found %s", line)
  637. // }
  638. // })
  639. // // Close pipes (client disconnects)
  640. // if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  641. // t.Fatal(err)
  642. // }
  643. // // Wait for imagesPush to finish, the client disconnected, therefore, Push finished his job
  644. // setTimeout(t, "Waiting for imagesPush timed out", 10*time.Second, func() {
  645. // <-c1
  646. // })
  647. }
  648. func TestPostImagesTag(t *testing.T) {
  649. // FIXME: Use staging in order to perform tests
  650. // runtime, err := newTestRuntime()
  651. // if err != nil {
  652. // t.Fatal(err)
  653. // }
  654. // defer nuke(runtime)
  655. // srv := &Server{runtime: runtime}
  656. // r := httptest.NewRecorder()
  657. // req, err := http.NewRequest("POST", "/images/docker-ut/tag?repo=testrepo&tag=testtag", bytes.NewReader([]byte{}))
  658. // if err != nil {
  659. // t.Fatal(err)
  660. // }
  661. // body, err := postImagesTag(srv, r, req, map[string]string{"name": "docker-ut"})
  662. // if err != nil {
  663. // t.Fatal(err)
  664. // }
  665. // if body != nil {
  666. // t.Fatalf("No body expected, received: %s\n", body)
  667. // }
  668. // if r.Code != http.StatusCreated {
  669. // t.Fatalf("%d Created expected, received %d\n", http.StatusCreated, r.Code)
  670. // }
  671. }
  672. func TestPostContainersCreate(t *testing.T) {
  673. runtime, err := newTestRuntime()
  674. if err != nil {
  675. t.Fatal(err)
  676. }
  677. defer nuke(runtime)
  678. srv := &Server{runtime: runtime}
  679. configJSON, err := json.Marshal(&Config{
  680. Image: GetTestImage(runtime).ID,
  681. Memory: 33554432,
  682. Cmd: []string{"touch", "/test"},
  683. })
  684. if err != nil {
  685. t.Fatal(err)
  686. }
  687. req, err := http.NewRequest("POST", "/containers/create", bytes.NewReader(configJSON))
  688. if err != nil {
  689. t.Fatal(err)
  690. }
  691. r := httptest.NewRecorder()
  692. if err := postContainersCreate(srv, APIVERSION, r, req, nil); err != nil {
  693. t.Fatal(err)
  694. }
  695. if r.Code != http.StatusCreated {
  696. t.Fatalf("%d Created expected, received %d\n", http.StatusCreated, r.Code)
  697. }
  698. apiRun := &APIRun{}
  699. if err := json.Unmarshal(r.Body.Bytes(), apiRun); err != nil {
  700. t.Fatal(err)
  701. }
  702. container := srv.runtime.Get(apiRun.ID)
  703. if container == nil {
  704. t.Fatalf("Container not created")
  705. }
  706. if err := container.Run(); err != nil {
  707. t.Fatal(err)
  708. }
  709. if _, err := os.Stat(path.Join(container.rwPath(), "test")); err != nil {
  710. if os.IsNotExist(err) {
  711. utils.Debugf("Err: %s", err)
  712. t.Fatalf("The test file has not been created")
  713. }
  714. t.Fatal(err)
  715. }
  716. }
  717. func TestPostContainersKill(t *testing.T) {
  718. runtime, err := newTestRuntime()
  719. if err != nil {
  720. t.Fatal(err)
  721. }
  722. defer nuke(runtime)
  723. srv := &Server{runtime: runtime}
  724. container, err := NewBuilder(runtime).Create(
  725. &Config{
  726. Image: GetTestImage(runtime).ID,
  727. Cmd: []string{"/bin/cat"},
  728. OpenStdin: true,
  729. },
  730. )
  731. if err != nil {
  732. t.Fatal(err)
  733. }
  734. defer runtime.Destroy(container)
  735. if err := container.Start(); err != nil {
  736. t.Fatal(err)
  737. }
  738. // Give some time to the process to start
  739. container.WaitTimeout(500 * time.Millisecond)
  740. if !container.State.Running {
  741. t.Errorf("Container should be running")
  742. }
  743. r := httptest.NewRecorder()
  744. if err := postContainersKill(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  745. t.Fatal(err)
  746. }
  747. if r.Code != http.StatusNoContent {
  748. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  749. }
  750. if container.State.Running {
  751. t.Fatalf("The container hasn't been killed")
  752. }
  753. }
  754. func TestPostContainersRestart(t *testing.T) {
  755. runtime, err := newTestRuntime()
  756. if err != nil {
  757. t.Fatal(err)
  758. }
  759. defer nuke(runtime)
  760. srv := &Server{runtime: runtime}
  761. container, err := NewBuilder(runtime).Create(
  762. &Config{
  763. Image: GetTestImage(runtime).ID,
  764. Cmd: []string{"/bin/cat"},
  765. OpenStdin: true,
  766. },
  767. )
  768. if err != nil {
  769. t.Fatal(err)
  770. }
  771. defer runtime.Destroy(container)
  772. if err := container.Start(); err != nil {
  773. t.Fatal(err)
  774. }
  775. // Give some time to the process to start
  776. container.WaitTimeout(500 * time.Millisecond)
  777. if !container.State.Running {
  778. t.Errorf("Container should be running")
  779. }
  780. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/restart?t=1", bytes.NewReader([]byte{}))
  781. if err != nil {
  782. t.Fatal(err)
  783. }
  784. r := httptest.NewRecorder()
  785. if err := postContainersRestart(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  786. t.Fatal(err)
  787. }
  788. if r.Code != http.StatusNoContent {
  789. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  790. }
  791. // Give some time to the process to restart
  792. container.WaitTimeout(500 * time.Millisecond)
  793. if !container.State.Running {
  794. t.Fatalf("Container should be running")
  795. }
  796. if err := container.Kill(); err != nil {
  797. t.Fatal(err)
  798. }
  799. }
  800. func TestPostContainersStart(t *testing.T) {
  801. runtime, err := newTestRuntime()
  802. if err != nil {
  803. t.Fatal(err)
  804. }
  805. defer nuke(runtime)
  806. srv := &Server{runtime: runtime}
  807. container, err := NewBuilder(runtime).Create(
  808. &Config{
  809. Image: GetTestImage(runtime).ID,
  810. Cmd: []string{"/bin/cat"},
  811. OpenStdin: true,
  812. },
  813. )
  814. if err != nil {
  815. t.Fatal(err)
  816. }
  817. defer runtime.Destroy(container)
  818. r := httptest.NewRecorder()
  819. if err := postContainersStart(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  820. t.Fatal(err)
  821. }
  822. if r.Code != http.StatusNoContent {
  823. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  824. }
  825. // Give some time to the process to start
  826. container.WaitTimeout(500 * time.Millisecond)
  827. if !container.State.Running {
  828. t.Errorf("Container should be running")
  829. }
  830. r = httptest.NewRecorder()
  831. if err = postContainersStart(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err == nil {
  832. t.Fatalf("A running containter should be able to be started")
  833. }
  834. if err := container.Kill(); err != nil {
  835. t.Fatal(err)
  836. }
  837. }
  838. func TestPostContainersStop(t *testing.T) {
  839. runtime, err := newTestRuntime()
  840. if err != nil {
  841. t.Fatal(err)
  842. }
  843. defer nuke(runtime)
  844. srv := &Server{runtime: runtime}
  845. container, err := NewBuilder(runtime).Create(
  846. &Config{
  847. Image: GetTestImage(runtime).ID,
  848. Cmd: []string{"/bin/cat"},
  849. OpenStdin: true,
  850. },
  851. )
  852. if err != nil {
  853. t.Fatal(err)
  854. }
  855. defer runtime.Destroy(container)
  856. if err := container.Start(); err != nil {
  857. t.Fatal(err)
  858. }
  859. // Give some time to the process to start
  860. container.WaitTimeout(500 * time.Millisecond)
  861. if !container.State.Running {
  862. t.Errorf("Container should be running")
  863. }
  864. // Note: as it is a POST request, it requires a body.
  865. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/stop?t=1", bytes.NewReader([]byte{}))
  866. if err != nil {
  867. t.Fatal(err)
  868. }
  869. r := httptest.NewRecorder()
  870. if err := postContainersStop(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  871. t.Fatal(err)
  872. }
  873. if r.Code != http.StatusNoContent {
  874. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  875. }
  876. if container.State.Running {
  877. t.Fatalf("The container hasn't been stopped")
  878. }
  879. }
  880. func TestPostContainersWait(t *testing.T) {
  881. runtime, err := newTestRuntime()
  882. if err != nil {
  883. t.Fatal(err)
  884. }
  885. defer nuke(runtime)
  886. srv := &Server{runtime: runtime}
  887. container, err := NewBuilder(runtime).Create(
  888. &Config{
  889. Image: GetTestImage(runtime).ID,
  890. Cmd: []string{"/bin/sleep", "1"},
  891. OpenStdin: true,
  892. },
  893. )
  894. if err != nil {
  895. t.Fatal(err)
  896. }
  897. defer runtime.Destroy(container)
  898. if err := container.Start(); err != nil {
  899. t.Fatal(err)
  900. }
  901. setTimeout(t, "Wait timed out", 3*time.Second, func() {
  902. r := httptest.NewRecorder()
  903. if err := postContainersWait(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  904. t.Fatal(err)
  905. }
  906. apiWait := &APIWait{}
  907. if err := json.Unmarshal(r.Body.Bytes(), apiWait); err != nil {
  908. t.Fatal(err)
  909. }
  910. if apiWait.StatusCode != 0 {
  911. t.Fatalf("Non zero exit code for sleep: %d\n", apiWait.StatusCode)
  912. }
  913. })
  914. if container.State.Running {
  915. t.Fatalf("The container should be stopped after wait")
  916. }
  917. }
  918. func TestPostContainersAttach(t *testing.T) {
  919. runtime, err := newTestRuntime()
  920. if err != nil {
  921. t.Fatal(err)
  922. }
  923. defer nuke(runtime)
  924. srv := &Server{runtime: runtime}
  925. container, err := NewBuilder(runtime).Create(
  926. &Config{
  927. Image: GetTestImage(runtime).ID,
  928. Cmd: []string{"/bin/cat"},
  929. OpenStdin: true,
  930. },
  931. )
  932. if err != nil {
  933. t.Fatal(err)
  934. }
  935. defer runtime.Destroy(container)
  936. // Start the process
  937. if err := container.Start(); err != nil {
  938. t.Fatal(err)
  939. }
  940. stdin, stdinPipe := io.Pipe()
  941. stdout, stdoutPipe := io.Pipe()
  942. // Attach to it
  943. c1 := make(chan struct{})
  944. go func() {
  945. defer close(c1)
  946. r := &hijackTester{
  947. ResponseRecorder: httptest.NewRecorder(),
  948. in: stdin,
  949. out: stdoutPipe,
  950. }
  951. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/attach?stream=1&stdin=1&stdout=1&stderr=1", bytes.NewReader([]byte{}))
  952. if err != nil {
  953. t.Fatal(err)
  954. }
  955. if err := postContainersAttach(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  956. t.Fatal(err)
  957. }
  958. }()
  959. // Acknowledge hijack
  960. setTimeout(t, "hijack acknowledge timed out", 2*time.Second, func() {
  961. stdout.Read([]byte{})
  962. stdout.Read(make([]byte, 4096))
  963. })
  964. setTimeout(t, "read/write assertion timed out", 2*time.Second, func() {
  965. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 15); err != nil {
  966. t.Fatal(err)
  967. }
  968. })
  969. // Close pipes (client disconnects)
  970. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  971. t.Fatal(err)
  972. }
  973. // Wait for attach to finish, the client disconnected, therefore, Attach finished his job
  974. setTimeout(t, "Waiting for CmdAttach timed out", 2*time.Second, func() {
  975. <-c1
  976. })
  977. // We closed stdin, expect /bin/cat to still be running
  978. // Wait a little bit to make sure container.monitor() did his thing
  979. err = container.WaitTimeout(500 * time.Millisecond)
  980. if err == nil || !container.State.Running {
  981. t.Fatalf("/bin/cat is not running after closing stdin")
  982. }
  983. // Try to avoid the timeoout in destroy. Best effort, don't check error
  984. cStdin, _ := container.StdinPipe()
  985. cStdin.Close()
  986. container.Wait()
  987. }
  988. // FIXME: Test deleting running container
  989. // FIXME: Test deleting container with volume
  990. // FIXME: Test deleting volume in use by other container
  991. func TestDeleteContainers(t *testing.T) {
  992. runtime, err := newTestRuntime()
  993. if err != nil {
  994. t.Fatal(err)
  995. }
  996. defer nuke(runtime)
  997. srv := &Server{runtime: runtime}
  998. container, err := NewBuilder(runtime).Create(&Config{
  999. Image: GetTestImage(runtime).ID,
  1000. Cmd: []string{"touch", "/test"},
  1001. })
  1002. if err != nil {
  1003. t.Fatal(err)
  1004. }
  1005. defer runtime.Destroy(container)
  1006. if err := container.Run(); err != nil {
  1007. t.Fatal(err)
  1008. }
  1009. req, err := http.NewRequest("DELETE", "/containers/"+container.ID, nil)
  1010. if err != nil {
  1011. t.Fatal(err)
  1012. }
  1013. r := httptest.NewRecorder()
  1014. if err := deleteContainers(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  1015. t.Fatal(err)
  1016. }
  1017. if r.Code != http.StatusNoContent {
  1018. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  1019. }
  1020. if c := runtime.Get(container.ID); c != nil {
  1021. t.Fatalf("The container as not been deleted")
  1022. }
  1023. if _, err := os.Stat(path.Join(container.rwPath(), "test")); err == nil {
  1024. t.Fatalf("The test file has not been deleted")
  1025. }
  1026. }
  1027. func TestOptionsRoute(t *testing.T) {
  1028. runtime, err := newTestRuntime()
  1029. if err != nil {
  1030. t.Fatal(err)
  1031. }
  1032. defer nuke(runtime)
  1033. srv := &Server{runtime: runtime, enableCors: true}
  1034. r := httptest.NewRecorder()
  1035. router, err := createRouter(srv, false)
  1036. if err != nil {
  1037. t.Fatal(err)
  1038. }
  1039. req, err := http.NewRequest("OPTIONS", "/", nil)
  1040. if err != nil {
  1041. t.Fatal(err)
  1042. }
  1043. router.ServeHTTP(r, req)
  1044. if r.Code != http.StatusOK {
  1045. t.Errorf("Expected response for OPTIONS request to be \"200\", %v found.", r.Code)
  1046. }
  1047. }
  1048. func TestGetEnabledCors(t *testing.T) {
  1049. runtime, err := newTestRuntime()
  1050. if err != nil {
  1051. t.Fatal(err)
  1052. }
  1053. defer nuke(runtime)
  1054. srv := &Server{runtime: runtime, enableCors: true}
  1055. r := httptest.NewRecorder()
  1056. router, err := createRouter(srv, false)
  1057. if err != nil {
  1058. t.Fatal(err)
  1059. }
  1060. req, err := http.NewRequest("GET", "/version", nil)
  1061. if err != nil {
  1062. t.Fatal(err)
  1063. }
  1064. router.ServeHTTP(r, req)
  1065. if r.Code != http.StatusOK {
  1066. t.Errorf("Expected response for OPTIONS request to be \"200\", %v found.", r.Code)
  1067. }
  1068. allowOrigin := r.Header().Get("Access-Control-Allow-Origin")
  1069. allowHeaders := r.Header().Get("Access-Control-Allow-Headers")
  1070. allowMethods := r.Header().Get("Access-Control-Allow-Methods")
  1071. if allowOrigin != "*" {
  1072. t.Errorf("Expected header Access-Control-Allow-Origin to be \"*\", %s found.", allowOrigin)
  1073. }
  1074. if allowHeaders != "Origin, X-Requested-With, Content-Type, Accept" {
  1075. t.Errorf("Expected header Access-Control-Allow-Headers to be \"Origin, X-Requested-With, Content-Type, Accept\", %s found.", allowHeaders)
  1076. }
  1077. if allowMethods != "GET, POST, DELETE, PUT, OPTIONS" {
  1078. t.Errorf("Expected hearder Access-Control-Allow-Methods to be \"GET, POST, DELETE, PUT, OPTIONS\", %s found.", allowMethods)
  1079. }
  1080. }
  1081. func TestDeleteImages(t *testing.T) {
  1082. runtime, err := newTestRuntime()
  1083. if err != nil {
  1084. t.Fatal(err)
  1085. }
  1086. defer nuke(runtime)
  1087. srv := &Server{runtime: runtime}
  1088. if err := srv.runtime.repositories.Set("test", "test", unitTestImageName, true); err != nil {
  1089. t.Fatal(err)
  1090. }
  1091. images, err := srv.Images(false, "")
  1092. if err != nil {
  1093. t.Fatal(err)
  1094. }
  1095. if len(images) != 2 {
  1096. t.Errorf("Excepted 2 images, %d found", len(images))
  1097. }
  1098. req, err := http.NewRequest("DELETE", "/images/test:test", nil)
  1099. if err != nil {
  1100. t.Fatal(err)
  1101. }
  1102. r := httptest.NewRecorder()
  1103. if err := deleteImages(srv, APIVERSION, r, req, map[string]string{"name": "test:test"}); err != nil {
  1104. t.Fatal(err)
  1105. }
  1106. if r.Code != http.StatusOK {
  1107. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  1108. }
  1109. var outs []APIRmi
  1110. if err := json.Unmarshal(r.Body.Bytes(), &outs); err != nil {
  1111. t.Fatal(err)
  1112. }
  1113. if len(outs) != 1 {
  1114. t.Fatalf("Expected %d event (untagged), got %d", 1, len(outs))
  1115. }
  1116. images, err = srv.Images(false, "")
  1117. if err != nil {
  1118. t.Fatal(err)
  1119. }
  1120. if len(images) != 1 {
  1121. t.Errorf("Excepted 1 image, %d found", len(images))
  1122. }
  1123. /* if c := runtime.Get(container.Id); c != nil {
  1124. t.Fatalf("The container as not been deleted")
  1125. }
  1126. if _, err := os.Stat(path.Join(container.rwPath(), "test")); err == nil {
  1127. t.Fatalf("The test file has not been deleted")
  1128. } */
  1129. }
  1130. // Mocked types for tests
  1131. type NopConn struct {
  1132. io.ReadCloser
  1133. io.Writer
  1134. }
  1135. func (c *NopConn) LocalAddr() net.Addr { return nil }
  1136. func (c *NopConn) RemoteAddr() net.Addr { return nil }
  1137. func (c *NopConn) SetDeadline(t time.Time) error { return nil }
  1138. func (c *NopConn) SetReadDeadline(t time.Time) error { return nil }
  1139. func (c *NopConn) SetWriteDeadline(t time.Time) error { return nil }
  1140. type hijackTester struct {
  1141. *httptest.ResponseRecorder
  1142. in io.ReadCloser
  1143. out io.Writer
  1144. }
  1145. func (t *hijackTester) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  1146. bufrw := bufio.NewReadWriter(bufio.NewReader(t.in), bufio.NewWriter(t.out))
  1147. conn := &NopConn{
  1148. ReadCloser: t.in,
  1149. Writer: t.out,
  1150. }
  1151. return conn, bufrw, nil
  1152. }