api_test.go 31 KB

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