api_test.go 32 KB

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