api_test.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356
  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.Map()
  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", "fakeimage")
  86. srv.LogEvent("fakeaction2", "fakeid", "fakeimage")
  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 := 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. // Create a container and remove a file
  293. container, err := runtime.Create(
  294. &Config{
  295. Image: GetTestImage(runtime).ID,
  296. Cmd: []string{"touch", "/test"},
  297. },
  298. )
  299. if err != nil {
  300. t.Fatal(err)
  301. }
  302. defer runtime.Destroy(container)
  303. if err := container.Run(); err != nil {
  304. t.Fatal(err)
  305. }
  306. r := httptest.NewRecorder()
  307. if err = getContainersExport(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  308. t.Fatal(err)
  309. }
  310. if r.Code != http.StatusOK {
  311. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  312. }
  313. found := false
  314. for tarReader := tar.NewReader(r.Body); ; {
  315. h, err := tarReader.Next()
  316. if err != nil {
  317. if err == io.EOF {
  318. break
  319. }
  320. t.Fatal(err)
  321. }
  322. if h.Name == "./test" {
  323. found = true
  324. break
  325. }
  326. }
  327. if !found {
  328. t.Fatalf("The created test file has not been found in the exported image")
  329. }
  330. }
  331. func TestGetContainersChanges(t *testing.T) {
  332. runtime := mkRuntime(t)
  333. defer nuke(runtime)
  334. srv := &Server{runtime: runtime}
  335. // Create a container and remove a file
  336. container, err := runtime.Create(
  337. &Config{
  338. Image: GetTestImage(runtime).ID,
  339. Cmd: []string{"/bin/rm", "/etc/passwd"},
  340. },
  341. )
  342. if err != nil {
  343. t.Fatal(err)
  344. }
  345. defer runtime.Destroy(container)
  346. if err := container.Run(); err != nil {
  347. t.Fatal(err)
  348. }
  349. r := httptest.NewRecorder()
  350. if err := getContainersChanges(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  351. t.Fatal(err)
  352. }
  353. changes := []Change{}
  354. if err := json.Unmarshal(r.Body.Bytes(), &changes); err != nil {
  355. t.Fatal(err)
  356. }
  357. // Check the changelog
  358. success := false
  359. for _, elem := range changes {
  360. if elem.Path == "/etc/passwd" && elem.Kind == 2 {
  361. success = true
  362. }
  363. }
  364. if !success {
  365. t.Fatalf("/etc/passwd as been removed but is not present in the diff")
  366. }
  367. }
  368. func TestGetContainersTop(t *testing.T) {
  369. t.Skip("Fixme. Skipping test for now. Reported error when testing using dind: 'api_test.go:527: Expected 2 processes, found 0.'")
  370. runtime, err := newTestRuntime()
  371. if err != nil {
  372. t.Fatal(err)
  373. }
  374. defer nuke(runtime)
  375. srv := &Server{runtime: runtime}
  376. container, err := runtime.Create(
  377. &Config{
  378. Image: GetTestImage(runtime).ID,
  379. Cmd: []string{"/bin/sh", "-c", "cat"},
  380. OpenStdin: true,
  381. },
  382. )
  383. if err != nil {
  384. t.Fatal(err)
  385. }
  386. defer runtime.Destroy(container)
  387. defer func() {
  388. // Make sure the process dies before destroying runtime
  389. container.stdin.Close()
  390. container.WaitTimeout(2 * time.Second)
  391. }()
  392. hostConfig := &HostConfig{}
  393. if err := container.Start(hostConfig); err != nil {
  394. t.Fatal(err)
  395. }
  396. setTimeout(t, "Waiting for the container to be started timed out", 10*time.Second, func() {
  397. for {
  398. if container.State.Running {
  399. break
  400. }
  401. time.Sleep(10 * time.Millisecond)
  402. }
  403. })
  404. if !container.State.Running {
  405. t.Fatalf("Container should be running")
  406. }
  407. // Make sure sh spawn up cat
  408. setTimeout(t, "read/write assertion timed out", 2*time.Second, func() {
  409. in, _ := container.StdinPipe()
  410. out, _ := container.StdoutPipe()
  411. if err := assertPipe("hello\n", "hello", out, in, 15); err != nil {
  412. t.Fatal(err)
  413. }
  414. })
  415. r := httptest.NewRecorder()
  416. req, err := http.NewRequest("GET", "/"+container.ID+"/top?ps_args=u", bytes.NewReader([]byte{}))
  417. if err != nil {
  418. t.Fatal(err)
  419. }
  420. if err := getContainersTop(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  421. t.Fatal(err)
  422. }
  423. procs := APITop{}
  424. if err := json.Unmarshal(r.Body.Bytes(), &procs); err != nil {
  425. t.Fatal(err)
  426. }
  427. if len(procs.Titles) != 11 {
  428. t.Fatalf("Expected 11 titles, found %d.", len(procs.Titles))
  429. }
  430. if procs.Titles[0] != "USER" || procs.Titles[10] != "COMMAND" {
  431. t.Fatalf("Expected Titles[0] to be USER and Titles[10] to be COMMAND, found %s and %s.", procs.Titles[0], procs.Titles[10])
  432. }
  433. if len(procs.Processes) != 2 {
  434. t.Fatalf("Expected 2 processes, found %d.", len(procs.Processes))
  435. }
  436. if procs.Processes[0][10] != "/bin/sh" && procs.Processes[0][10] != "cat" {
  437. t.Fatalf("Expected `cat` or `/bin/sh`, found %s.", procs.Processes[0][10])
  438. }
  439. if procs.Processes[1][10] != "/bin/sh" && procs.Processes[1][10] != "cat" {
  440. t.Fatalf("Expected `cat` or `/bin/sh`, found %s.", procs.Processes[1][10])
  441. }
  442. }
  443. func TestGetContainersByName(t *testing.T) {
  444. runtime := mkRuntime(t)
  445. defer nuke(runtime)
  446. srv := &Server{runtime: runtime}
  447. // Create a container and remove a file
  448. container, err := runtime.Create(
  449. &Config{
  450. Image: GetTestImage(runtime).ID,
  451. Cmd: []string{"echo", "test"},
  452. },
  453. )
  454. if err != nil {
  455. t.Fatal(err)
  456. }
  457. defer runtime.Destroy(container)
  458. r := httptest.NewRecorder()
  459. if err := getContainersByName(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  460. t.Fatal(err)
  461. }
  462. outContainer := &Container{}
  463. if err := json.Unmarshal(r.Body.Bytes(), outContainer); err != nil {
  464. t.Fatal(err)
  465. }
  466. if outContainer.ID != container.ID {
  467. t.Fatalf("Wrong containers retrieved. Expected %s, received %s", container.ID, outContainer.ID)
  468. }
  469. }
  470. func TestPostCommit(t *testing.T) {
  471. runtime := mkRuntime(t)
  472. defer nuke(runtime)
  473. srv := &Server{runtime: runtime}
  474. // Create a container and remove a file
  475. container, err := runtime.Create(
  476. &Config{
  477. Image: GetTestImage(runtime).ID,
  478. Cmd: []string{"touch", "/test"},
  479. },
  480. )
  481. if err != nil {
  482. t.Fatal(err)
  483. }
  484. defer runtime.Destroy(container)
  485. if err := container.Run(); err != nil {
  486. t.Fatal(err)
  487. }
  488. req, err := http.NewRequest("POST", "/commit?repo=testrepo&testtag=tag&container="+container.ID, bytes.NewReader([]byte{}))
  489. if err != nil {
  490. t.Fatal(err)
  491. }
  492. r := httptest.NewRecorder()
  493. if err := postCommit(srv, APIVERSION, r, req, nil); err != nil {
  494. t.Fatal(err)
  495. }
  496. if r.Code != http.StatusCreated {
  497. t.Fatalf("%d Created expected, received %d\n", http.StatusCreated, r.Code)
  498. }
  499. apiID := &APIID{}
  500. if err := json.Unmarshal(r.Body.Bytes(), apiID); err != nil {
  501. t.Fatal(err)
  502. }
  503. if _, err := runtime.graph.Get(apiID.ID); err != nil {
  504. t.Fatalf("The image has not been commited")
  505. }
  506. }
  507. func TestPostContainersCreate(t *testing.T) {
  508. runtime := mkRuntime(t)
  509. defer nuke(runtime)
  510. srv := &Server{runtime: runtime}
  511. configJSON, err := json.Marshal(&Config{
  512. Image: GetTestImage(runtime).ID,
  513. Memory: 33554432,
  514. Cmd: []string{"touch", "/test"},
  515. })
  516. if err != nil {
  517. t.Fatal(err)
  518. }
  519. req, err := http.NewRequest("POST", "/containers/create", bytes.NewReader(configJSON))
  520. if err != nil {
  521. t.Fatal(err)
  522. }
  523. r := httptest.NewRecorder()
  524. if err := postContainersCreate(srv, APIVERSION, r, req, nil); err != nil {
  525. t.Fatal(err)
  526. }
  527. if r.Code != http.StatusCreated {
  528. t.Fatalf("%d Created expected, received %d\n", http.StatusCreated, r.Code)
  529. }
  530. apiRun := &APIRun{}
  531. if err := json.Unmarshal(r.Body.Bytes(), apiRun); err != nil {
  532. t.Fatal(err)
  533. }
  534. container := srv.runtime.Get(apiRun.ID)
  535. if container == nil {
  536. t.Fatalf("Container not created")
  537. }
  538. if err := container.Run(); err != nil {
  539. t.Fatal(err)
  540. }
  541. if err := container.EnsureMounted(); err != nil {
  542. t.Fatalf("Unable to mount container: %s", err)
  543. }
  544. if _, err := os.Stat(path.Join(container.RootfsPath(), "test")); err != nil {
  545. if os.IsNotExist(err) {
  546. utils.Debugf("Err: %s", err)
  547. t.Fatalf("The test file has not been created")
  548. }
  549. t.Fatal(err)
  550. }
  551. if err := container.Unmount(); err != nil {
  552. t.Fatalf("Unable to unmount container: %s", err)
  553. }
  554. }
  555. func TestPostContainersKill(t *testing.T) {
  556. runtime := mkRuntime(t)
  557. defer nuke(runtime)
  558. srv := &Server{runtime: runtime}
  559. container, err := runtime.Create(
  560. &Config{
  561. Image: GetTestImage(runtime).ID,
  562. Cmd: []string{"/bin/cat"},
  563. OpenStdin: true,
  564. },
  565. )
  566. if err != nil {
  567. t.Fatal(err)
  568. }
  569. defer runtime.Destroy(container)
  570. hostConfig := &HostConfig{}
  571. if err := container.Start(hostConfig); err != nil {
  572. t.Fatal(err)
  573. }
  574. // Give some time to the process to start
  575. container.WaitTimeout(500 * time.Millisecond)
  576. if !container.State.Running {
  577. t.Errorf("Container should be running")
  578. }
  579. r := httptest.NewRecorder()
  580. if err := postContainersKill(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  581. t.Fatal(err)
  582. }
  583. if r.Code != http.StatusNoContent {
  584. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  585. }
  586. if container.State.Running {
  587. t.Fatalf("The container hasn't been killed")
  588. }
  589. }
  590. func TestPostContainersRestart(t *testing.T) {
  591. runtime := mkRuntime(t)
  592. defer nuke(runtime)
  593. srv := &Server{runtime: runtime}
  594. container, err := runtime.Create(
  595. &Config{
  596. Image: GetTestImage(runtime).ID,
  597. Cmd: []string{"/bin/cat"},
  598. OpenStdin: true,
  599. },
  600. )
  601. if err != nil {
  602. t.Fatal(err)
  603. }
  604. defer runtime.Destroy(container)
  605. hostConfig := &HostConfig{}
  606. if err := container.Start(hostConfig); err != nil {
  607. t.Fatal(err)
  608. }
  609. // Give some time to the process to start
  610. container.WaitTimeout(500 * time.Millisecond)
  611. if !container.State.Running {
  612. t.Errorf("Container should be running")
  613. }
  614. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/restart?t=1", bytes.NewReader([]byte{}))
  615. if err != nil {
  616. t.Fatal(err)
  617. }
  618. r := httptest.NewRecorder()
  619. if err := postContainersRestart(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  620. t.Fatal(err)
  621. }
  622. if r.Code != http.StatusNoContent {
  623. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  624. }
  625. // Give some time to the process to restart
  626. container.WaitTimeout(500 * time.Millisecond)
  627. if !container.State.Running {
  628. t.Fatalf("Container should be running")
  629. }
  630. if err := container.Kill(); err != nil {
  631. t.Fatal(err)
  632. }
  633. }
  634. func TestPostContainersStart(t *testing.T) {
  635. runtime := mkRuntime(t)
  636. defer nuke(runtime)
  637. srv := &Server{runtime: runtime}
  638. container, err := runtime.Create(
  639. &Config{
  640. Image: GetTestImage(runtime).ID,
  641. Cmd: []string{"/bin/cat"},
  642. OpenStdin: true,
  643. },
  644. )
  645. if err != nil {
  646. t.Fatal(err)
  647. }
  648. defer runtime.Destroy(container)
  649. hostConfigJSON, err := json.Marshal(&HostConfig{})
  650. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/start", bytes.NewReader(hostConfigJSON))
  651. if err != nil {
  652. t.Fatal(err)
  653. }
  654. r := httptest.NewRecorder()
  655. if err := postContainersStart(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  656. t.Fatal(err)
  657. }
  658. if r.Code != http.StatusNoContent {
  659. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  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. r = httptest.NewRecorder()
  667. if err = postContainersStart(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err == nil {
  668. t.Fatalf("A running container should be able to be started")
  669. }
  670. if err := container.Kill(); err != nil {
  671. t.Fatal(err)
  672. }
  673. }
  674. func TestPostContainersStop(t *testing.T) {
  675. runtime := mkRuntime(t)
  676. defer nuke(runtime)
  677. srv := &Server{runtime: runtime}
  678. container, err := runtime.Create(
  679. &Config{
  680. Image: GetTestImage(runtime).ID,
  681. Cmd: []string{"/bin/cat"},
  682. OpenStdin: true,
  683. },
  684. )
  685. if err != nil {
  686. t.Fatal(err)
  687. }
  688. defer runtime.Destroy(container)
  689. hostConfig := &HostConfig{}
  690. if err := container.Start(hostConfig); err != nil {
  691. t.Fatal(err)
  692. }
  693. // Give some time to the process to start
  694. container.WaitTimeout(500 * time.Millisecond)
  695. if !container.State.Running {
  696. t.Errorf("Container should be running")
  697. }
  698. // Note: as it is a POST request, it requires a body.
  699. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/stop?t=1", bytes.NewReader([]byte{}))
  700. if err != nil {
  701. t.Fatal(err)
  702. }
  703. r := httptest.NewRecorder()
  704. if err := postContainersStop(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  705. t.Fatal(err)
  706. }
  707. if r.Code != http.StatusNoContent {
  708. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  709. }
  710. if container.State.Running {
  711. t.Fatalf("The container hasn't been stopped")
  712. }
  713. }
  714. func TestPostContainersWait(t *testing.T) {
  715. runtime := mkRuntime(t)
  716. defer nuke(runtime)
  717. srv := &Server{runtime: runtime}
  718. container, err := runtime.Create(
  719. &Config{
  720. Image: GetTestImage(runtime).ID,
  721. Cmd: []string{"/bin/sleep", "1"},
  722. OpenStdin: true,
  723. },
  724. )
  725. if err != nil {
  726. t.Fatal(err)
  727. }
  728. defer runtime.Destroy(container)
  729. hostConfig := &HostConfig{}
  730. if err := container.Start(hostConfig); err != nil {
  731. t.Fatal(err)
  732. }
  733. setTimeout(t, "Wait timed out", 3*time.Second, func() {
  734. r := httptest.NewRecorder()
  735. if err := postContainersWait(srv, APIVERSION, r, nil, map[string]string{"name": container.ID}); err != nil {
  736. t.Fatal(err)
  737. }
  738. apiWait := &APIWait{}
  739. if err := json.Unmarshal(r.Body.Bytes(), apiWait); err != nil {
  740. t.Fatal(err)
  741. }
  742. if apiWait.StatusCode != 0 {
  743. t.Fatalf("Non zero exit code for sleep: %d\n", apiWait.StatusCode)
  744. }
  745. })
  746. if container.State.Running {
  747. t.Fatalf("The container should be stopped after wait")
  748. }
  749. }
  750. func TestPostContainersAttach(t *testing.T) {
  751. runtime := mkRuntime(t)
  752. defer nuke(runtime)
  753. srv := &Server{runtime: runtime}
  754. container, err := runtime.Create(
  755. &Config{
  756. Image: GetTestImage(runtime).ID,
  757. Cmd: []string{"/bin/cat"},
  758. OpenStdin: true,
  759. },
  760. )
  761. if err != nil {
  762. t.Fatal(err)
  763. }
  764. defer runtime.Destroy(container)
  765. // Start the process
  766. hostConfig := &HostConfig{}
  767. if err := container.Start(hostConfig); err != nil {
  768. t.Fatal(err)
  769. }
  770. stdin, stdinPipe := io.Pipe()
  771. stdout, stdoutPipe := io.Pipe()
  772. // Try to avoid the timeout in destroy. Best effort, don't check error
  773. defer func() {
  774. closeWrap(stdin, stdinPipe, stdout, stdoutPipe)
  775. container.Kill()
  776. }()
  777. // Attach to it
  778. c1 := make(chan struct{})
  779. go func() {
  780. defer close(c1)
  781. r := &hijackTester{
  782. ResponseRecorder: httptest.NewRecorder(),
  783. in: stdin,
  784. out: stdoutPipe,
  785. }
  786. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/attach?stream=1&stdin=1&stdout=1&stderr=1", bytes.NewReader([]byte{}))
  787. if err != nil {
  788. t.Fatal(err)
  789. }
  790. if err := postContainersAttach(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  791. t.Fatal(err)
  792. }
  793. }()
  794. // Acknowledge hijack
  795. setTimeout(t, "hijack acknowledge timed out", 2*time.Second, func() {
  796. stdout.Read([]byte{})
  797. stdout.Read(make([]byte, 4096))
  798. })
  799. setTimeout(t, "read/write assertion timed out", 2*time.Second, func() {
  800. if err := assertPipe("hello\n", string([]byte{1, 0, 0, 0, 0, 0, 0, 6})+"hello", stdout, stdinPipe, 15); err != nil {
  801. t.Fatal(err)
  802. }
  803. })
  804. // Close pipes (client disconnects)
  805. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  806. t.Fatal(err)
  807. }
  808. // Wait for attach to finish, the client disconnected, therefore, Attach finished his job
  809. setTimeout(t, "Waiting for CmdAttach timed out", 10*time.Second, func() {
  810. <-c1
  811. })
  812. // We closed stdin, expect /bin/cat to still be running
  813. // Wait a little bit to make sure container.monitor() did his thing
  814. err = container.WaitTimeout(500 * time.Millisecond)
  815. if err == nil || !container.State.Running {
  816. t.Fatalf("/bin/cat is not running after closing stdin")
  817. }
  818. // Try to avoid the timeout in destroy. Best effort, don't check error
  819. cStdin, _ := container.StdinPipe()
  820. cStdin.Close()
  821. container.Wait()
  822. }
  823. func TestPostContainersAttachStderr(t *testing.T) {
  824. runtime := mkRuntime(t)
  825. defer nuke(runtime)
  826. srv := &Server{runtime: runtime}
  827. container, err := runtime.Create(
  828. &Config{
  829. Image: GetTestImage(runtime).ID,
  830. Cmd: []string{"/bin/sh", "-c", "/bin/cat >&2"},
  831. OpenStdin: true,
  832. },
  833. )
  834. if err != nil {
  835. t.Fatal(err)
  836. }
  837. defer runtime.Destroy(container)
  838. // Start the process
  839. hostConfig := &HostConfig{}
  840. if err := container.Start(hostConfig); err != nil {
  841. t.Fatal(err)
  842. }
  843. stdin, stdinPipe := io.Pipe()
  844. stdout, stdoutPipe := io.Pipe()
  845. // Try to avoid the timeout in destroy. Best effort, don't check error
  846. defer func() {
  847. closeWrap(stdin, stdinPipe, stdout, stdoutPipe)
  848. container.Kill()
  849. }()
  850. // Attach to it
  851. c1 := make(chan struct{})
  852. go func() {
  853. defer close(c1)
  854. r := &hijackTester{
  855. ResponseRecorder: httptest.NewRecorder(),
  856. in: stdin,
  857. out: stdoutPipe,
  858. }
  859. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/attach?stream=1&stdin=1&stdout=1&stderr=1", bytes.NewReader([]byte{}))
  860. if err != nil {
  861. t.Fatal(err)
  862. }
  863. if err := postContainersAttach(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  864. t.Fatal(err)
  865. }
  866. }()
  867. // Acknowledge hijack
  868. setTimeout(t, "hijack acknowledge timed out", 2*time.Second, func() {
  869. stdout.Read([]byte{})
  870. stdout.Read(make([]byte, 4096))
  871. })
  872. setTimeout(t, "read/write assertion timed out", 2*time.Second, func() {
  873. if err := assertPipe("hello\n", string([]byte{2, 0, 0, 0, 0, 0, 0, 6})+"hello", stdout, stdinPipe, 15); err != nil {
  874. t.Fatal(err)
  875. }
  876. })
  877. // Close pipes (client disconnects)
  878. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  879. t.Fatal(err)
  880. }
  881. // Wait for attach to finish, the client disconnected, therefore, Attach finished his job
  882. setTimeout(t, "Waiting for CmdAttach timed out", 10*time.Second, func() {
  883. <-c1
  884. })
  885. // We closed stdin, expect /bin/cat to still be running
  886. // Wait a little bit to make sure container.monitor() did his thing
  887. err = container.WaitTimeout(500 * time.Millisecond)
  888. if err == nil || !container.State.Running {
  889. t.Fatalf("/bin/cat is not running after closing stdin")
  890. }
  891. // Try to avoid the timeout in destroy. Best effort, don't check error
  892. cStdin, _ := container.StdinPipe()
  893. cStdin.Close()
  894. container.Wait()
  895. }
  896. // FIXME: Test deleting running container
  897. // FIXME: Test deleting container with volume
  898. // FIXME: Test deleting volume in use by other container
  899. func TestDeleteContainers(t *testing.T) {
  900. runtime := mkRuntime(t)
  901. defer nuke(runtime)
  902. srv := &Server{runtime: runtime}
  903. container, err := runtime.Create(&Config{
  904. Image: GetTestImage(runtime).ID,
  905. Cmd: []string{"touch", "/test"},
  906. })
  907. if err != nil {
  908. t.Fatal(err)
  909. }
  910. defer runtime.Destroy(container)
  911. if err := container.Run(); err != nil {
  912. t.Fatal(err)
  913. }
  914. req, err := http.NewRequest("DELETE", "/containers/"+container.ID, nil)
  915. if err != nil {
  916. t.Fatal(err)
  917. }
  918. r := httptest.NewRecorder()
  919. if err := deleteContainers(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  920. t.Fatal(err)
  921. }
  922. if r.Code != http.StatusNoContent {
  923. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  924. }
  925. if c := runtime.Get(container.ID); c != nil {
  926. t.Fatalf("The container as not been deleted")
  927. }
  928. if _, err := os.Stat(path.Join(container.rwPath(), "test")); err == nil {
  929. t.Fatalf("The test file has not been deleted")
  930. }
  931. }
  932. func TestOptionsRoute(t *testing.T) {
  933. runtime := mkRuntime(t)
  934. defer nuke(runtime)
  935. srv := &Server{runtime: runtime, enableCors: true}
  936. r := httptest.NewRecorder()
  937. router, err := createRouter(srv, false)
  938. if err != nil {
  939. t.Fatal(err)
  940. }
  941. req, err := http.NewRequest("OPTIONS", "/", nil)
  942. if err != nil {
  943. t.Fatal(err)
  944. }
  945. router.ServeHTTP(r, req)
  946. if r.Code != http.StatusOK {
  947. t.Errorf("Expected response for OPTIONS request to be \"200\", %v found.", r.Code)
  948. }
  949. }
  950. func TestGetEnabledCors(t *testing.T) {
  951. runtime := mkRuntime(t)
  952. defer nuke(runtime)
  953. srv := &Server{runtime: runtime, enableCors: true}
  954. r := httptest.NewRecorder()
  955. router, err := createRouter(srv, false)
  956. if err != nil {
  957. t.Fatal(err)
  958. }
  959. req, err := http.NewRequest("GET", "/version", nil)
  960. if err != nil {
  961. t.Fatal(err)
  962. }
  963. router.ServeHTTP(r, req)
  964. if r.Code != http.StatusOK {
  965. t.Errorf("Expected response for OPTIONS request to be \"200\", %v found.", r.Code)
  966. }
  967. allowOrigin := r.Header().Get("Access-Control-Allow-Origin")
  968. allowHeaders := r.Header().Get("Access-Control-Allow-Headers")
  969. allowMethods := r.Header().Get("Access-Control-Allow-Methods")
  970. if allowOrigin != "*" {
  971. t.Errorf("Expected header Access-Control-Allow-Origin to be \"*\", %s found.", allowOrigin)
  972. }
  973. if allowHeaders != "Origin, X-Requested-With, Content-Type, Accept" {
  974. t.Errorf("Expected header Access-Control-Allow-Headers to be \"Origin, X-Requested-With, Content-Type, Accept\", %s found.", allowHeaders)
  975. }
  976. if allowMethods != "GET, POST, DELETE, PUT, OPTIONS" {
  977. t.Errorf("Expected hearder Access-Control-Allow-Methods to be \"GET, POST, DELETE, PUT, OPTIONS\", %s found.", allowMethods)
  978. }
  979. }
  980. func TestDeleteImages(t *testing.T) {
  981. runtime := mkRuntime(t)
  982. defer nuke(runtime)
  983. srv := &Server{runtime: runtime}
  984. initialImages, err := srv.Images(false, "")
  985. if err != nil {
  986. t.Fatal(err)
  987. }
  988. if err := srv.runtime.repositories.Set("test", "test", unitTestImageName, true); err != nil {
  989. t.Fatal(err)
  990. }
  991. images, err := srv.Images(false, "")
  992. if err != nil {
  993. t.Fatal(err)
  994. }
  995. if len(images) != len(initialImages)+1 {
  996. t.Errorf("Expected %d images, %d found", len(initialImages)+1, len(images))
  997. }
  998. req, err := http.NewRequest("DELETE", "/images/"+unitTestImageID, nil)
  999. if err != nil {
  1000. t.Fatal(err)
  1001. }
  1002. r := httptest.NewRecorder()
  1003. if err := deleteImages(srv, APIVERSION, r, req, map[string]string{"name": unitTestImageID}); err == nil {
  1004. t.Fatalf("Expected conflict error, got none")
  1005. }
  1006. req2, err := http.NewRequest("DELETE", "/images/test:test", nil)
  1007. if err != nil {
  1008. t.Fatal(err)
  1009. }
  1010. r2 := httptest.NewRecorder()
  1011. if err := deleteImages(srv, APIVERSION, r2, req2, map[string]string{"name": "test:test"}); err != nil {
  1012. t.Fatal(err)
  1013. }
  1014. if r2.Code != http.StatusOK {
  1015. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  1016. }
  1017. var outs []APIRmi
  1018. if err := json.Unmarshal(r2.Body.Bytes(), &outs); err != nil {
  1019. t.Fatal(err)
  1020. }
  1021. if len(outs) != 1 {
  1022. t.Fatalf("Expected %d event (untagged), got %d", 1, len(outs))
  1023. }
  1024. images, err = srv.Images(false, "")
  1025. if err != nil {
  1026. t.Fatal(err)
  1027. }
  1028. if len(images) != len(initialImages) {
  1029. t.Errorf("Expected %d image, %d found", len(initialImages), len(images))
  1030. }
  1031. /* if c := runtime.Get(container.Id); c != nil {
  1032. t.Fatalf("The container as not been deleted")
  1033. }
  1034. if _, err := os.Stat(path.Join(container.rwPath(), "test")); err == nil {
  1035. t.Fatalf("The test file has not been deleted")
  1036. } */
  1037. }
  1038. func TestJsonContentType(t *testing.T) {
  1039. if !matchesContentType("application/json", "application/json") {
  1040. t.Fail()
  1041. }
  1042. if !matchesContentType("application/json; charset=utf-8", "application/json") {
  1043. t.Fail()
  1044. }
  1045. if matchesContentType("dockerapplication/json", "application/json") {
  1046. t.Fail()
  1047. }
  1048. }
  1049. func TestPostContainersCopy(t *testing.T) {
  1050. runtime := mkRuntime(t)
  1051. defer nuke(runtime)
  1052. srv := &Server{runtime: runtime}
  1053. // Create a container and remove a file
  1054. container, err := runtime.Create(
  1055. &Config{
  1056. Image: GetTestImage(runtime).ID,
  1057. Cmd: []string{"touch", "/test.txt"},
  1058. },
  1059. )
  1060. if err != nil {
  1061. t.Fatal(err)
  1062. }
  1063. defer runtime.Destroy(container)
  1064. if err := container.Run(); err != nil {
  1065. t.Fatal(err)
  1066. }
  1067. r := httptest.NewRecorder()
  1068. copyData := APICopy{HostPath: ".", Resource: "/test.txt"}
  1069. jsonData, err := json.Marshal(copyData)
  1070. if err != nil {
  1071. t.Fatal(err)
  1072. }
  1073. req, err := http.NewRequest("POST", "/containers/"+container.ID+"/copy", bytes.NewReader(jsonData))
  1074. if err != nil {
  1075. t.Fatal(err)
  1076. }
  1077. req.Header.Add("Content-Type", "application/json")
  1078. if err = postContainersCopy(srv, APIVERSION, r, req, map[string]string{"name": container.ID}); err != nil {
  1079. t.Fatal(err)
  1080. }
  1081. if r.Code != http.StatusOK {
  1082. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  1083. }
  1084. found := false
  1085. for tarReader := tar.NewReader(r.Body); ; {
  1086. h, err := tarReader.Next()
  1087. if err != nil {
  1088. if err == io.EOF {
  1089. break
  1090. }
  1091. t.Fatal(err)
  1092. }
  1093. if h.Name == "test.txt" {
  1094. found = true
  1095. break
  1096. }
  1097. }
  1098. if !found {
  1099. t.Fatalf("The created test file has not been found in the copied output")
  1100. }
  1101. }
  1102. // Mocked types for tests
  1103. type NopConn struct {
  1104. io.ReadCloser
  1105. io.Writer
  1106. }
  1107. func (c *NopConn) LocalAddr() net.Addr { return nil }
  1108. func (c *NopConn) RemoteAddr() net.Addr { return nil }
  1109. func (c *NopConn) SetDeadline(t time.Time) error { return nil }
  1110. func (c *NopConn) SetReadDeadline(t time.Time) error { return nil }
  1111. func (c *NopConn) SetWriteDeadline(t time.Time) error { return nil }
  1112. type hijackTester struct {
  1113. *httptest.ResponseRecorder
  1114. in io.ReadCloser
  1115. out io.Writer
  1116. }
  1117. func (t *hijackTester) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  1118. bufrw := bufio.NewReadWriter(bufio.NewReader(t.in), bufio.NewWriter(t.out))
  1119. conn := &NopConn{
  1120. ReadCloser: t.in,
  1121. Writer: t.out,
  1122. }
  1123. return conn, bufrw, nil
  1124. }