api_test.go 31 KB

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