api_test.go 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  1. package docker
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net"
  10. "net/http"
  11. "net/http/httptest"
  12. "strings"
  13. "testing"
  14. "time"
  15. "github.com/docker/docker/api"
  16. "github.com/docker/docker/api/server"
  17. "github.com/docker/docker/engine"
  18. "github.com/docker/docker/runconfig"
  19. "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
  20. )
  21. func TestSaveImageAndThenLoad(t *testing.T) {
  22. eng := NewTestEngine(t)
  23. defer mkDaemonFromEngine(eng, t).Nuke()
  24. // save image
  25. r := httptest.NewRecorder()
  26. req, err := http.NewRequest("GET", "/images/"+unitTestImageID+"/get", nil)
  27. if err != nil {
  28. t.Fatal(err)
  29. }
  30. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  31. t.Fatal(err)
  32. }
  33. if r.Code != http.StatusOK {
  34. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  35. }
  36. tarball := r.Body
  37. // delete the image
  38. r = httptest.NewRecorder()
  39. req, err = http.NewRequest("DELETE", "/images/"+unitTestImageID, nil)
  40. if err != nil {
  41. t.Fatal(err)
  42. }
  43. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  44. t.Fatal(err)
  45. }
  46. if r.Code != http.StatusOK {
  47. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  48. }
  49. // make sure there is no image
  50. r = httptest.NewRecorder()
  51. req, err = http.NewRequest("GET", "/images/"+unitTestImageID+"/get", nil)
  52. if err != nil {
  53. t.Fatal(err)
  54. }
  55. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  56. t.Fatal(err)
  57. }
  58. if r.Code != http.StatusNotFound {
  59. t.Fatalf("%d NotFound expected, received %d\n", http.StatusNotFound, r.Code)
  60. }
  61. // load the image
  62. r = httptest.NewRecorder()
  63. req, err = http.NewRequest("POST", "/images/load", tarball)
  64. if err != nil {
  65. t.Fatal(err)
  66. }
  67. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  68. t.Fatal(err)
  69. }
  70. if r.Code != http.StatusOK {
  71. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  72. }
  73. // finally make sure the image is there
  74. r = httptest.NewRecorder()
  75. req, err = http.NewRequest("GET", "/images/"+unitTestImageID+"/get", nil)
  76. if err != nil {
  77. t.Fatal(err)
  78. }
  79. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  80. t.Fatal(err)
  81. }
  82. if r.Code != http.StatusOK {
  83. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  84. }
  85. }
  86. func TestGetContainersTop(t *testing.T) {
  87. eng := NewTestEngine(t)
  88. defer mkDaemonFromEngine(eng, t).Nuke()
  89. containerID := createTestContainer(eng,
  90. &runconfig.Config{
  91. Image: unitTestImageID,
  92. Cmd: []string{"/bin/sh", "-c", "cat"},
  93. OpenStdin: true,
  94. },
  95. t,
  96. )
  97. defer func() {
  98. // Make sure the process dies before destroying daemon
  99. containerKill(eng, containerID, t)
  100. containerWait(eng, containerID, t)
  101. }()
  102. startContainer(eng, containerID, t)
  103. setTimeout(t, "Waiting for the container to be started timed out", 10*time.Second, func() {
  104. for {
  105. if containerRunning(eng, containerID, t) {
  106. break
  107. }
  108. time.Sleep(10 * time.Millisecond)
  109. }
  110. })
  111. if !containerRunning(eng, containerID, t) {
  112. t.Fatalf("Container should be running")
  113. }
  114. // Make sure sh spawn up cat
  115. setTimeout(t, "read/write assertion timed out", 2*time.Second, func() {
  116. in, out := containerAttach(eng, containerID, t)
  117. if err := assertPipe("hello\n", "hello", out, in, 150); err != nil {
  118. t.Fatal(err)
  119. }
  120. })
  121. r := httptest.NewRecorder()
  122. req, err := http.NewRequest("GET", "/containers/"+containerID+"/top?ps_args=aux", nil)
  123. if err != nil {
  124. t.Fatal(err)
  125. }
  126. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  127. t.Fatal(err)
  128. }
  129. assertHttpNotError(r, t)
  130. var procs engine.Env
  131. if err := procs.Decode(r.Body); err != nil {
  132. t.Fatal(err)
  133. }
  134. if len(procs.GetList("Titles")) != 11 {
  135. t.Fatalf("Expected 11 titles, found %d.", len(procs.GetList("Titles")))
  136. }
  137. if procs.GetList("Titles")[0] != "USER" || procs.GetList("Titles")[10] != "COMMAND" {
  138. t.Fatalf("Expected Titles[0] to be USER and Titles[10] to be COMMAND, found %s and %s.", procs.GetList("Titles")[0], procs.GetList("Titles")[10])
  139. }
  140. processes := [][]string{}
  141. if err := procs.GetJson("Processes", &processes); err != nil {
  142. t.Fatal(err)
  143. }
  144. if len(processes) != 2 {
  145. t.Fatalf("Expected 2 processes, found %d.", len(processes))
  146. }
  147. if processes[0][10] != "/bin/sh -c cat" {
  148. t.Fatalf("Expected `/bin/sh -c cat`, found %s.", processes[0][10])
  149. }
  150. if processes[1][10] != "/bin/sh -c cat" {
  151. t.Fatalf("Expected `/bin/sh -c cat`, found %s.", processes[1][10])
  152. }
  153. }
  154. func TestPostCommit(t *testing.T) {
  155. eng := NewTestEngine(t)
  156. defer mkDaemonFromEngine(eng, t).Nuke()
  157. // Create a container and remove a file
  158. containerID := createTestContainer(eng,
  159. &runconfig.Config{
  160. Image: unitTestImageID,
  161. Cmd: []string{"touch", "/test"},
  162. },
  163. t,
  164. )
  165. containerRun(eng, containerID, t)
  166. req, err := http.NewRequest("POST", "/commit?repo=testrepo&testtag=tag&container="+containerID, bytes.NewReader([]byte{}))
  167. if err != nil {
  168. t.Fatal(err)
  169. }
  170. r := httptest.NewRecorder()
  171. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  172. t.Fatal(err)
  173. }
  174. assertHttpNotError(r, t)
  175. if r.Code != http.StatusCreated {
  176. t.Fatalf("%d Created expected, received %d\n", http.StatusCreated, r.Code)
  177. }
  178. var env engine.Env
  179. if err := env.Decode(r.Body); err != nil {
  180. t.Fatal(err)
  181. }
  182. if err := eng.Job("image_inspect", env.Get("Id")).Run(); err != nil {
  183. t.Fatalf("The image has not been committed")
  184. }
  185. }
  186. func TestPostContainersCreate(t *testing.T) {
  187. eng := NewTestEngine(t)
  188. defer mkDaemonFromEngine(eng, t).Nuke()
  189. configJSON, err := json.Marshal(&runconfig.Config{
  190. Image: unitTestImageID,
  191. Memory: 33554432,
  192. Cmd: []string{"touch", "/test"},
  193. })
  194. if err != nil {
  195. t.Fatal(err)
  196. }
  197. req, err := http.NewRequest("POST", "/containers/create", bytes.NewReader(configJSON))
  198. if err != nil {
  199. t.Fatal(err)
  200. }
  201. req.Header.Set("Content-Type", "application/json")
  202. r := httptest.NewRecorder()
  203. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  204. t.Fatal(err)
  205. }
  206. assertHttpNotError(r, t)
  207. if r.Code != http.StatusCreated {
  208. t.Fatalf("%d Created expected, received %d\n", http.StatusCreated, r.Code)
  209. }
  210. var apiRun engine.Env
  211. if err := apiRun.Decode(r.Body); err != nil {
  212. t.Fatal(err)
  213. }
  214. containerID := apiRun.Get("Id")
  215. containerAssertExists(eng, containerID, t)
  216. containerRun(eng, containerID, t)
  217. if !containerFileExists(eng, containerID, "test", t) {
  218. t.Fatal("Test file was not created")
  219. }
  220. }
  221. func TestPostJsonVerify(t *testing.T) {
  222. eng := NewTestEngine(t)
  223. defer mkDaemonFromEngine(eng, t).Nuke()
  224. configJSON, err := json.Marshal(&runconfig.Config{
  225. Image: unitTestImageID,
  226. Memory: 33554432,
  227. Cmd: []string{"touch", "/test"},
  228. })
  229. if err != nil {
  230. t.Fatal(err)
  231. }
  232. req, err := http.NewRequest("POST", "/containers/create", bytes.NewReader(configJSON))
  233. if err != nil {
  234. t.Fatal(err)
  235. }
  236. r := httptest.NewRecorder()
  237. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  238. t.Fatal(err)
  239. }
  240. // Don't add Content-Type header
  241. // req.Header.Set("Content-Type", "application/json")
  242. err = server.ServeRequest(eng, api.APIVERSION, r, req)
  243. if r.Code != http.StatusInternalServerError || !strings.Contains(((*r.Body).String()), "application/json") {
  244. t.Fatal("Create should have failed due to no Content-Type header - got:", r)
  245. }
  246. // Now add header but with wrong type and retest
  247. req.Header.Set("Content-Type", "application/xml")
  248. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  249. t.Fatal(err)
  250. }
  251. if r.Code != http.StatusInternalServerError || !strings.Contains(((*r.Body).String()), "application/json") {
  252. t.Fatal("Create should have failed due to wrong Content-Type header - got:", r)
  253. }
  254. }
  255. // Issue 7941 - test to make sure a "null" in JSON is just ignored.
  256. // W/o this fix a null in JSON would be parsed into a string var as "null"
  257. func TestPostCreateNull(t *testing.T) {
  258. eng := NewTestEngine(t)
  259. daemon := mkDaemonFromEngine(eng, t)
  260. defer daemon.Nuke()
  261. configStr := fmt.Sprintf(`{
  262. "Hostname":"",
  263. "Domainname":"",
  264. "Memory":0,
  265. "MemorySwap":0,
  266. "CpuShares":0,
  267. "Cpuset":null,
  268. "AttachStdin":true,
  269. "AttachStdout":true,
  270. "AttachStderr":true,
  271. "PortSpecs":null,
  272. "ExposedPorts":{},
  273. "Tty":true,
  274. "OpenStdin":true,
  275. "StdinOnce":true,
  276. "Env":[],
  277. "Cmd":"ls",
  278. "Image":"%s",
  279. "Volumes":{},
  280. "WorkingDir":"",
  281. "Entrypoint":null,
  282. "NetworkDisabled":false,
  283. "OnBuild":null}`, unitTestImageID)
  284. req, err := http.NewRequest("POST", "/containers/create", strings.NewReader(configStr))
  285. if err != nil {
  286. t.Fatal(err)
  287. }
  288. req.Header.Set("Content-Type", "application/json")
  289. r := httptest.NewRecorder()
  290. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  291. t.Fatal(err)
  292. }
  293. assertHttpNotError(r, t)
  294. if r.Code != http.StatusCreated {
  295. t.Fatalf("%d Created expected, received %d\n", http.StatusCreated, r.Code)
  296. }
  297. var apiRun engine.Env
  298. if err := apiRun.Decode(r.Body); err != nil {
  299. t.Fatal(err)
  300. }
  301. containerID := apiRun.Get("Id")
  302. containerAssertExists(eng, containerID, t)
  303. c := daemon.Get(containerID)
  304. if c.Config.Cpuset != "" {
  305. t.Fatalf("Cpuset should have been empty - instead its:" + c.Config.Cpuset)
  306. }
  307. }
  308. func TestPostContainersKill(t *testing.T) {
  309. eng := NewTestEngine(t)
  310. defer mkDaemonFromEngine(eng, t).Nuke()
  311. containerID := createTestContainer(eng,
  312. &runconfig.Config{
  313. Image: unitTestImageID,
  314. Cmd: []string{"/bin/cat"},
  315. OpenStdin: true,
  316. },
  317. t,
  318. )
  319. startContainer(eng, containerID, t)
  320. // Give some time to the process to start
  321. containerWaitTimeout(eng, containerID, t)
  322. if !containerRunning(eng, containerID, t) {
  323. t.Errorf("Container should be running")
  324. }
  325. r := httptest.NewRecorder()
  326. req, err := http.NewRequest("POST", "/containers/"+containerID+"/kill", bytes.NewReader([]byte{}))
  327. if err != nil {
  328. t.Fatal(err)
  329. }
  330. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  331. t.Fatal(err)
  332. }
  333. assertHttpNotError(r, t)
  334. if r.Code != http.StatusNoContent {
  335. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  336. }
  337. if containerRunning(eng, containerID, t) {
  338. t.Fatalf("The container hasn't been killed")
  339. }
  340. }
  341. func TestPostContainersRestart(t *testing.T) {
  342. eng := NewTestEngine(t)
  343. defer mkDaemonFromEngine(eng, t).Nuke()
  344. containerID := createTestContainer(eng,
  345. &runconfig.Config{
  346. Image: unitTestImageID,
  347. Cmd: []string{"/bin/top"},
  348. OpenStdin: true,
  349. },
  350. t,
  351. )
  352. startContainer(eng, containerID, t)
  353. // Give some time to the process to start
  354. containerWaitTimeout(eng, containerID, t)
  355. if !containerRunning(eng, containerID, t) {
  356. t.Errorf("Container should be running")
  357. }
  358. req, err := http.NewRequest("POST", "/containers/"+containerID+"/restart?t=1", bytes.NewReader([]byte{}))
  359. if err != nil {
  360. t.Fatal(err)
  361. }
  362. r := httptest.NewRecorder()
  363. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  364. t.Fatal(err)
  365. }
  366. assertHttpNotError(r, t)
  367. if r.Code != http.StatusNoContent {
  368. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  369. }
  370. // Give some time to the process to restart
  371. containerWaitTimeout(eng, containerID, t)
  372. if !containerRunning(eng, containerID, t) {
  373. t.Fatalf("Container should be running")
  374. }
  375. containerKill(eng, containerID, t)
  376. }
  377. func TestPostContainersStart(t *testing.T) {
  378. eng := NewTestEngine(t)
  379. defer mkDaemonFromEngine(eng, t).Nuke()
  380. containerID := createTestContainer(
  381. eng,
  382. &runconfig.Config{
  383. Image: unitTestImageID,
  384. Cmd: []string{"/bin/cat"},
  385. OpenStdin: true,
  386. },
  387. t,
  388. )
  389. hostConfigJSON, err := json.Marshal(&runconfig.HostConfig{})
  390. req, err := http.NewRequest("POST", "/containers/"+containerID+"/start", bytes.NewReader(hostConfigJSON))
  391. if err != nil {
  392. t.Fatal(err)
  393. }
  394. req.Header.Set("Content-Type", "application/json")
  395. r := httptest.NewRecorder()
  396. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  397. t.Fatal(err)
  398. }
  399. assertHttpNotError(r, t)
  400. if r.Code != http.StatusNoContent {
  401. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  402. }
  403. containerAssertExists(eng, containerID, t)
  404. req, err = http.NewRequest("POST", "/containers/"+containerID+"/start", bytes.NewReader(hostConfigJSON))
  405. if err != nil {
  406. t.Fatal(err)
  407. }
  408. req.Header.Set("Content-Type", "application/json")
  409. r = httptest.NewRecorder()
  410. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  411. t.Fatal(err)
  412. }
  413. // Starting an already started container should return a 304
  414. assertHttpNotError(r, t)
  415. if r.Code != http.StatusNotModified {
  416. t.Fatalf("%d NOT MODIFIER expected, received %d\n", http.StatusNotModified, r.Code)
  417. }
  418. containerAssertExists(eng, containerID, t)
  419. containerKill(eng, containerID, t)
  420. }
  421. func TestPostContainersStop(t *testing.T) {
  422. eng := NewTestEngine(t)
  423. defer mkDaemonFromEngine(eng, t).Nuke()
  424. containerID := createTestContainer(eng,
  425. &runconfig.Config{
  426. Image: unitTestImageID,
  427. Cmd: []string{"/bin/top"},
  428. OpenStdin: true,
  429. },
  430. t,
  431. )
  432. startContainer(eng, containerID, t)
  433. // Give some time to the process to start
  434. containerWaitTimeout(eng, containerID, t)
  435. if !containerRunning(eng, containerID, t) {
  436. t.Errorf("Container should be running")
  437. }
  438. // Note: as it is a POST request, it requires a body.
  439. req, err := http.NewRequest("POST", "/containers/"+containerID+"/stop?t=1", bytes.NewReader([]byte{}))
  440. if err != nil {
  441. t.Fatal(err)
  442. }
  443. r := httptest.NewRecorder()
  444. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  445. t.Fatal(err)
  446. }
  447. assertHttpNotError(r, t)
  448. if r.Code != http.StatusNoContent {
  449. t.Fatalf("%d NO CONTENT expected, received %d\n", http.StatusNoContent, r.Code)
  450. }
  451. if containerRunning(eng, containerID, t) {
  452. t.Fatalf("The container hasn't been stopped")
  453. }
  454. req, err = http.NewRequest("POST", "/containers/"+containerID+"/stop?t=1", bytes.NewReader([]byte{}))
  455. if err != nil {
  456. t.Fatal(err)
  457. }
  458. r = httptest.NewRecorder()
  459. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  460. t.Fatal(err)
  461. }
  462. // Stopping an already stopper container should return a 304
  463. assertHttpNotError(r, t)
  464. if r.Code != http.StatusNotModified {
  465. t.Fatalf("%d NOT MODIFIER expected, received %d\n", http.StatusNotModified, r.Code)
  466. }
  467. }
  468. func TestPostContainersWait(t *testing.T) {
  469. eng := NewTestEngine(t)
  470. defer mkDaemonFromEngine(eng, t).Nuke()
  471. containerID := createTestContainer(eng,
  472. &runconfig.Config{
  473. Image: unitTestImageID,
  474. Cmd: []string{"/bin/sleep", "1"},
  475. OpenStdin: true,
  476. },
  477. t,
  478. )
  479. startContainer(eng, containerID, t)
  480. setTimeout(t, "Wait timed out", 3*time.Second, func() {
  481. r := httptest.NewRecorder()
  482. req, err := http.NewRequest("POST", "/containers/"+containerID+"/wait", bytes.NewReader([]byte{}))
  483. if err != nil {
  484. t.Fatal(err)
  485. }
  486. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  487. t.Fatal(err)
  488. }
  489. assertHttpNotError(r, t)
  490. var apiWait engine.Env
  491. if err := apiWait.Decode(r.Body); err != nil {
  492. t.Fatal(err)
  493. }
  494. if apiWait.GetInt("StatusCode") != 0 {
  495. t.Fatalf("Non zero exit code for sleep: %d\n", apiWait.GetInt("StatusCode"))
  496. }
  497. })
  498. if containerRunning(eng, containerID, t) {
  499. t.Fatalf("The container should be stopped after wait")
  500. }
  501. }
  502. func TestPostContainersAttach(t *testing.T) {
  503. eng := NewTestEngine(t)
  504. defer mkDaemonFromEngine(eng, t).Nuke()
  505. containerID := createTestContainer(eng,
  506. &runconfig.Config{
  507. Image: unitTestImageID,
  508. Cmd: []string{"/bin/cat"},
  509. OpenStdin: true,
  510. },
  511. t,
  512. )
  513. // Start the process
  514. startContainer(eng, containerID, t)
  515. stdin, stdinPipe := io.Pipe()
  516. stdout, stdoutPipe := io.Pipe()
  517. // Try to avoid the timeout in destroy. Best effort, don't check error
  518. defer func() {
  519. closeWrap(stdin, stdinPipe, stdout, stdoutPipe)
  520. containerKill(eng, containerID, t)
  521. }()
  522. // Attach to it
  523. c1 := make(chan struct{})
  524. go func() {
  525. defer close(c1)
  526. r := &hijackTester{
  527. ResponseRecorder: httptest.NewRecorder(),
  528. in: stdin,
  529. out: stdoutPipe,
  530. }
  531. req, err := http.NewRequest("POST", "/containers/"+containerID+"/attach?stream=1&stdin=1&stdout=1&stderr=1", bytes.NewReader([]byte{}))
  532. if err != nil {
  533. t.Fatal(err)
  534. }
  535. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  536. t.Fatal(err)
  537. }
  538. assertHttpNotError(r.ResponseRecorder, t)
  539. }()
  540. // Acknowledge hijack
  541. setTimeout(t, "hijack acknowledge timed out", 2*time.Second, func() {
  542. stdout.Read([]byte{})
  543. stdout.Read(make([]byte, 4096))
  544. })
  545. setTimeout(t, "read/write assertion timed out", 2*time.Second, func() {
  546. if err := assertPipe("hello\n", string([]byte{1, 0, 0, 0, 0, 0, 0, 6})+"hello", stdout, stdinPipe, 150); err != nil {
  547. t.Fatal(err)
  548. }
  549. })
  550. // Close pipes (client disconnects)
  551. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  552. t.Fatal(err)
  553. }
  554. // Wait for attach to finish, the client disconnected, therefore, Attach finished his job
  555. setTimeout(t, "Waiting for CmdAttach timed out", 10*time.Second, func() {
  556. <-c1
  557. })
  558. // We closed stdin, expect /bin/cat to still be running
  559. // Wait a little bit to make sure container.monitor() did his thing
  560. containerWaitTimeout(eng, containerID, t)
  561. // Try to avoid the timeout in destroy. Best effort, don't check error
  562. cStdin, _ := containerAttach(eng, containerID, t)
  563. cStdin.Close()
  564. containerWait(eng, containerID, t)
  565. }
  566. func TestPostContainersAttachStderr(t *testing.T) {
  567. eng := NewTestEngine(t)
  568. defer mkDaemonFromEngine(eng, t).Nuke()
  569. containerID := createTestContainer(eng,
  570. &runconfig.Config{
  571. Image: unitTestImageID,
  572. Cmd: []string{"/bin/sh", "-c", "/bin/cat >&2"},
  573. OpenStdin: true,
  574. },
  575. t,
  576. )
  577. // Start the process
  578. startContainer(eng, containerID, t)
  579. stdin, stdinPipe := io.Pipe()
  580. stdout, stdoutPipe := io.Pipe()
  581. // Try to avoid the timeout in destroy. Best effort, don't check error
  582. defer func() {
  583. closeWrap(stdin, stdinPipe, stdout, stdoutPipe)
  584. containerKill(eng, containerID, t)
  585. }()
  586. // Attach to it
  587. c1 := make(chan struct{})
  588. go func() {
  589. defer close(c1)
  590. r := &hijackTester{
  591. ResponseRecorder: httptest.NewRecorder(),
  592. in: stdin,
  593. out: stdoutPipe,
  594. }
  595. req, err := http.NewRequest("POST", "/containers/"+containerID+"/attach?stream=1&stdin=1&stdout=1&stderr=1", bytes.NewReader([]byte{}))
  596. if err != nil {
  597. t.Fatal(err)
  598. }
  599. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  600. t.Fatal(err)
  601. }
  602. assertHttpNotError(r.ResponseRecorder, t)
  603. }()
  604. // Acknowledge hijack
  605. setTimeout(t, "hijack acknowledge timed out", 2*time.Second, func() {
  606. stdout.Read([]byte{})
  607. stdout.Read(make([]byte, 4096))
  608. })
  609. setTimeout(t, "read/write assertion timed out", 2*time.Second, func() {
  610. if err := assertPipe("hello\n", string([]byte{2, 0, 0, 0, 0, 0, 0, 6})+"hello", stdout, stdinPipe, 150); err != nil {
  611. t.Fatal(err)
  612. }
  613. })
  614. // Close pipes (client disconnects)
  615. if err := closeWrap(stdin, stdinPipe, stdout, stdoutPipe); err != nil {
  616. t.Fatal(err)
  617. }
  618. // Wait for attach to finish, the client disconnected, therefore, Attach finished his job
  619. setTimeout(t, "Waiting for CmdAttach timed out", 10*time.Second, func() {
  620. <-c1
  621. })
  622. // We closed stdin, expect /bin/cat to still be running
  623. // Wait a little bit to make sure container.monitor() did his thing
  624. containerWaitTimeout(eng, containerID, t)
  625. // Try to avoid the timeout in destroy. Best effort, don't check error
  626. cStdin, _ := containerAttach(eng, containerID, t)
  627. cStdin.Close()
  628. containerWait(eng, containerID, t)
  629. }
  630. func TestOptionsRoute(t *testing.T) {
  631. eng := NewTestEngine(t)
  632. defer mkDaemonFromEngine(eng, t).Nuke()
  633. r := httptest.NewRecorder()
  634. req, err := http.NewRequest("OPTIONS", "/", nil)
  635. if err != nil {
  636. t.Fatal(err)
  637. }
  638. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  639. t.Fatal(err)
  640. }
  641. assertHttpNotError(r, t)
  642. if r.Code != http.StatusOK {
  643. t.Errorf("Expected response for OPTIONS request to be \"200\", %v found.", r.Code)
  644. }
  645. }
  646. func TestGetEnabledCors(t *testing.T) {
  647. eng := NewTestEngine(t)
  648. defer mkDaemonFromEngine(eng, t).Nuke()
  649. r := httptest.NewRecorder()
  650. req, err := http.NewRequest("GET", "/version", nil)
  651. if err != nil {
  652. t.Fatal(err)
  653. }
  654. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  655. t.Fatal(err)
  656. }
  657. assertHttpNotError(r, t)
  658. if r.Code != http.StatusOK {
  659. t.Errorf("Expected response for OPTIONS request to be \"200\", %v found.", r.Code)
  660. }
  661. allowOrigin := r.Header().Get("Access-Control-Allow-Origin")
  662. allowHeaders := r.Header().Get("Access-Control-Allow-Headers")
  663. allowMethods := r.Header().Get("Access-Control-Allow-Methods")
  664. if allowOrigin != "*" {
  665. t.Errorf("Expected header Access-Control-Allow-Origin to be \"*\", %s found.", allowOrigin)
  666. }
  667. if allowHeaders != "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth" {
  668. t.Errorf("Expected header Access-Control-Allow-Headers to be \"Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth\", %s found.", allowHeaders)
  669. }
  670. if allowMethods != "GET, POST, DELETE, PUT, OPTIONS" {
  671. t.Errorf("Expected hearder Access-Control-Allow-Methods to be \"GET, POST, DELETE, PUT, OPTIONS\", %s found.", allowMethods)
  672. }
  673. }
  674. func TestDeleteImages(t *testing.T) {
  675. eng := NewTestEngine(t)
  676. //we expect errors, so we disable stderr
  677. eng.Stderr = ioutil.Discard
  678. defer mkDaemonFromEngine(eng, t).Nuke()
  679. initialImages := getImages(eng, t, true, "")
  680. if err := eng.Job("tag", unitTestImageName, "test", "test").Run(); err != nil {
  681. t.Fatal(err)
  682. }
  683. images := getImages(eng, t, true, "")
  684. if len(images.Data[0].GetList("RepoTags")) != len(initialImages.Data[0].GetList("RepoTags"))+1 {
  685. t.Errorf("Expected %d images, %d found", len(initialImages.Data[0].GetList("RepoTags"))+1, len(images.Data[0].GetList("RepoTags")))
  686. }
  687. req, err := http.NewRequest("DELETE", "/images/"+unitTestImageID, nil)
  688. if err != nil {
  689. t.Fatal(err)
  690. }
  691. r := httptest.NewRecorder()
  692. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  693. t.Fatal(err)
  694. }
  695. if r.Code != http.StatusConflict {
  696. t.Fatalf("Expected http status 409-conflict, got %v", r.Code)
  697. }
  698. req2, err := http.NewRequest("DELETE", "/images/test:test", nil)
  699. if err != nil {
  700. t.Fatal(err)
  701. }
  702. r2 := httptest.NewRecorder()
  703. if err := server.ServeRequest(eng, api.APIVERSION, r2, req2); err != nil {
  704. t.Fatal(err)
  705. }
  706. assertHttpNotError(r2, t)
  707. if r2.Code != http.StatusOK {
  708. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  709. }
  710. outs := engine.NewTable("Created", 0)
  711. if _, err := outs.ReadListFrom(r2.Body.Bytes()); err != nil {
  712. t.Fatal(err)
  713. }
  714. if len(outs.Data) != 1 {
  715. t.Fatalf("Expected %d event (untagged), got %d", 1, len(outs.Data))
  716. }
  717. images = getImages(eng, t, false, "")
  718. if images.Len() != initialImages.Len() {
  719. t.Errorf("Expected %d image, %d found", initialImages.Len(), images.Len())
  720. }
  721. }
  722. func TestPostContainersCopy(t *testing.T) {
  723. eng := NewTestEngine(t)
  724. defer mkDaemonFromEngine(eng, t).Nuke()
  725. // Create a container and remove a file
  726. containerID := createTestContainer(eng,
  727. &runconfig.Config{
  728. Image: unitTestImageID,
  729. Cmd: []string{"touch", "/test.txt"},
  730. },
  731. t,
  732. )
  733. containerRun(eng, containerID, t)
  734. r := httptest.NewRecorder()
  735. var copyData engine.Env
  736. copyData.Set("Resource", "/test.txt")
  737. copyData.Set("HostPath", ".")
  738. jsonData := bytes.NewBuffer(nil)
  739. if err := copyData.Encode(jsonData); err != nil {
  740. t.Fatal(err)
  741. }
  742. req, err := http.NewRequest("POST", "/containers/"+containerID+"/copy", jsonData)
  743. if err != nil {
  744. t.Fatal(err)
  745. }
  746. req.Header.Add("Content-Type", "application/json")
  747. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  748. t.Fatal(err)
  749. }
  750. assertHttpNotError(r, t)
  751. if r.Code != http.StatusOK {
  752. t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code)
  753. }
  754. found := false
  755. for tarReader := tar.NewReader(r.Body); ; {
  756. h, err := tarReader.Next()
  757. if err != nil {
  758. if err == io.EOF {
  759. break
  760. }
  761. t.Fatal(err)
  762. }
  763. if h.Name == "test.txt" {
  764. found = true
  765. break
  766. }
  767. }
  768. if !found {
  769. t.Fatalf("The created test file has not been found in the copied output")
  770. }
  771. }
  772. func TestPostContainersCopyWhenContainerNotFound(t *testing.T) {
  773. eng := NewTestEngine(t)
  774. defer mkDaemonFromEngine(eng, t).Nuke()
  775. r := httptest.NewRecorder()
  776. var copyData engine.Env
  777. copyData.Set("Resource", "/test.txt")
  778. copyData.Set("HostPath", ".")
  779. jsonData := bytes.NewBuffer(nil)
  780. if err := copyData.Encode(jsonData); err != nil {
  781. t.Fatal(err)
  782. }
  783. req, err := http.NewRequest("POST", "/containers/id_not_found/copy", jsonData)
  784. if err != nil {
  785. t.Fatal(err)
  786. }
  787. req.Header.Add("Content-Type", "application/json")
  788. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  789. t.Fatal(err)
  790. }
  791. if r.Code != http.StatusNotFound {
  792. t.Fatalf("404 expected for id_not_found Container, received %v", r.Code)
  793. }
  794. }
  795. // Regression test for https://github.com/docker/docker/issues/6231
  796. func TestConstainersStartChunkedEncodingHostConfig(t *testing.T) {
  797. eng := NewTestEngine(t)
  798. defer mkDaemonFromEngine(eng, t).Nuke()
  799. r := httptest.NewRecorder()
  800. var testData engine.Env
  801. testData.Set("Image", "docker-test-image")
  802. testData.SetAuto("Volumes", map[string]struct{}{"/foo": {}})
  803. testData.Set("Cmd", "true")
  804. jsonData := bytes.NewBuffer(nil)
  805. if err := testData.Encode(jsonData); err != nil {
  806. t.Fatal(err)
  807. }
  808. req, err := http.NewRequest("POST", "/containers/create?name=chunk_test", jsonData)
  809. if err != nil {
  810. t.Fatal(err)
  811. }
  812. req.Header.Add("Content-Type", "application/json")
  813. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  814. t.Fatal(err)
  815. }
  816. assertHttpNotError(r, t)
  817. var testData2 engine.Env
  818. testData2.SetAuto("Binds", []string{"/tmp:/foo"})
  819. jsonData = bytes.NewBuffer(nil)
  820. if err := testData2.Encode(jsonData); err != nil {
  821. t.Fatal(err)
  822. }
  823. req, err = http.NewRequest("POST", "/containers/chunk_test/start", jsonData)
  824. if err != nil {
  825. t.Fatal(err)
  826. }
  827. req.Header.Add("Content-Type", "application/json")
  828. // This is a cheat to make the http request do chunked encoding
  829. // Otherwise (just setting the Content-Encoding to chunked) net/http will overwrite
  830. // http://golang.org/src/pkg/net/http/request.go?s=11980:12172
  831. req.ContentLength = -1
  832. if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
  833. t.Fatal(err)
  834. }
  835. assertHttpNotError(r, t)
  836. type config struct {
  837. HostConfig struct {
  838. Binds []string
  839. }
  840. }
  841. req, err = http.NewRequest("GET", "/containers/chunk_test/json", nil)
  842. if err != nil {
  843. t.Fatal(err)
  844. }
  845. r2 := httptest.NewRecorder()
  846. req.Header.Add("Content-Type", "application/json")
  847. if err := server.ServeRequest(eng, api.APIVERSION, r2, req); err != nil {
  848. t.Fatal(err)
  849. }
  850. assertHttpNotError(r, t)
  851. c := config{}
  852. json.Unmarshal(r2.Body.Bytes(), &c)
  853. if len(c.HostConfig.Binds) == 0 {
  854. t.Fatal("Chunked Encoding not handled")
  855. }
  856. if c.HostConfig.Binds[0] != "/tmp:/foo" {
  857. t.Fatal("Chunked encoding not properly handled, execpted binds to be /tmp:/foo, got:", c.HostConfig.Binds[0])
  858. }
  859. }
  860. // Mocked types for tests
  861. type NopConn struct {
  862. io.ReadCloser
  863. io.Writer
  864. }
  865. func (c *NopConn) LocalAddr() net.Addr { return nil }
  866. func (c *NopConn) RemoteAddr() net.Addr { return nil }
  867. func (c *NopConn) SetDeadline(t time.Time) error { return nil }
  868. func (c *NopConn) SetReadDeadline(t time.Time) error { return nil }
  869. func (c *NopConn) SetWriteDeadline(t time.Time) error { return nil }
  870. type hijackTester struct {
  871. *httptest.ResponseRecorder
  872. in io.ReadCloser
  873. out io.Writer
  874. }
  875. func (t *hijackTester) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  876. bufrw := bufio.NewReadWriter(bufio.NewReader(t.in), bufio.NewWriter(t.out))
  877. conn := &NopConn{
  878. ReadCloser: t.in,
  879. Writer: t.out,
  880. }
  881. return conn, bufrw, nil
  882. }