api_test.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358
  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 strings.Contains(img.RepoTags[0], 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 TestGetImagesHistory(t *testing.T) {
  227. runtime := mkRuntime(t)
  228. defer nuke(runtime)
  229. srv := &Server{runtime: runtime}
  230. r := httptest.NewRecorder()
  231. if err := getImagesHistory(srv, APIVERSION, r, nil, map[string]string{"name": unitTestImageName}); err != nil {
  232. t.Fatal(err)
  233. }
  234. history := []APIHistory{}
  235. if err := json.Unmarshal(r.Body.Bytes(), &history); err != nil {
  236. t.Fatal(err)
  237. }
  238. if len(history) != 1 {
  239. t.Errorf("Expected 1 line, %d found", len(history))
  240. }
  241. }
  242. func TestGetImagesByName(t *testing.T) {
  243. runtime := mkRuntime(t)
  244. defer nuke(runtime)
  245. srv := &Server{runtime: runtime}
  246. r := httptest.NewRecorder()
  247. if err := getImagesByName(srv, APIVERSION, r, nil, map[string]string{"name": unitTestImageName}); err != nil {
  248. t.Fatal(err)
  249. }
  250. img := &Image{}
  251. if err := json.Unmarshal(r.Body.Bytes(), img); err != nil {
  252. t.Fatal(err)
  253. }
  254. if img.ID != unitTestImageID {
  255. t.Errorf("Error inspecting image")
  256. }
  257. }
  258. func TestGetContainersJSON(t *testing.T) {
  259. runtime := mkRuntime(t)
  260. defer nuke(runtime)
  261. srv := &Server{runtime: runtime}
  262. beginLen := runtime.containers.Len()
  263. container, _, err := runtime.Create(&Config{
  264. Image: GetTestImage(runtime).ID,
  265. Cmd: []string{"echo", "test"},
  266. }, "")
  267. if err != nil {
  268. t.Fatal(err)
  269. }
  270. defer runtime.Destroy(container)
  271. req, err := http.NewRequest("GET", "/containers/json?all=1", nil)
  272. if err != nil {
  273. t.Fatal(err)
  274. }
  275. r := httptest.NewRecorder()
  276. if err := getContainersJSON(srv, APIVERSION, r, req, nil); err != nil {
  277. t.Fatal(err)
  278. }
  279. containers := []APIContainers{}
  280. if err := json.Unmarshal(r.Body.Bytes(), &containers); err != nil {
  281. t.Fatal(err)
  282. }
  283. if len(containers) != beginLen+1 {
  284. t.Fatalf("Expected %d container, %d found (started with: %d)", beginLen+1, len(containers), beginLen)
  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. )
  302. if err != nil {
  303. t.Fatal(err)
  304. }
  305. defer runtime.Destroy(container)
  306. if err := container.Run(); err != nil {
  307. t.Fatal(err)
  308. }
  309. r := httptest.NewRecorder()
  310. if err = getContainersExport(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  311. t.Fatal(err)
  312. }
  313. if r.Code != http.StatusOK {
  314. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  315. }
  316. found := false
  317. for tarReader := tar.NewReader(r.Body); ; {
  318. h, err := tarReader.Next()
  319. if err != nil {
  320. if err == io.EOF {
  321. break
  322. }
  323. t.Fatal(err)
  324. }
  325. if h.Name == "./test" {
  326. found = true
  327. break
  328. }
  329. }
  330. if !found {
  331. t.Fatalf("The created test file has not been found in the exported image")
  332. }
  333. }
  334. func TestGetContainersChanges(t *testing.T) {
  335. runtime := mkRuntime(t)
  336. defer nuke(runtime)
  337. srv := &Server{runtime: runtime}
  338. // Create a container and remove a file
  339. container, _, err := runtime.Create(
  340. &Config{
  341. Image: GetTestImage(runtime).ID,
  342. Cmd: []string{"/bin/rm", "/etc/passwd"},
  343. },
  344. "",
  345. )
  346. if err != nil {
  347. t.Fatal(err)
  348. }
  349. defer runtime.Destroy(container)
  350. if err := container.Run(); err != nil {
  351. t.Fatal(err)
  352. }
  353. r := httptest.NewRecorder()
  354. if err := getContainersChanges(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  355. t.Fatal(err)
  356. }
  357. changes := []Change{}
  358. if err := json.Unmarshal(r.Body.Bytes(), &changes); err != nil {
  359. t.Fatal(err)
  360. }
  361. // Check the changelog
  362. success := false
  363. for _, elem := range changes {
  364. if elem.Path == "/etc/passwd" && elem.Kind == 2 {
  365. success = true
  366. }
  367. }
  368. if !success {
  369. t.Fatalf("/etc/passwd as been removed but is not present in the diff")
  370. }
  371. }
  372. func TestGetContainersTop(t *testing.T) {
  373. t.Skip("Fixme. Skipping test for now. Reported error when testing using dind: 'api_test.go:527: Expected 2 processes, found 0.'")
  374. runtime := mkRuntime(t)
  375. defer nuke(runtime)
  376. srv := &Server{runtime: runtime}
  377. container, _, err := runtime.Create(
  378. &Config{
  379. Image: GetTestImage(runtime).ID,
  380. Cmd: []string{"/bin/sh", "-c", "cat"},
  381. OpenStdin: true,
  382. },
  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. if err := container.Start(); err != nil {
  395. t.Fatal(err)
  396. }
  397. setTimeout(t, "Waiting for the container to be started timed out", 10*time.Second, func() {
  398. for {
  399. if container.State.Running {
  400. break
  401. }
  402. time.Sleep(10 * time.Millisecond)
  403. }
  404. })
  405. if !container.State.Running {
  406. t.Fatalf("Container should be running")
  407. }
  408. // Make sure sh spawn up cat
  409. setTimeout(t, "read/write assertion timed out", 2*time.Second, func() {
  410. in, _ := container.StdinPipe()
  411. out, _ := container.StdoutPipe()
  412. if err := assertPipe("hello\n", "hello", out, in, 15); err != nil {
  413. t.Fatal(err)
  414. }
  415. })
  416. r := httptest.NewRecorder()
  417. req, err := http.NewRequest("GET", "/"+container.ID+"/top?ps_args=u", bytes.NewReader([]byte{}))
  418. if err != nil {
  419. t.Fatal(err)
  420. }
  421. if err := getContainersTop(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  422. t.Fatal(err)
  423. }
  424. procs := APITop{}
  425. if err := json.Unmarshal(r.Body.Bytes(), &procs); err != nil {
  426. t.Fatal(err)
  427. }
  428. if len(procs.Titles) != 11 {
  429. t.Fatalf("Expected 11 titles, found %d.", len(procs.Titles))
  430. }
  431. if procs.Titles[0] != "USER" || procs.Titles[10] != "COMMAND" {
  432. t.Fatalf("Expected Titles[0] to be USER and Titles[10] to be COMMAND, found %s and %s.", procs.Titles[0], procs.Titles[10])
  433. }
  434. if len(procs.Processes) != 2 {
  435. t.Fatalf("Expected 2 processes, found %d.", len(procs.Processes))
  436. }
  437. if procs.Processes[0][10] != "/bin/sh" && procs.Processes[0][10] != "cat" {
  438. t.Fatalf("Expected `cat` or `/bin/sh`, found %s.", procs.Processes[0][10])
  439. }
  440. if procs.Processes[1][10] != "/bin/sh" && procs.Processes[1][10] != "cat" {
  441. t.Fatalf("Expected `cat` or `/bin/sh`, found %s.", procs.Processes[1][10])
  442. }
  443. }
  444. func TestGetContainersByName(t *testing.T) {
  445. runtime := mkRuntime(t)
  446. defer nuke(runtime)
  447. srv := &Server{runtime: runtime}
  448. // Create a container and remove a file
  449. container, _, err := runtime.Create(
  450. &Config{
  451. Image: GetTestImage(runtime).ID,
  452. Cmd: []string{"echo", "test"},
  453. },
  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. )
  484. if err != nil {
  485. t.Fatal(err)
  486. }
  487. defer runtime.Destroy(container)
  488. if err := container.Run(); err != nil {
  489. t.Fatal(err)
  490. }
  491. req, err := http.NewRequest("POST", "/commit?repo=testrepo&testtag=tag&container="+container.ID, bytes.NewReader([]byte{}))
  492. if err != nil {
  493. t.Fatal(err)
  494. }
  495. r := httptest.NewRecorder()
  496. if err := postCommit(srv, APIVERSION, r, req, nil); err != nil {
  497. t.Fatal(err)
  498. }
  499. if r.Code != http.StatusCreated {
  500. t.Fatalf("%d Created expected, received %d\n", http.StatusCreated, r.Code)
  501. }
  502. apiID := &APIID{}
  503. if err := json.Unmarshal(r.Body.Bytes(), apiID); err != nil {
  504. t.Fatal(err)
  505. }
  506. if _, err := runtime.graph.Get(apiID.ID); err != nil {
  507. t.Fatalf("The image has not been commited")
  508. }
  509. }
  510. func TestPostContainersCreate(t *testing.T) {
  511. eng := NewTestEngine(t)
  512. srv := mkServerFromEngine(eng, t)
  513. runtime := srv.runtime
  514. defer nuke(runtime)
  515. configJSON, err := json.Marshal(&Config{
  516. Image: GetTestImage(runtime).ID,
  517. Memory: 33554432,
  518. Cmd: []string{"touch", "/test"},
  519. })
  520. if err != nil {
  521. t.Fatal(err)
  522. }
  523. req, err := http.NewRequest("POST", "/containers/create", bytes.NewReader(configJSON))
  524. if err != nil {
  525. t.Fatal(err)
  526. }
  527. r := httptest.NewRecorder()
  528. if err := postContainersCreate(srv, APIVERSION, r, req, nil); err != nil {
  529. t.Fatal(err)
  530. }
  531. if r.Code != http.StatusCreated {
  532. t.Fatalf("%d Created expected, received %d\n", http.StatusCreated, r.Code)
  533. }
  534. apiRun := &APIRun{}
  535. if err := json.Unmarshal(r.Body.Bytes(), apiRun); err != nil {
  536. t.Fatal(err)
  537. }
  538. container := srv.runtime.Get(apiRun.ID)
  539. if container == nil {
  540. t.Fatalf("Container not created")
  541. }
  542. if err := container.Run(); err != nil {
  543. t.Fatal(err)
  544. }
  545. if _, err := os.Stat(path.Join(container.rwPath(), "test")); err != nil {
  546. if os.IsNotExist(err) {
  547. utils.Debugf("Err: %s", err)
  548. t.Fatalf("The test file has not been created")
  549. }
  550. t.Fatal(err)
  551. }
  552. }
  553. func TestPostContainersKill(t *testing.T) {
  554. runtime := mkRuntime(t)
  555. defer nuke(runtime)
  556. srv := &Server{runtime: runtime}
  557. container, _, err := runtime.Create(
  558. &Config{
  559. Image: GetTestImage(runtime).ID,
  560. Cmd: []string{"/bin/cat"},
  561. OpenStdin: true,
  562. },
  563. "",
  564. )
  565. if err != nil {
  566. t.Fatal(err)
  567. }
  568. defer runtime.Destroy(container)
  569. if err := container.Start(); err != nil {
  570. t.Fatal(err)
  571. }
  572. // Give some time to the process to start
  573. container.WaitTimeout(500 * time.Millisecond)
  574. if !container.State.Running {
  575. t.Errorf("Container should be running")
  576. }
  577. r := httptest.NewRecorder()
  578. if err := postContainersKill(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  579. t.Fatal(err)
  580. }
  581. if r.Code != http.StatusNoContent {
  582. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  583. }
  584. if container.State.Running {
  585. t.Fatalf("The container hasn't been killed")
  586. }
  587. }
  588. func TestPostContainersRestart(t *testing.T) {
  589. runtime := mkRuntime(t)
  590. defer nuke(runtime)
  591. srv := &Server{runtime: runtime}
  592. container, _, err := runtime.Create(
  593. &Config{
  594. Image: GetTestImage(runtime).ID,
  595. Cmd: []string{"/bin/top"},
  596. OpenStdin: true,
  597. },
  598. "",
  599. )
  600. if err != nil {
  601. t.Fatal(err)
  602. }
  603. defer runtime.Destroy(container)
  604. if err := container.Start(); err != nil {
  605. t.Fatal(err)
  606. }
  607. // Give some time to the process to start
  608. container.WaitTimeout(500 * time.Millisecond)
  609. if !container.State.Running {
  610. t.Errorf("Container should be running")
  611. }
  612. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/restart?t=1", bytes.NewReader([]byte{}))
  613. if err != nil {
  614. t.Fatal(err)
  615. }
  616. r := httptest.NewRecorder()
  617. if err := postContainersRestart(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  618. t.Fatal(err)
  619. }
  620. if r.Code != http.StatusNoContent {
  621. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  622. }
  623. // Give some time to the process to restart
  624. container.WaitTimeout(500 * time.Millisecond)
  625. if !container.State.Running {
  626. t.Fatalf("Container should be running")
  627. }
  628. if err := container.Kill(); err != nil {
  629. t.Fatal(err)
  630. }
  631. }
  632. func TestPostContainersStart(t *testing.T) {
  633. eng := NewTestEngine(t)
  634. srv := mkServerFromEngine(eng, t)
  635. runtime := srv.runtime
  636. defer nuke(runtime)
  637. id := createTestContainer(
  638. eng,
  639. &Config{
  640. Image: GetTestImage(runtime).ID,
  641. Cmd: []string{"/bin/cat"},
  642. OpenStdin: true,
  643. },
  644. t)
  645. hostConfigJSON, err := json.Marshal(&HostConfig{})
  646. req, err := http.NewRequest("POST", "/containers/"+id+"/start", bytes.NewReader(hostConfigJSON))
  647. if err != nil {
  648. t.Fatal(err)
  649. }
  650. req.Header.Set("Content-Type", "application/json")
  651. r := httptest.NewRecorder()
  652. if err := postContainersStart(srv, APIVERSION, r, req, map[string]string{"name": id}); err != nil {
  653. t.Fatal(err)
  654. }
  655. if r.Code != http.StatusNoContent {
  656. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  657. }
  658. container := runtime.Get(id)
  659. if container == nil {
  660. t.Fatalf("Container %s was not created", id)
  661. }
  662. // Give some time to the process to start
  663. // FIXME: use Wait once it's available as a job
  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": 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/top"},
  684. OpenStdin: true,
  685. },
  686. "",
  687. )
  688. if err != nil {
  689. t.Fatal(err)
  690. }
  691. defer runtime.Destroy(container)
  692. if err := container.Start(); 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. )
  728. if err != nil {
  729. t.Fatal(err)
  730. }
  731. defer runtime.Destroy(container)
  732. if err := container.Start(); 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. )
  764. if err != nil {
  765. t.Fatal(err)
  766. }
  767. defer runtime.Destroy(container)
  768. // Start the process
  769. if err := container.Start(); 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. )
  837. if err != nil {
  838. t.Fatal(err)
  839. }
  840. defer runtime.Destroy(container)
  841. // Start the process
  842. if err := container.Start(); 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. runtime.config.EnableCors = true
  938. srv := &Server{runtime: runtime}
  939. r := httptest.NewRecorder()
  940. router, err := createRouter(srv, false)
  941. if err != nil {
  942. t.Fatal(err)
  943. }
  944. req, err := http.NewRequest("OPTIONS", "/", nil)
  945. if err != nil {
  946. t.Fatal(err)
  947. }
  948. router.ServeHTTP(r, req)
  949. if r.Code != http.StatusOK {
  950. t.Errorf("Expected response for OPTIONS request to be \"200\", %v found.", r.Code)
  951. }
  952. }
  953. func TestGetEnabledCors(t *testing.T) {
  954. runtime := mkRuntime(t)
  955. defer nuke(runtime)
  956. runtime.config.EnableCors = true
  957. srv := &Server{runtime: runtime}
  958. r := httptest.NewRecorder()
  959. router, err := createRouter(srv, false)
  960. if err != nil {
  961. t.Fatal(err)
  962. }
  963. req, err := http.NewRequest("GET", "/version", nil)
  964. if err != nil {
  965. t.Fatal(err)
  966. }
  967. router.ServeHTTP(r, req)
  968. if r.Code != http.StatusOK {
  969. t.Errorf("Expected response for OPTIONS request to be \"200\", %v found.", r.Code)
  970. }
  971. allowOrigin := r.Header().Get("Access-Control-Allow-Origin")
  972. allowHeaders := r.Header().Get("Access-Control-Allow-Headers")
  973. allowMethods := r.Header().Get("Access-Control-Allow-Methods")
  974. if allowOrigin != "*" {
  975. t.Errorf("Expected header Access-Control-Allow-Origin to be \"*\", %s found.", allowOrigin)
  976. }
  977. if allowHeaders != "Origin, X-Requested-With, Content-Type, Accept" {
  978. t.Errorf("Expected header Access-Control-Allow-Headers to be \"Origin, X-Requested-With, Content-Type, Accept\", %s found.", allowHeaders)
  979. }
  980. if allowMethods != "GET, POST, DELETE, PUT, OPTIONS" {
  981. t.Errorf("Expected hearder Access-Control-Allow-Methods to be \"GET, POST, DELETE, PUT, OPTIONS\", %s found.", allowMethods)
  982. }
  983. }
  984. func TestDeleteImages(t *testing.T) {
  985. runtime := mkRuntime(t)
  986. defer nuke(runtime)
  987. srv := &Server{runtime: runtime}
  988. initialImages, err := srv.Images(false, "")
  989. if err != nil {
  990. t.Fatal(err)
  991. }
  992. if err := srv.runtime.repositories.Set("test", "test", unitTestImageName, true); err != nil {
  993. t.Fatal(err)
  994. }
  995. images, err := srv.Images(false, "")
  996. if err != nil {
  997. t.Fatal(err)
  998. }
  999. if len(images[0].RepoTags) != len(initialImages[0].RepoTags)+1 {
  1000. t.Errorf("Expected %d images, %d found", len(initialImages)+1, len(images))
  1001. }
  1002. req, err := http.NewRequest("DELETE", "/images/"+unitTestImageID, nil)
  1003. if err != nil {
  1004. t.Fatal(err)
  1005. }
  1006. r := httptest.NewRecorder()
  1007. if err := deleteImages(srv, APIVERSION, r, req, map[string]string{"name": unitTestImageID}); err == nil {
  1008. t.Fatalf("Expected conflict error, got none")
  1009. }
  1010. req2, err := http.NewRequest("DELETE", "/images/test:test", nil)
  1011. if err != nil {
  1012. t.Fatal(err)
  1013. }
  1014. r2 := httptest.NewRecorder()
  1015. if err := deleteImages(srv, APIVERSION, r2, req2, map[string]string{"name": "test:test"}); err != nil {
  1016. t.Fatal(err)
  1017. }
  1018. if r2.Code != http.StatusOK {
  1019. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  1020. }
  1021. var outs []APIRmi
  1022. if err := json.Unmarshal(r2.Body.Bytes(), &outs); err != nil {
  1023. t.Fatal(err)
  1024. }
  1025. if len(outs) != 1 {
  1026. t.Fatalf("Expected %d event (untagged), got %d", 1, len(outs))
  1027. }
  1028. images, err = srv.Images(false, "")
  1029. if err != nil {
  1030. t.Fatal(err)
  1031. }
  1032. if len(images[0].RepoTags) != len(initialImages[0].RepoTags) {
  1033. t.Errorf("Expected %d image, %d found", len(initialImages), len(images))
  1034. }
  1035. /* if c := runtime.Get(container.Id); c != nil {
  1036. t.Fatalf("The container as not been deleted")
  1037. }
  1038. if _, err := os.Stat(path.Join(container.rwPath(), "test")); err == nil {
  1039. t.Fatalf("The test file has not been deleted")
  1040. } */
  1041. }
  1042. func TestJsonContentType(t *testing.T) {
  1043. if !matchesContentType("application/json", "application/json") {
  1044. t.Fail()
  1045. }
  1046. if !matchesContentType("application/json; charset=utf-8", "application/json") {
  1047. t.Fail()
  1048. }
  1049. if matchesContentType("dockerapplication/json", "application/json") {
  1050. t.Fail()
  1051. }
  1052. }
  1053. func TestPostContainersCopy(t *testing.T) {
  1054. runtime := mkRuntime(t)
  1055. defer nuke(runtime)
  1056. srv := &Server{runtime: runtime}
  1057. // Create a container and remove a file
  1058. container, _, err := runtime.Create(
  1059. &Config{
  1060. Image: GetTestImage(runtime).ID,
  1061. Cmd: []string{"touch", "/test.txt"},
  1062. },
  1063. "",
  1064. )
  1065. if err != nil {
  1066. t.Fatal(err)
  1067. }
  1068. defer runtime.Destroy(container)
  1069. if err := container.Run(); err != nil {
  1070. t.Fatal(err)
  1071. }
  1072. r := httptest.NewRecorder()
  1073. copyData := APICopy{HostPath: ".", Resource: "/test.txt"}
  1074. jsonData, err := json.Marshal(copyData)
  1075. if err != nil {
  1076. t.Fatal(err)
  1077. }
  1078. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/copy", bytes.NewReader(jsonData))
  1079. if err != nil {
  1080. t.Fatal(err)
  1081. }
  1082. req.Header.Add("Content-Type", "application/json")
  1083. if err = postContainersCopy(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  1084. t.Fatal(err)
  1085. }
  1086. if r.Code != http.StatusOK {
  1087. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  1088. }
  1089. found := false
  1090. for tarReader := tar.NewReader(r.Body); ; {
  1091. h, err := tarReader.Next()
  1092. if err != nil {
  1093. if err == io.EOF {
  1094. break
  1095. }
  1096. t.Fatal(err)
  1097. }
  1098. if h.Name == "test.txt" {
  1099. found = true
  1100. break
  1101. }
  1102. }
  1103. if !found {
  1104. t.Fatalf("The created test file has not been found in the copied output")
  1105. }
  1106. }
  1107. // Mocked types for tests
  1108. type NopConn struct {
  1109. io.ReadCloser
  1110. io.Writer
  1111. }
  1112. func (c *NopConn) LocalAddr() net.Addr { return nil }
  1113. func (c *NopConn) RemoteAddr() net.Addr { return nil }
  1114. func (c *NopConn) SetDeadline(t time.Time) error { return nil }
  1115. func (c *NopConn) SetReadDeadline(t time.Time) error { return nil }
  1116. func (c *NopConn) SetWriteDeadline(t time.Time) error { return nil }
  1117. type hijackTester struct {
  1118. *httptest.ResponseRecorder
  1119. in io.ReadCloser
  1120. out io.Writer
  1121. }
  1122. func (t *hijackTester) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  1123. bufrw := bufio.NewReadWriter(bufio.NewReader(t.in), bufio.NewWriter(t.out))
  1124. conn := &NopConn{
  1125. ReadCloser: t.in,
  1126. Writer: t.out,
  1127. }
  1128. return conn, bufrw, nil
  1129. }