api_test.go 32 KB

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