api_test.go 27 KB

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