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