api_test.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358
  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.Map()
  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", "fakeimage")
  86. srv.LogEvent("fakeaction2", "fakeid", "fakeimage")
  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 := 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. setTimeout(t, "getContainerJSON timed out", 5*time.Second, func() {
  275. if err := getContainersJSON(srv, APIVERSION, r, req, nil); err != nil {
  276. t.Fatal(err)
  277. }
  278. })
  279. containers := []APIContainers{}
  280. if err := json.Unmarshal(r.Body.Bytes(), &containers); err != nil {
  281. t.Fatal(err)
  282. }
  283. if len(containers) != 1 {
  284. t.Fatalf("Expected %d container, %d found", 1, len(containers))
  285. }
  286. if containers[0].ID != container.ID {
  287. t.Fatalf("Container ID mismatch. Expected: %s, received: %s\n", container.ID, containers[0].ID)
  288. }
  289. }
  290. func TestGetContainersExport(t *testing.T) {
  291. runtime := mkRuntime(t)
  292. defer nuke(runtime)
  293. srv := &Server{runtime: runtime}
  294. // Create a container and remove a file
  295. container, err := runtime.Create(
  296. &Config{
  297. Image: GetTestImage(runtime).ID,
  298. Cmd: []string{"touch", "/test"},
  299. },
  300. )
  301. if err != nil {
  302. t.Fatal(err)
  303. }
  304. defer runtime.Destroy(container)
  305. if err := container.Run(); err != nil {
  306. t.Fatal(err)
  307. }
  308. r := httptest.NewRecorder()
  309. if err := getContainersExport(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  310. t.Fatal(err)
  311. }
  312. if r.Code != http.StatusOK {
  313. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  314. }
  315. found := false
  316. for tarReader := tar.NewReader(r.Body); ; {
  317. h, err := tarReader.Next()
  318. if err != nil {
  319. if err == io.EOF {
  320. break
  321. }
  322. t.Fatal(err)
  323. }
  324. if h.Name == "./test" {
  325. found = true
  326. break
  327. }
  328. }
  329. if !found {
  330. t.Fatalf("The created test file has not been found in the exported image")
  331. }
  332. }
  333. func TestGetContainersChanges(t *testing.T) {
  334. runtime := mkRuntime(t)
  335. defer nuke(runtime)
  336. srv := &Server{runtime: runtime}
  337. // Create a container and remove a file
  338. container, err := runtime.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. t.Skip("Fixme. Skipping test for now. Reported error when testing using dind: 'api_test.go:527: Expected 2 processes, found 0.'")
  372. runtime, err := newTestRuntime()
  373. if err != nil {
  374. t.Fatal(err)
  375. }
  376. defer nuke(runtime)
  377. srv := &Server{runtime: runtime}
  378. container, err := runtime.Create(
  379. &Config{
  380. Image: GetTestImage(runtime).ID,
  381. Cmd: []string{"/bin/sh", "-c", "cat"},
  382. OpenStdin: true,
  383. },
  384. )
  385. if err != nil {
  386. t.Fatal(err)
  387. }
  388. defer runtime.Destroy(container)
  389. defer func() {
  390. // Make sure the process dies before destroying runtime
  391. container.stdin.Close()
  392. container.WaitTimeout(2 * time.Second)
  393. }()
  394. hostConfig := &HostConfig{}
  395. if err := container.Start(hostConfig); err != nil {
  396. t.Fatal(err)
  397. }
  398. setTimeout(t, "Waiting for the container to be started timed out", 10*time.Second, func() {
  399. for {
  400. if container.State.Running {
  401. break
  402. }
  403. time.Sleep(10 * time.Millisecond)
  404. }
  405. })
  406. if !container.State.Running {
  407. t.Fatalf("Container should be running")
  408. }
  409. // Make sure sh spawn up cat
  410. setTimeout(t, "read/write assertion timed out", 2*time.Second, func() {
  411. in, _ := container.StdinPipe()
  412. out, _ := container.StdoutPipe()
  413. if err := assertPipe("hello\n", "hello", out, in, 15); err != nil {
  414. t.Fatal(err)
  415. }
  416. })
  417. r := httptest.NewRecorder()
  418. req, err := http.NewRequest("GET", "/"+container.ID+"/top?ps_args=u", bytes.NewReader([]byte{}))
  419. if err != nil {
  420. t.Fatal(err)
  421. }
  422. if err := getContainersTop(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  423. t.Fatal(err)
  424. }
  425. procs := APITop{}
  426. if err := json.Unmarshal(r.Body.Bytes(), &procs); err != nil {
  427. t.Fatal(err)
  428. }
  429. if len(procs.Titles) != 11 {
  430. t.Fatalf("Expected 11 titles, found %d.", len(procs.Titles))
  431. }
  432. if procs.Titles[0] != "USER" || procs.Titles[10] != "COMMAND" {
  433. t.Fatalf("Expected Titles[0] to be USER and Titles[10] to be COMMAND, found %s and %s.", procs.Titles[0], procs.Titles[10])
  434. }
  435. if len(procs.Processes) != 2 {
  436. t.Fatalf("Expected 2 processes, found %d.", len(procs.Processes))
  437. }
  438. if procs.Processes[0][10] != "/bin/sh" && procs.Processes[0][10] != "cat" {
  439. t.Fatalf("Expected `cat` or `/bin/sh`, found %s.", procs.Processes[0][10])
  440. }
  441. if procs.Processes[1][10] != "/bin/sh" && procs.Processes[1][10] != "cat" {
  442. t.Fatalf("Expected `cat` or `/bin/sh`, found %s.", procs.Processes[1][10])
  443. }
  444. }
  445. func TestGetContainersByName(t *testing.T) {
  446. runtime := mkRuntime(t)
  447. defer nuke(runtime)
  448. srv := &Server{runtime: runtime}
  449. // Create a container and remove a file
  450. container, err := runtime.Create(
  451. &Config{
  452. Image: GetTestImage(runtime).ID,
  453. Cmd: []string{"echo", "test"},
  454. },
  455. )
  456. if err != nil {
  457. t.Fatal(err)
  458. }
  459. defer runtime.Destroy(container)
  460. r := httptest.NewRecorder()
  461. if err := getContainersByName(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  462. t.Fatal(err)
  463. }
  464. outContainer := &Container{}
  465. if err := json.Unmarshal(r.Body.Bytes(), outContainer); err != nil {
  466. t.Fatal(err)
  467. }
  468. if outContainer.ID != container.ID {
  469. t.Fatalf("Wrong containers retrieved. Expected %s, received %s", container.ID, outContainer.ID)
  470. }
  471. }
  472. func TestPostCommit(t *testing.T) {
  473. runtime := mkRuntime(t)
  474. defer nuke(runtime)
  475. srv := &Server{runtime: runtime}
  476. // Create a container and remove a file
  477. container, err := runtime.Create(
  478. &Config{
  479. Image: GetTestImage(runtime).ID,
  480. Cmd: []string{"touch", "/test"},
  481. },
  482. )
  483. if err != nil {
  484. t.Fatal(err)
  485. }
  486. defer runtime.Destroy(container)
  487. if err := container.Run(); err != nil {
  488. t.Fatal(err)
  489. }
  490. req, err := http.NewRequest("POST", "/commit?repo=testrepo&testtag=tag&container="+container.ID, bytes.NewReader([]byte{}))
  491. if err != nil {
  492. t.Fatal(err)
  493. }
  494. r := httptest.NewRecorder()
  495. if err := postCommit(srv, APIVERSION, r, req, nil); err != nil {
  496. t.Fatal(err)
  497. }
  498. if r.Code != http.StatusCreated {
  499. t.Fatalf("%d Created expected, received %d\n", http.StatusCreated, r.Code)
  500. }
  501. apiID := &APIID{}
  502. if err := json.Unmarshal(r.Body.Bytes(), apiID); err != nil {
  503. t.Fatal(err)
  504. }
  505. if _, err := runtime.graph.Get(apiID.ID); err != nil {
  506. t.Fatalf("The image has not been commited")
  507. }
  508. }
  509. func TestPostContainersCreate(t *testing.T) {
  510. runtime := mkRuntime(t)
  511. defer nuke(runtime)
  512. srv := &Server{runtime: runtime}
  513. configJSON, err := json.Marshal(&Config{
  514. Image: GetTestImage(runtime).ID,
  515. Memory: 33554432,
  516. Cmd: []string{"touch", "/test"},
  517. })
  518. if err != nil {
  519. t.Fatal(err)
  520. }
  521. req, err := http.NewRequest("POST", "/containers/create", bytes.NewReader(configJSON))
  522. if err != nil {
  523. t.Fatal(err)
  524. }
  525. r := httptest.NewRecorder()
  526. if err := postContainersCreate(srv, APIVERSION, r, req, nil); err != nil {
  527. t.Fatal(err)
  528. }
  529. if r.Code != http.StatusCreated {
  530. t.Fatalf("%d Created expected, received %d\n", http.StatusCreated, r.Code)
  531. }
  532. apiRun := &APIRun{}
  533. if err := json.Unmarshal(r.Body.Bytes(), apiRun); err != nil {
  534. t.Fatal(err)
  535. }
  536. container := srv.runtime.Get(apiRun.ID)
  537. if container == nil {
  538. t.Fatalf("Container not created")
  539. }
  540. if err := container.Run(); err != nil {
  541. t.Fatal(err)
  542. }
  543. if err := container.EnsureMounted(); err != nil {
  544. t.Fatalf("Unable to mount container: %s", err)
  545. }
  546. if _, err := os.Stat(path.Join(container.RootfsPath(), "test")); err != nil {
  547. if os.IsNotExist(err) {
  548. utils.Debugf("Err: %s", err)
  549. t.Fatalf("The test file has not been created")
  550. }
  551. t.Fatal(err)
  552. }
  553. if err := container.Unmount(); err != nil {
  554. t.Fatalf("Unable to unmount container: %s", err)
  555. }
  556. }
  557. func TestPostContainersKill(t *testing.T) {
  558. runtime := mkRuntime(t)
  559. defer nuke(runtime)
  560. srv := &Server{runtime: runtime}
  561. container, err := runtime.Create(
  562. &Config{
  563. Image: GetTestImage(runtime).ID,
  564. Cmd: []string{"/bin/cat"},
  565. OpenStdin: true,
  566. },
  567. )
  568. if err != nil {
  569. t.Fatal(err)
  570. }
  571. defer runtime.Destroy(container)
  572. hostConfig := &HostConfig{}
  573. if err := container.Start(hostConfig); err != nil {
  574. t.Fatal(err)
  575. }
  576. // Give some time to the process to start
  577. container.WaitTimeout(500 * time.Millisecond)
  578. if !container.State.Running {
  579. t.Errorf("Container should be running")
  580. }
  581. r := httptest.NewRecorder()
  582. if err := postContainersKill(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  583. t.Fatal(err)
  584. }
  585. if r.Code != http.StatusNoContent {
  586. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  587. }
  588. if container.State.Running {
  589. t.Fatalf("The container hasn't been killed")
  590. }
  591. }
  592. func TestPostContainersRestart(t *testing.T) {
  593. runtime := mkRuntime(t)
  594. defer nuke(runtime)
  595. srv := &Server{runtime: runtime}
  596. container, err := runtime.Create(
  597. &Config{
  598. Image: GetTestImage(runtime).ID,
  599. Cmd: []string{"/bin/cat"},
  600. OpenStdin: true,
  601. },
  602. )
  603. if err != nil {
  604. t.Fatal(err)
  605. }
  606. defer runtime.Destroy(container)
  607. hostConfig := &HostConfig{}
  608. if err := container.Start(hostConfig); err != nil {
  609. t.Fatal(err)
  610. }
  611. // Give some time to the process to start
  612. container.WaitTimeout(500 * time.Millisecond)
  613. if !container.State.Running {
  614. t.Errorf("Container should be running")
  615. }
  616. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/restart?t=1", bytes.NewReader([]byte{}))
  617. if err != nil {
  618. t.Fatal(err)
  619. }
  620. r := httptest.NewRecorder()
  621. if err := postContainersRestart(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  622. t.Fatal(err)
  623. }
  624. if r.Code != http.StatusNoContent {
  625. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  626. }
  627. // Give some time to the process to restart
  628. container.WaitTimeout(500 * time.Millisecond)
  629. if !container.State.Running {
  630. t.Fatalf("Container should be running")
  631. }
  632. if err := container.Kill(); err != nil {
  633. t.Fatal(err)
  634. }
  635. }
  636. func TestPostContainersStart(t *testing.T) {
  637. runtime := mkRuntime(t)
  638. defer nuke(runtime)
  639. srv := &Server{runtime: runtime}
  640. container, err := runtime.Create(
  641. &Config{
  642. Image: GetTestImage(runtime).ID,
  643. Cmd: []string{"/bin/cat"},
  644. OpenStdin: true,
  645. },
  646. )
  647. if err != nil {
  648. t.Fatal(err)
  649. }
  650. defer runtime.Destroy(container)
  651. hostConfigJSON, err := json.Marshal(&HostConfig{})
  652. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/start", bytes.NewReader(hostConfigJSON))
  653. if err != nil {
  654. t.Fatal(err)
  655. }
  656. r := httptest.NewRecorder()
  657. if err := postContainersStart(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  658. t.Fatal(err)
  659. }
  660. if r.Code != http.StatusNoContent {
  661. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  662. }
  663. // Give some time to the process to start
  664. container.WaitTimeout(500 * time.Millisecond)
  665. if !container.State.Running {
  666. t.Errorf("Container should be running")
  667. }
  668. r = httptest.NewRecorder()
  669. if err = postContainersStart(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err == nil {
  670. t.Fatalf("A running container should be able to be started")
  671. }
  672. if err := container.Kill(); err != nil {
  673. t.Fatal(err)
  674. }
  675. }
  676. func TestPostContainersStop(t *testing.T) {
  677. runtime := mkRuntime(t)
  678. defer nuke(runtime)
  679. srv := &Server{runtime: runtime}
  680. container, err := runtime.Create(
  681. &Config{
  682. Image: GetTestImage(runtime).ID,
  683. Cmd: []string{"/bin/cat"},
  684. OpenStdin: true,
  685. },
  686. )
  687. if err != nil {
  688. t.Fatal(err)
  689. }
  690. defer runtime.Destroy(container)
  691. hostConfig := &HostConfig{}
  692. if err := container.Start(hostConfig); err != nil {
  693. t.Fatal(err)
  694. }
  695. // Give some time to the process to start
  696. container.WaitTimeout(500 * time.Millisecond)
  697. if !container.State.Running {
  698. t.Errorf("Container should be running")
  699. }
  700. // Note: as it is a POST request, it requires a body.
  701. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/stop?t=1", bytes.NewReader([]byte{}))
  702. if err != nil {
  703. t.Fatal(err)
  704. }
  705. r := httptest.NewRecorder()
  706. if err := postContainersStop(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  707. t.Fatal(err)
  708. }
  709. if r.Code != http.StatusNoContent {
  710. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  711. }
  712. if container.State.Running {
  713. t.Fatalf("The container hasn't been stopped")
  714. }
  715. }
  716. func TestPostContainersWait(t *testing.T) {
  717. runtime := mkRuntime(t)
  718. defer nuke(runtime)
  719. srv := &Server{runtime: runtime}
  720. container, err := runtime.Create(
  721. &Config{
  722. Image: GetTestImage(runtime).ID,
  723. Cmd: []string{"/bin/sleep", "1"},
  724. OpenStdin: true,
  725. },
  726. )
  727. if err != nil {
  728. t.Fatal(err)
  729. }
  730. defer runtime.Destroy(container)
  731. hostConfig := &HostConfig{}
  732. if err := container.Start(hostConfig); err != nil {
  733. t.Fatal(err)
  734. }
  735. setTimeout(t, "Wait timed out", 3*time.Second, func() {
  736. r := httptest.NewRecorder()
  737. if err := postContainersWait(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  738. t.Fatal(err)
  739. }
  740. apiWait := &APIWait{}
  741. if err := json.Unmarshal(r.Body.Bytes(), apiWait); err != nil {
  742. t.Fatal(err)
  743. }
  744. if apiWait.StatusCode != 0 {
  745. t.Fatalf("Non zero exit code for sleep: %d\n", apiWait.StatusCode)
  746. }
  747. })
  748. if container.State.Running {
  749. t.Fatalf("The container should be stopped after wait")
  750. }
  751. }
  752. func TestPostContainersAttach(t *testing.T) {
  753. runtime := mkRuntime(t)
  754. defer nuke(runtime)
  755. srv := &Server{runtime: runtime}
  756. container, err := runtime.Create(
  757. &Config{
  758. Image: GetTestImage(runtime).ID,
  759. Cmd: []string{"/bin/cat"},
  760. OpenStdin: true,
  761. },
  762. )
  763. if err != nil {
  764. t.Fatal(err)
  765. }
  766. defer runtime.Destroy(container)
  767. // Start the process
  768. hostConfig := &HostConfig{}
  769. if err := container.Start(hostConfig); err != nil {
  770. t.Fatal(err)
  771. }
  772. stdin, stdinPipe := io.Pipe()
  773. stdout, stdoutPipe := io.Pipe()
  774. // Try to avoid the timeout in destroy. Best effort, don't check error
  775. defer func() {
  776. closeWrap(stdin, stdinPipe, stdout, stdoutPipe)
  777. container.Kill()
  778. }()
  779. // Attach to it
  780. c1 := make(chan struct{})
  781. go func() {
  782. defer close(c1)
  783. r := &hijackTester{
  784. ResponseRecorder: httptest.NewRecorder(),
  785. in: stdin,
  786. out: stdoutPipe,
  787. }
  788. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/attach?stream=1&stdin=1&stdout=1&stderr=1", bytes.NewReader([]byte{}))
  789. if err != nil {
  790. t.Fatal(err)
  791. }
  792. if err := postContainersAttach(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  793. t.Fatal(err)
  794. }
  795. }()
  796. // Acknowledge hijack
  797. setTimeout(t, "hijack acknowledge timed out", 2*time.Second, func() {
  798. stdout.Read([]byte{})
  799. stdout.Read(make([]byte, 4096))
  800. })
  801. setTimeout(t, "read/write assertion timed out", 2*time.Second, func() {
  802. if err := assertPipe("hello\n", string([]byte{1, 0, 0, 0, 0, 0, 0, 6})+"hello", stdout, stdinPipe, 15); err != nil {
  803. t.Fatal(err)
  804. }
  805. })
  806. // Close pipes (client disconnects)
  807. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  808. t.Fatal(err)
  809. }
  810. // Wait for attach to finish, the client disconnected, therefore, Attach finished his job
  811. setTimeout(t, "Waiting for CmdAttach timed out", 10*time.Second, func() {
  812. <-c1
  813. })
  814. // We closed stdin, expect /bin/cat to still be running
  815. // Wait a little bit to make sure container.monitor() did his thing
  816. err = container.WaitTimeout(500 * time.Millisecond)
  817. if err == nil || !container.State.Running {
  818. t.Fatalf("/bin/cat is not running after closing stdin")
  819. }
  820. // Try to avoid the timeout in destroy. Best effort, don't check error
  821. cStdin, _ := container.StdinPipe()
  822. cStdin.Close()
  823. container.Wait()
  824. }
  825. func TestPostContainersAttachStderr(t *testing.T) {
  826. runtime := mkRuntime(t)
  827. defer nuke(runtime)
  828. srv := &Server{runtime: runtime}
  829. container, err := runtime.Create(
  830. &Config{
  831. Image: GetTestImage(runtime).ID,
  832. Cmd: []string{"/bin/sh", "-c", "/bin/cat >&2"},
  833. OpenStdin: true,
  834. },
  835. )
  836. if err != nil {
  837. t.Fatal(err)
  838. }
  839. defer runtime.Destroy(container)
  840. // Start the process
  841. hostConfig := &HostConfig{}
  842. if err := container.Start(hostConfig); err != nil {
  843. t.Fatal(err)
  844. }
  845. stdin, stdinPipe := io.Pipe()
  846. stdout, stdoutPipe := io.Pipe()
  847. // Try to avoid the timeout in destroy. Best effort, don't check error
  848. defer func() {
  849. closeWrap(stdin, stdinPipe, stdout, stdoutPipe)
  850. container.Kill()
  851. }()
  852. // Attach to it
  853. c1 := make(chan struct{})
  854. go func() {
  855. defer close(c1)
  856. r := &hijackTester{
  857. ResponseRecorder: httptest.NewRecorder(),
  858. in: stdin,
  859. out: stdoutPipe,
  860. }
  861. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/attach?stream=1&stdin=1&stdout=1&stderr=1", bytes.NewReader([]byte{}))
  862. if err != nil {
  863. t.Fatal(err)
  864. }
  865. if err := postContainersAttach(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  866. t.Fatal(err)
  867. }
  868. }()
  869. // Acknowledge hijack
  870. setTimeout(t, "hijack acknowledge timed out", 2*time.Second, func() {
  871. stdout.Read([]byte{})
  872. stdout.Read(make([]byte, 4096))
  873. })
  874. setTimeout(t, "read/write assertion timed out", 2*time.Second, func() {
  875. if err := assertPipe("hello\n", string([]byte{2, 0, 0, 0, 0, 0, 0, 6})+"hello", stdout, stdinPipe, 15); err != nil {
  876. t.Fatal(err)
  877. }
  878. })
  879. // Close pipes (client disconnects)
  880. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  881. t.Fatal(err)
  882. }
  883. // Wait for attach to finish, the client disconnected, therefore, Attach finished his job
  884. setTimeout(t, "Waiting for CmdAttach timed out", 10*time.Second, func() {
  885. <-c1
  886. })
  887. // We closed stdin, expect /bin/cat to still be running
  888. // Wait a little bit to make sure container.monitor() did his thing
  889. err = container.WaitTimeout(500 * time.Millisecond)
  890. if err == nil || !container.State.Running {
  891. t.Fatalf("/bin/cat is not running after closing stdin")
  892. }
  893. // Try to avoid the timeout in destroy. Best effort, don't check error
  894. cStdin, _ := container.StdinPipe()
  895. cStdin.Close()
  896. container.Wait()
  897. }
  898. // FIXME: Test deleting running container
  899. // FIXME: Test deleting container with volume
  900. // FIXME: Test deleting volume in use by other container
  901. func TestDeleteContainers(t *testing.T) {
  902. runtime := mkRuntime(t)
  903. defer nuke(runtime)
  904. srv := &Server{runtime: runtime}
  905. container, err := runtime.Create(&Config{
  906. Image: GetTestImage(runtime).ID,
  907. Cmd: []string{"touch", "/test"},
  908. })
  909. if err != nil {
  910. t.Fatal(err)
  911. }
  912. defer runtime.Destroy(container)
  913. if err := container.Run(); err != nil {
  914. t.Fatal(err)
  915. }
  916. req, err := http.NewRequest("DELETE", "/containers/"+container.ID, nil)
  917. if err != nil {
  918. t.Fatal(err)
  919. }
  920. r := httptest.NewRecorder()
  921. if err := deleteContainers(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  922. t.Fatal(err)
  923. }
  924. if r.Code != http.StatusNoContent {
  925. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  926. }
  927. if c := runtime.Get(container.ID); c != nil {
  928. t.Fatalf("The container as not been deleted")
  929. }
  930. if _, err := os.Stat(path.Join(container.rwPath(), "test")); err == nil {
  931. t.Fatalf("The test file has not been deleted")
  932. }
  933. }
  934. func TestOptionsRoute(t *testing.T) {
  935. runtime := mkRuntime(t)
  936. defer nuke(runtime)
  937. srv := &Server{runtime: runtime, enableCors: true}
  938. r := httptest.NewRecorder()
  939. router, err := createRouter(srv, false)
  940. if err != nil {
  941. t.Fatal(err)
  942. }
  943. req, err := http.NewRequest("OPTIONS", "/", nil)
  944. if err != nil {
  945. t.Fatal(err)
  946. }
  947. router.ServeHTTP(r, req)
  948. if r.Code != http.StatusOK {
  949. t.Errorf("Expected response for OPTIONS request to be \"200\", %v found.", r.Code)
  950. }
  951. }
  952. func TestGetEnabledCors(t *testing.T) {
  953. runtime := mkRuntime(t)
  954. defer nuke(runtime)
  955. srv := &Server{runtime: runtime, enableCors: true}
  956. r := httptest.NewRecorder()
  957. router, err := createRouter(srv, false)
  958. if err != nil {
  959. t.Fatal(err)
  960. }
  961. req, err := http.NewRequest("GET", "/version", nil)
  962. if err != nil {
  963. t.Fatal(err)
  964. }
  965. router.ServeHTTP(r, req)
  966. if r.Code != http.StatusOK {
  967. t.Errorf("Expected response for OPTIONS request to be \"200\", %v found.", r.Code)
  968. }
  969. allowOrigin := r.Header().Get("Access-Control-Allow-Origin")
  970. allowHeaders := r.Header().Get("Access-Control-Allow-Headers")
  971. allowMethods := r.Header().Get("Access-Control-Allow-Methods")
  972. if allowOrigin != "*" {
  973. t.Errorf("Expected header Access-Control-Allow-Origin to be \"*\", %s found.", allowOrigin)
  974. }
  975. if allowHeaders != "Origin, X-Requested-With, Content-Type, Accept" {
  976. t.Errorf("Expected header Access-Control-Allow-Headers to be \"Origin, X-Requested-With, Content-Type, Accept\", %s found.", allowHeaders)
  977. }
  978. if allowMethods != "GET, POST, DELETE, PUT, OPTIONS" {
  979. t.Errorf("Expected hearder Access-Control-Allow-Methods to be \"GET, POST, DELETE, PUT, OPTIONS\", %s found.", allowMethods)
  980. }
  981. }
  982. func TestDeleteImages(t *testing.T) {
  983. runtime := mkRuntime(t)
  984. defer nuke(runtime)
  985. srv := &Server{runtime: runtime}
  986. initialImages, err := srv.Images(false, "")
  987. if err != nil {
  988. t.Fatal(err)
  989. }
  990. if err := srv.runtime.repositories.Set("test", "test", unitTestImageName, true); err != nil {
  991. t.Fatal(err)
  992. }
  993. images, err := srv.Images(false, "")
  994. if err != nil {
  995. t.Fatal(err)
  996. }
  997. if len(images) != len(initialImages)+1 {
  998. t.Errorf("Expected %d images, %d found", len(initialImages)+1, len(images))
  999. }
  1000. req, err := http.NewRequest("DELETE", "/images/"+unitTestImageID, nil)
  1001. if err != nil {
  1002. t.Fatal(err)
  1003. }
  1004. r := httptest.NewRecorder()
  1005. if err := deleteImages(srv, APIVERSION, r, req, map[string]string{"name": unitTestImageID}); err == nil {
  1006. t.Fatalf("Expected conflict error, got none")
  1007. }
  1008. req2, err := http.NewRequest("DELETE", "/images/test:test", nil)
  1009. if err != nil {
  1010. t.Fatal(err)
  1011. }
  1012. r2 := httptest.NewRecorder()
  1013. if err := deleteImages(srv, APIVERSION, r2, req2, map[string]string{"name": "test:test"}); err != nil {
  1014. t.Fatal(err)
  1015. }
  1016. if r2.Code != http.StatusOK {
  1017. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  1018. }
  1019. var outs []APIRmi
  1020. if err := json.Unmarshal(r2.Body.Bytes(), &outs); err != nil {
  1021. t.Fatal(err)
  1022. }
  1023. if len(outs) != 1 {
  1024. t.Fatalf("Expected %d event (untagged), got %d", 1, len(outs))
  1025. }
  1026. images, err = srv.Images(false, "")
  1027. if err != nil {
  1028. t.Fatal(err)
  1029. }
  1030. if len(images) != len(initialImages) {
  1031. t.Errorf("Expected %d image, %d found", len(initialImages), len(images))
  1032. }
  1033. /* if c := runtime.Get(container.Id); c != nil {
  1034. t.Fatalf("The container as not been deleted")
  1035. }
  1036. if _, err := os.Stat(path.Join(container.rwPath(), "test")); err == nil {
  1037. t.Fatalf("The test file has not been deleted")
  1038. } */
  1039. }
  1040. func TestJsonContentType(t *testing.T) {
  1041. if !matchesContentType("application/json", "application/json") {
  1042. t.Fail()
  1043. }
  1044. if !matchesContentType("application/json; charset=utf-8", "application/json") {
  1045. t.Fail()
  1046. }
  1047. if matchesContentType("dockerapplication/json", "application/json") {
  1048. t.Fail()
  1049. }
  1050. }
  1051. func TestPostContainersCopy(t *testing.T) {
  1052. runtime := mkRuntime(t)
  1053. defer nuke(runtime)
  1054. srv := &Server{runtime: runtime}
  1055. // Create a container and remove a file
  1056. container, err := runtime.Create(
  1057. &Config{
  1058. Image: GetTestImage(runtime).ID,
  1059. Cmd: []string{"touch", "/test.txt"},
  1060. },
  1061. )
  1062. if err != nil {
  1063. t.Fatal(err)
  1064. }
  1065. defer runtime.Destroy(container)
  1066. if err := container.Run(); err != nil {
  1067. t.Fatal(err)
  1068. }
  1069. r := httptest.NewRecorder()
  1070. copyData := APICopy{HostPath: ".", Resource: "/test.txt"}
  1071. jsonData, err := json.Marshal(copyData)
  1072. if err != nil {
  1073. t.Fatal(err)
  1074. }
  1075. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/copy", bytes.NewReader(jsonData))
  1076. if err != nil {
  1077. t.Fatal(err)
  1078. }
  1079. req.Header.Add("Content-Type", "application/json")
  1080. if err = postContainersCopy(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  1081. t.Fatal(err)
  1082. }
  1083. if r.Code != http.StatusOK {
  1084. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  1085. }
  1086. found := false
  1087. for tarReader := tar.NewReader(r.Body); ; {
  1088. h, err := tarReader.Next()
  1089. if err != nil {
  1090. if err == io.EOF {
  1091. break
  1092. }
  1093. t.Fatal(err)
  1094. }
  1095. if h.Name == "test.txt" {
  1096. found = true
  1097. break
  1098. }
  1099. }
  1100. if !found {
  1101. t.Fatalf("The created test file has not been found in the copied output")
  1102. }
  1103. }
  1104. // Mocked types for tests
  1105. type NopConn struct {
  1106. io.ReadCloser
  1107. io.Writer
  1108. }
  1109. func (c *NopConn) LocalAddr() net.Addr { return nil }
  1110. func (c *NopConn) RemoteAddr() net.Addr { return nil }
  1111. func (c *NopConn) SetDeadline(t time.Time) error { return nil }
  1112. func (c *NopConn) SetReadDeadline(t time.Time) error { return nil }
  1113. func (c *NopConn) SetWriteDeadline(t time.Time) error { return nil }
  1114. type hijackTester struct {
  1115. *httptest.ResponseRecorder
  1116. in io.ReadCloser
  1117. out io.Writer
  1118. }
  1119. func (t *hijackTester) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  1120. bufrw := bufio.NewReadWriter(bufio.NewReader(t.in), bufio.NewWriter(t.out))
  1121. conn := &NopConn{
  1122. ReadCloser: t.in,
  1123. Writer: t.out,
  1124. }
  1125. return conn, bufrw, nil
  1126. }