api_test.go 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  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. req, err := http.NewRequest("GET", "/"+container.ID+"/top?ps_args=u", bytes.NewReader([]byte{}))
  367. if err != nil {
  368. t.Fatal(err)
  369. }
  370. if err := getContainersTop(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  371. t.Fatal(err)
  372. }
  373. procs := APITop{}
  374. if err := json.Unmarshal(r.Body.Bytes(), &procs); err != nil {
  375. t.Fatal(err)
  376. }
  377. if len(procs.Titles) != 11 {
  378. t.Fatalf("Expected 11 titles, found %d.", len(procs.Titles))
  379. }
  380. if procs.Titles[0] != "USER" || procs.Titles[10] != "COMMAND" {
  381. t.Fatalf("Expected Titles[0] to be USER and Titles[10] to be COMMAND, found %s and %s.", procs.Titles[0], procs.Titles[10])
  382. }
  383. if len(procs.Processes) != 2 {
  384. t.Fatalf("Expected 2 processes, found %d.", len(procs.Processes))
  385. }
  386. if procs.Processes[0][10] != "/bin/sh" && procs.Processes[0][10] != "sleep" {
  387. t.Fatalf("Expected `sleep` or `/bin/sh`, found %s.", procs.Processes[0][10])
  388. }
  389. if procs.Processes[1][10] != "/bin/sh" && procs.Processes[1][10] != "sleep" {
  390. t.Fatalf("Expected `sleep` or `/bin/sh`, found %s.", procs.Processes[1][10])
  391. }
  392. }
  393. func TestGetContainersByName(t *testing.T) {
  394. runtime := mkRuntime(t)
  395. defer nuke(runtime)
  396. srv := &Server{runtime: runtime}
  397. builder := NewBuilder(runtime)
  398. // Create a container and remove a file
  399. container, err := builder.Create(
  400. &Config{
  401. Image: GetTestImage(runtime).ID,
  402. Cmd: []string{"echo", "test"},
  403. },
  404. )
  405. if err != nil {
  406. t.Fatal(err)
  407. }
  408. defer runtime.Destroy(container)
  409. r := httptest.NewRecorder()
  410. if err := getContainersByName(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  411. t.Fatal(err)
  412. }
  413. outContainer := &Container{}
  414. if err := json.Unmarshal(r.Body.Bytes(), outContainer); err != nil {
  415. t.Fatal(err)
  416. }
  417. if outContainer.ID != container.ID {
  418. t.Fatalf("Wrong containers retrieved. Expected %s, recieved %s", container.ID, outContainer.ID)
  419. }
  420. }
  421. func TestPostCommit(t *testing.T) {
  422. runtime := mkRuntime(t)
  423. defer nuke(runtime)
  424. srv := &Server{runtime: runtime}
  425. builder := NewBuilder(runtime)
  426. // Create a container and remove a file
  427. container, err := builder.Create(
  428. &Config{
  429. Image: GetTestImage(runtime).ID,
  430. Cmd: []string{"touch", "/test"},
  431. },
  432. )
  433. if err != nil {
  434. t.Fatal(err)
  435. }
  436. defer runtime.Destroy(container)
  437. if err := container.Run(); err != nil {
  438. t.Fatal(err)
  439. }
  440. req, err := http.NewRequest("POST", "/commit?repo=testrepo&testtag=tag&container="+container.ID, bytes.NewReader([]byte{}))
  441. if err != nil {
  442. t.Fatal(err)
  443. }
  444. r := httptest.NewRecorder()
  445. if err := postCommit(srv, APIVERSION, r, req, nil); err != nil {
  446. t.Fatal(err)
  447. }
  448. if r.Code != http.StatusCreated {
  449. t.Fatalf("%d Created expected, received %d\n", http.StatusCreated, r.Code)
  450. }
  451. apiID := &APIID{}
  452. if err := json.Unmarshal(r.Body.Bytes(), apiID); err != nil {
  453. t.Fatal(err)
  454. }
  455. if _, err := runtime.graph.Get(apiID.ID); err != nil {
  456. t.Fatalf("The image has not been commited")
  457. }
  458. }
  459. func TestPostContainersCreate(t *testing.T) {
  460. runtime := mkRuntime(t)
  461. defer nuke(runtime)
  462. srv := &Server{runtime: runtime}
  463. configJSON, err := json.Marshal(&Config{
  464. Image: GetTestImage(runtime).ID,
  465. Memory: 33554432,
  466. Cmd: []string{"touch", "/test"},
  467. })
  468. if err != nil {
  469. t.Fatal(err)
  470. }
  471. req, err := http.NewRequest("POST", "/containers/create", bytes.NewReader(configJSON))
  472. if err != nil {
  473. t.Fatal(err)
  474. }
  475. r := httptest.NewRecorder()
  476. if err := postContainersCreate(srv, APIVERSION, r, req, nil); err != nil {
  477. t.Fatal(err)
  478. }
  479. if r.Code != http.StatusCreated {
  480. t.Fatalf("%d Created expected, received %d\n", http.StatusCreated, r.Code)
  481. }
  482. apiRun := &APIRun{}
  483. if err := json.Unmarshal(r.Body.Bytes(), apiRun); err != nil {
  484. t.Fatal(err)
  485. }
  486. container := srv.runtime.Get(apiRun.ID)
  487. if container == nil {
  488. t.Fatalf("Container not created")
  489. }
  490. if err := container.Run(); err != nil {
  491. t.Fatal(err)
  492. }
  493. if _, err := os.Stat(path.Join(container.rwPath(), "test")); err != nil {
  494. if os.IsNotExist(err) {
  495. utils.Debugf("Err: %s", err)
  496. t.Fatalf("The test file has not been created")
  497. }
  498. t.Fatal(err)
  499. }
  500. }
  501. func TestPostContainersKill(t *testing.T) {
  502. runtime := mkRuntime(t)
  503. defer nuke(runtime)
  504. srv := &Server{runtime: runtime}
  505. container, err := NewBuilder(runtime).Create(
  506. &Config{
  507. Image: GetTestImage(runtime).ID,
  508. Cmd: []string{"/bin/cat"},
  509. OpenStdin: true,
  510. },
  511. )
  512. if err != nil {
  513. t.Fatal(err)
  514. }
  515. defer runtime.Destroy(container)
  516. hostConfig := &HostConfig{}
  517. if err := container.Start(hostConfig); err != nil {
  518. t.Fatal(err)
  519. }
  520. // Give some time to the process to start
  521. container.WaitTimeout(500 * time.Millisecond)
  522. if !container.State.Running {
  523. t.Errorf("Container should be running")
  524. }
  525. r := httptest.NewRecorder()
  526. if err := postContainersKill(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  527. t.Fatal(err)
  528. }
  529. if r.Code != http.StatusNoContent {
  530. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  531. }
  532. if container.State.Running {
  533. t.Fatalf("The container hasn't been killed")
  534. }
  535. }
  536. func TestPostContainersRestart(t *testing.T) {
  537. runtime := mkRuntime(t)
  538. defer nuke(runtime)
  539. srv := &Server{runtime: runtime}
  540. container, err := NewBuilder(runtime).Create(
  541. &Config{
  542. Image: GetTestImage(runtime).ID,
  543. Cmd: []string{"/bin/cat"},
  544. OpenStdin: true,
  545. },
  546. )
  547. if err != nil {
  548. t.Fatal(err)
  549. }
  550. defer runtime.Destroy(container)
  551. hostConfig := &HostConfig{}
  552. if err := container.Start(hostConfig); err != nil {
  553. t.Fatal(err)
  554. }
  555. // Give some time to the process to start
  556. container.WaitTimeout(500 * time.Millisecond)
  557. if !container.State.Running {
  558. t.Errorf("Container should be running")
  559. }
  560. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/restart?t=1", bytes.NewReader([]byte{}))
  561. if err != nil {
  562. t.Fatal(err)
  563. }
  564. r := httptest.NewRecorder()
  565. if err := postContainersRestart(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  566. t.Fatal(err)
  567. }
  568. if r.Code != http.StatusNoContent {
  569. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  570. }
  571. // Give some time to the process to restart
  572. container.WaitTimeout(500 * time.Millisecond)
  573. if !container.State.Running {
  574. t.Fatalf("Container should be running")
  575. }
  576. if err := container.Kill(); err != nil {
  577. t.Fatal(err)
  578. }
  579. }
  580. func TestPostContainersStart(t *testing.T) {
  581. runtime := mkRuntime(t)
  582. defer nuke(runtime)
  583. srv := &Server{runtime: runtime}
  584. container, err := NewBuilder(runtime).Create(
  585. &Config{
  586. Image: GetTestImage(runtime).ID,
  587. Cmd: []string{"/bin/cat"},
  588. OpenStdin: true,
  589. },
  590. )
  591. if err != nil {
  592. t.Fatal(err)
  593. }
  594. defer runtime.Destroy(container)
  595. hostConfigJSON, err := json.Marshal(&HostConfig{})
  596. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/start", bytes.NewReader(hostConfigJSON))
  597. if err != nil {
  598. t.Fatal(err)
  599. }
  600. r := httptest.NewRecorder()
  601. if err := postContainersStart(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  602. t.Fatal(err)
  603. }
  604. if r.Code != http.StatusNoContent {
  605. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  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. r = httptest.NewRecorder()
  613. if err = postContainersStart(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err == nil {
  614. t.Fatalf("A running containter should be able to be started")
  615. }
  616. if err := container.Kill(); err != nil {
  617. t.Fatal(err)
  618. }
  619. }
  620. func TestPostContainersStop(t *testing.T) {
  621. runtime := mkRuntime(t)
  622. defer nuke(runtime)
  623. srv := &Server{runtime: runtime}
  624. container, err := NewBuilder(runtime).Create(
  625. &Config{
  626. Image: GetTestImage(runtime).ID,
  627. Cmd: []string{"/bin/cat"},
  628. OpenStdin: true,
  629. },
  630. )
  631. if err != nil {
  632. t.Fatal(err)
  633. }
  634. defer runtime.Destroy(container)
  635. hostConfig := &HostConfig{}
  636. if err := container.Start(hostConfig); err != nil {
  637. t.Fatal(err)
  638. }
  639. // Give some time to the process to start
  640. container.WaitTimeout(500 * time.Millisecond)
  641. if !container.State.Running {
  642. t.Errorf("Container should be running")
  643. }
  644. // Note: as it is a POST request, it requires a body.
  645. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/stop?t=1", bytes.NewReader([]byte{}))
  646. if err != nil {
  647. t.Fatal(err)
  648. }
  649. r := httptest.NewRecorder()
  650. if err := postContainersStop(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  651. t.Fatal(err)
  652. }
  653. if r.Code != http.StatusNoContent {
  654. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  655. }
  656. if container.State.Running {
  657. t.Fatalf("The container hasn't been stopped")
  658. }
  659. }
  660. func TestPostContainersWait(t *testing.T) {
  661. runtime := mkRuntime(t)
  662. defer nuke(runtime)
  663. srv := &Server{runtime: runtime}
  664. container, err := NewBuilder(runtime).Create(
  665. &Config{
  666. Image: GetTestImage(runtime).ID,
  667. Cmd: []string{"/bin/sleep", "1"},
  668. OpenStdin: true,
  669. },
  670. )
  671. if err != nil {
  672. t.Fatal(err)
  673. }
  674. defer runtime.Destroy(container)
  675. hostConfig := &HostConfig{}
  676. if err := container.Start(hostConfig); err != nil {
  677. t.Fatal(err)
  678. }
  679. setTimeout(t, "Wait timed out", 3*time.Second, func() {
  680. r := httptest.NewRecorder()
  681. if err := postContainersWait(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  682. t.Fatal(err)
  683. }
  684. apiWait := &APIWait{}
  685. if err := json.Unmarshal(r.Body.Bytes(), apiWait); err != nil {
  686. t.Fatal(err)
  687. }
  688. if apiWait.StatusCode != 0 {
  689. t.Fatalf("Non zero exit code for sleep: %d\n", apiWait.StatusCode)
  690. }
  691. })
  692. if container.State.Running {
  693. t.Fatalf("The container should be stopped after wait")
  694. }
  695. }
  696. func TestPostContainersAttach(t *testing.T) {
  697. runtime := mkRuntime(t)
  698. defer nuke(runtime)
  699. srv := &Server{runtime: runtime}
  700. container, err := NewBuilder(runtime).Create(
  701. &Config{
  702. Image: GetTestImage(runtime).ID,
  703. Cmd: []string{"/bin/cat"},
  704. OpenStdin: true,
  705. },
  706. )
  707. if err != nil {
  708. t.Fatal(err)
  709. }
  710. defer runtime.Destroy(container)
  711. // Start the process
  712. hostConfig := &HostConfig{}
  713. if err := container.Start(hostConfig); err != nil {
  714. t.Fatal(err)
  715. }
  716. stdin, stdinPipe := io.Pipe()
  717. stdout, stdoutPipe := io.Pipe()
  718. // Attach to it
  719. c1 := make(chan struct{})
  720. go func() {
  721. defer close(c1)
  722. r := &hijackTester{
  723. ResponseRecorder: httptest.NewRecorder(),
  724. in: stdin,
  725. out: stdoutPipe,
  726. }
  727. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/attach?stream=1&stdin=1&stdout=1&stderr=1", bytes.NewReader([]byte{}))
  728. if err != nil {
  729. t.Fatal(err)
  730. }
  731. if err := postContainersAttach(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  732. t.Fatal(err)
  733. }
  734. }()
  735. // Acknowledge hijack
  736. setTimeout(t, "hijack acknowledge timed out", 2*time.Second, func() {
  737. stdout.Read([]byte{})
  738. stdout.Read(make([]byte, 4096))
  739. })
  740. setTimeout(t, "read/write assertion timed out", 2*time.Second, func() {
  741. if err := assertPipe("hello\n", "hello", stdout, stdinPipe, 15); err != nil {
  742. t.Fatal(err)
  743. }
  744. })
  745. // Close pipes (client disconnects)
  746. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  747. t.Fatal(err)
  748. }
  749. // Wait for attach to finish, the client disconnected, therefore, Attach finished his job
  750. setTimeout(t, "Waiting for CmdAttach timed out", 2*time.Second, func() {
  751. <-c1
  752. })
  753. // We closed stdin, expect /bin/cat to still be running
  754. // Wait a little bit to make sure container.monitor() did his thing
  755. err = container.WaitTimeout(500 * time.Millisecond)
  756. if err == nil || !container.State.Running {
  757. t.Fatalf("/bin/cat is not running after closing stdin")
  758. }
  759. // Try to avoid the timeoout in destroy. Best effort, don't check error
  760. cStdin, _ := container.StdinPipe()
  761. cStdin.Close()
  762. container.Wait()
  763. }
  764. // FIXME: Test deleting running container
  765. // FIXME: Test deleting container with volume
  766. // FIXME: Test deleting volume in use by other container
  767. func TestDeleteContainers(t *testing.T) {
  768. runtime := mkRuntime(t)
  769. defer nuke(runtime)
  770. srv := &Server{runtime: runtime}
  771. container, err := NewBuilder(runtime).Create(&Config{
  772. Image: GetTestImage(runtime).ID,
  773. Cmd: []string{"touch", "/test"},
  774. })
  775. if err != nil {
  776. t.Fatal(err)
  777. }
  778. defer runtime.Destroy(container)
  779. if err := container.Run(); err != nil {
  780. t.Fatal(err)
  781. }
  782. req, err := http.NewRequest("DELETE", "/containers/"+container.ID, nil)
  783. if err != nil {
  784. t.Fatal(err)
  785. }
  786. r := httptest.NewRecorder()
  787. if err := deleteContainers(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  788. t.Fatal(err)
  789. }
  790. if r.Code != http.StatusNoContent {
  791. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  792. }
  793. if c := runtime.Get(container.ID); c != nil {
  794. t.Fatalf("The container as not been deleted")
  795. }
  796. if _, err := os.Stat(path.Join(container.rwPath(), "test")); err == nil {
  797. t.Fatalf("The test file has not been deleted")
  798. }
  799. }
  800. func TestOptionsRoute(t *testing.T) {
  801. runtime := mkRuntime(t)
  802. defer nuke(runtime)
  803. srv := &Server{runtime: runtime, enableCors: true}
  804. r := httptest.NewRecorder()
  805. router, err := createRouter(srv, false)
  806. if err != nil {
  807. t.Fatal(err)
  808. }
  809. req, err := http.NewRequest("OPTIONS", "/", nil)
  810. if err != nil {
  811. t.Fatal(err)
  812. }
  813. router.ServeHTTP(r, req)
  814. if r.Code != http.StatusOK {
  815. t.Errorf("Expected response for OPTIONS request to be \"200\", %v found.", r.Code)
  816. }
  817. }
  818. func TestGetEnabledCors(t *testing.T) {
  819. runtime := mkRuntime(t)
  820. defer nuke(runtime)
  821. srv := &Server{runtime: runtime, enableCors: true}
  822. r := httptest.NewRecorder()
  823. router, err := createRouter(srv, false)
  824. if err != nil {
  825. t.Fatal(err)
  826. }
  827. req, err := http.NewRequest("GET", "/version", nil)
  828. if err != nil {
  829. t.Fatal(err)
  830. }
  831. router.ServeHTTP(r, req)
  832. if r.Code != http.StatusOK {
  833. t.Errorf("Expected response for OPTIONS request to be \"200\", %v found.", r.Code)
  834. }
  835. allowOrigin := r.Header().Get("Access-Control-Allow-Origin")
  836. allowHeaders := r.Header().Get("Access-Control-Allow-Headers")
  837. allowMethods := r.Header().Get("Access-Control-Allow-Methods")
  838. if allowOrigin != "*" {
  839. t.Errorf("Expected header Access-Control-Allow-Origin to be \"*\", %s found.", allowOrigin)
  840. }
  841. if allowHeaders != "Origin, X-Requested-With, Content-Type, Accept" {
  842. t.Errorf("Expected header Access-Control-Allow-Headers to be \"Origin, X-Requested-With, Content-Type, Accept\", %s found.", allowHeaders)
  843. }
  844. if allowMethods != "GET, POST, DELETE, PUT, OPTIONS" {
  845. t.Errorf("Expected hearder Access-Control-Allow-Methods to be \"GET, POST, DELETE, PUT, OPTIONS\", %s found.", allowMethods)
  846. }
  847. }
  848. func TestDeleteImages(t *testing.T) {
  849. runtime := mkRuntime(t)
  850. defer nuke(runtime)
  851. srv := &Server{runtime: runtime}
  852. initialImages, err := srv.Images(false, "")
  853. if err != nil {
  854. t.Fatal(err)
  855. }
  856. if err := srv.runtime.repositories.Set("test", "test", unitTestImageName, true); err != nil {
  857. t.Fatal(err)
  858. }
  859. images, err := srv.Images(false, "")
  860. if err != nil {
  861. t.Fatal(err)
  862. }
  863. if len(images) != len(initialImages)+1 {
  864. t.Errorf("Expected %d images, %d found", len(initialImages)+1, len(images))
  865. }
  866. req, err := http.NewRequest("DELETE", "/images/"+unitTestImageID, nil)
  867. if err != nil {
  868. t.Fatal(err)
  869. }
  870. r := httptest.NewRecorder()
  871. if err := deleteImages(srv, APIVERSION, r, req, map[string]string{"name": unitTestImageID}); err == nil {
  872. t.Fatalf("Expected conflict error, got none")
  873. }
  874. req2, err := http.NewRequest("DELETE", "/images/test:test", nil)
  875. if err != nil {
  876. t.Fatal(err)
  877. }
  878. r2 := httptest.NewRecorder()
  879. if err := deleteImages(srv, APIVERSION, r2, req2, map[string]string{"name": "test:test"}); err != nil {
  880. t.Fatal(err)
  881. }
  882. if r2.Code != http.StatusOK {
  883. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  884. }
  885. var outs []APIRmi
  886. if err := json.Unmarshal(r2.Body.Bytes(), &outs); err != nil {
  887. t.Fatal(err)
  888. }
  889. if len(outs) != 1 {
  890. t.Fatalf("Expected %d event (untagged), got %d", 1, len(outs))
  891. }
  892. images, err = srv.Images(false, "")
  893. if err != nil {
  894. t.Fatal(err)
  895. }
  896. if len(images) != len(initialImages) {
  897. t.Errorf("Expected %d image, %d found", len(initialImages), len(images))
  898. }
  899. /* if c := runtime.Get(container.Id); c != nil {
  900. t.Fatalf("The container as not been deleted")
  901. }
  902. if _, err := os.Stat(path.Join(container.rwPath(), "test")); err == nil {
  903. t.Fatalf("The test file has not been deleted")
  904. } */
  905. }
  906. // Mocked types for tests
  907. type NopConn struct {
  908. io.ReadCloser
  909. io.Writer
  910. }
  911. func (c *NopConn) LocalAddr() net.Addr { return nil }
  912. func (c *NopConn) RemoteAddr() net.Addr { return nil }
  913. func (c *NopConn) SetDeadline(t time.Time) error { return nil }
  914. func (c *NopConn) SetReadDeadline(t time.Time) error { return nil }
  915. func (c *NopConn) SetWriteDeadline(t time.Time) error { return nil }
  916. type hijackTester struct {
  917. *httptest.ResponseRecorder
  918. in io.ReadCloser
  919. out io.Writer
  920. }
  921. func (t *hijackTester) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  922. bufrw := bufio.NewReadWriter(bufio.NewReader(t.in), bufio.NewWriter(t.out))
  923. conn := &NopConn{
  924. ReadCloser: t.in,
  925. Writer: t.out,
  926. }
  927. return conn, bufrw, nil
  928. }