api_test.go 32 KB

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