api_test.go 32 KB

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