api_test.go 26 KB

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