api_test.go 26 KB

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