api_test.go 26 KB

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