api_test.go 28 KB

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