api_test.go 32 KB

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