api_test.go 29 KB

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