docker_api_containers_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io"
  6. "net/http"
  7. "os/exec"
  8. "strings"
  9. "testing"
  10. "time"
  11. "github.com/docker/docker/api/types"
  12. "github.com/docker/docker/pkg/stringid"
  13. "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
  14. )
  15. func TestContainerApiGetAll(t *testing.T) {
  16. defer deleteAllContainers()
  17. startCount, err := getContainerCount()
  18. if err != nil {
  19. t.Fatalf("Cannot query container count: %v", err)
  20. }
  21. name := "getall"
  22. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "true")
  23. out, _, err := runCommandWithOutput(runCmd)
  24. if err != nil {
  25. t.Fatalf("Error on container creation: %v, output: %q", err, out)
  26. }
  27. _, body, err := sockRequest("GET", "/containers/json?all=1", nil)
  28. if err != nil {
  29. t.Fatalf("GET all containers sockRequest failed: %v", err)
  30. }
  31. var inspectJSON []struct {
  32. Names []string
  33. }
  34. if err = json.Unmarshal(body, &inspectJSON); err != nil {
  35. t.Fatalf("unable to unmarshal response body: %v", err)
  36. }
  37. if len(inspectJSON) != startCount+1 {
  38. t.Fatalf("Expected %d container(s), %d found (started with: %d)", startCount+1, len(inspectJSON), startCount)
  39. }
  40. if actual := inspectJSON[0].Names[0]; actual != "/"+name {
  41. t.Fatalf("Container Name mismatch. Expected: %q, received: %q\n", "/"+name, actual)
  42. }
  43. logDone("container REST API - check GET json/all=1")
  44. }
  45. func TestContainerApiGetExport(t *testing.T) {
  46. defer deleteAllContainers()
  47. name := "exportcontainer"
  48. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "touch", "/test")
  49. out, _, err := runCommandWithOutput(runCmd)
  50. if err != nil {
  51. t.Fatalf("Error on container creation: %v, output: %q", err, out)
  52. }
  53. _, body, err := sockRequest("GET", "/containers/"+name+"/export", nil)
  54. if err != nil {
  55. t.Fatalf("GET containers/export sockRequest failed: %v", err)
  56. }
  57. found := false
  58. for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
  59. h, err := tarReader.Next()
  60. if err != nil {
  61. if err == io.EOF {
  62. break
  63. }
  64. t.Fatal(err)
  65. }
  66. if h.Name == "test" {
  67. found = true
  68. break
  69. }
  70. }
  71. if !found {
  72. t.Fatalf("The created test file has not been found in the exported image")
  73. }
  74. logDone("container REST API - check GET containers/export")
  75. }
  76. func TestContainerApiGetChanges(t *testing.T) {
  77. defer deleteAllContainers()
  78. name := "changescontainer"
  79. runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "rm", "/etc/passwd")
  80. out, _, err := runCommandWithOutput(runCmd)
  81. if err != nil {
  82. t.Fatalf("Error on container creation: %v, output: %q", err, out)
  83. }
  84. _, body, err := sockRequest("GET", "/containers/"+name+"/changes", nil)
  85. if err != nil {
  86. t.Fatalf("GET containers/changes sockRequest failed: %v", err)
  87. }
  88. changes := []struct {
  89. Kind int
  90. Path string
  91. }{}
  92. if err = json.Unmarshal(body, &changes); err != nil {
  93. t.Fatalf("unable to unmarshal response body: %v", err)
  94. }
  95. // Check the changelog for removal of /etc/passwd
  96. success := false
  97. for _, elem := range changes {
  98. if elem.Path == "/etc/passwd" && elem.Kind == 2 {
  99. success = true
  100. }
  101. }
  102. if !success {
  103. t.Fatalf("/etc/passwd has been removed but is not present in the diff")
  104. }
  105. logDone("container REST API - check GET containers/changes")
  106. }
  107. func TestContainerApiStartVolumeBinds(t *testing.T) {
  108. defer deleteAllContainers()
  109. name := "testing"
  110. config := map[string]interface{}{
  111. "Image": "busybox",
  112. "Volumes": map[string]struct{}{"/tmp": {}},
  113. }
  114. if status, _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && status != http.StatusCreated {
  115. t.Fatal(err)
  116. }
  117. bindPath := randomUnixTmpDirPath("test")
  118. config = map[string]interface{}{
  119. "Binds": []string{bindPath + ":/tmp"},
  120. }
  121. if status, _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && status != http.StatusNoContent {
  122. t.Fatal(err)
  123. }
  124. pth, err := inspectFieldMap(name, "Volumes", "/tmp")
  125. if err != nil {
  126. t.Fatal(err)
  127. }
  128. if pth != bindPath {
  129. t.Fatalf("expected volume host path to be %s, got %s", bindPath, pth)
  130. }
  131. logDone("container REST API - check volume binds on start")
  132. }
  133. // Test for GH#10618
  134. func TestContainerApiStartDupVolumeBinds(t *testing.T) {
  135. defer deleteAllContainers()
  136. name := "testdups"
  137. config := map[string]interface{}{
  138. "Image": "busybox",
  139. "Volumes": map[string]struct{}{"/tmp": {}},
  140. }
  141. if status, _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && status != http.StatusCreated {
  142. t.Fatal(err)
  143. }
  144. bindPath1 := randomUnixTmpDirPath("test1")
  145. bindPath2 := randomUnixTmpDirPath("test2")
  146. config = map[string]interface{}{
  147. "Binds": []string{bindPath1 + ":/tmp", bindPath2 + ":/tmp"},
  148. }
  149. if _, body, err := sockRequest("POST", "/containers/"+name+"/start", config); err == nil {
  150. t.Fatal("expected container start to fail when duplicate volume binds to same container path")
  151. } else {
  152. if !strings.Contains(string(body), "Duplicate volume") {
  153. t.Fatalf("Expected failure due to duplicate bind mounts to same path, instead got: %q with error: %v", string(body), err)
  154. }
  155. }
  156. logDone("container REST API - check for duplicate volume binds error on start")
  157. }
  158. func TestContainerApiStartVolumesFrom(t *testing.T) {
  159. defer deleteAllContainers()
  160. volName := "voltst"
  161. volPath := "/tmp"
  162. if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", volName, "-v", volPath, "busybox")); err != nil {
  163. t.Fatal(out, err)
  164. }
  165. name := "testing"
  166. config := map[string]interface{}{
  167. "Image": "busybox",
  168. "Volumes": map[string]struct{}{volPath: {}},
  169. }
  170. if status, _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && status != http.StatusCreated {
  171. t.Fatal(err)
  172. }
  173. config = map[string]interface{}{
  174. "VolumesFrom": []string{volName},
  175. }
  176. if status, _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && status != http.StatusNoContent {
  177. t.Fatal(err)
  178. }
  179. pth, err := inspectFieldMap(name, "Volumes", volPath)
  180. if err != nil {
  181. t.Fatal(err)
  182. }
  183. pth2, err := inspectFieldMap(volName, "Volumes", volPath)
  184. if err != nil {
  185. t.Fatal(err)
  186. }
  187. if pth != pth2 {
  188. t.Fatalf("expected volume host path to be %s, got %s", pth, pth2)
  189. }
  190. logDone("container REST API - check VolumesFrom on start")
  191. }
  192. // Ensure that volumes-from has priority over binds/anything else
  193. // This is pretty much the same as TestRunApplyVolumesFromBeforeVolumes, except with passing the VolumesFrom and the bind on start
  194. func TestVolumesFromHasPriority(t *testing.T) {
  195. defer deleteAllContainers()
  196. volName := "voltst2"
  197. volPath := "/tmp"
  198. if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", volName, "-v", volPath, "busybox")); err != nil {
  199. t.Fatal(out, err)
  200. }
  201. name := "testing"
  202. config := map[string]interface{}{
  203. "Image": "busybox",
  204. "Volumes": map[string]struct{}{volPath: {}},
  205. }
  206. if status, _, err := sockRequest("POST", "/containers/create?name="+name, config); err != nil && status != http.StatusCreated {
  207. t.Fatal(err)
  208. }
  209. bindPath := randomUnixTmpDirPath("test")
  210. config = map[string]interface{}{
  211. "VolumesFrom": []string{volName},
  212. "Binds": []string{bindPath + ":/tmp"},
  213. }
  214. if status, _, err := sockRequest("POST", "/containers/"+name+"/start", config); err != nil && status != http.StatusNoContent {
  215. t.Fatal(err)
  216. }
  217. pth, err := inspectFieldMap(name, "Volumes", volPath)
  218. if err != nil {
  219. t.Fatal(err)
  220. }
  221. pth2, err := inspectFieldMap(volName, "Volumes", volPath)
  222. if err != nil {
  223. t.Fatal(err)
  224. }
  225. if pth != pth2 {
  226. t.Fatalf("expected volume host path to be %s, got %s", pth, pth2)
  227. }
  228. logDone("container REST API - check VolumesFrom has priority")
  229. }
  230. func TestGetContainerStats(t *testing.T) {
  231. defer deleteAllContainers()
  232. var (
  233. name = "statscontainer"
  234. runCmd = exec.Command(dockerBinary, "run", "-d", "--name", name, "busybox", "top")
  235. )
  236. out, _, err := runCommandWithOutput(runCmd)
  237. if err != nil {
  238. t.Fatalf("Error on container creation: %v, output: %q", err, out)
  239. }
  240. type b struct {
  241. body []byte
  242. err error
  243. }
  244. bc := make(chan b, 1)
  245. go func() {
  246. _, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  247. bc <- b{body, err}
  248. }()
  249. // allow some time to stream the stats from the container
  250. time.Sleep(4 * time.Second)
  251. if _, err := runCommand(exec.Command(dockerBinary, "rm", "-f", name)); err != nil {
  252. t.Fatal(err)
  253. }
  254. // collect the results from the stats stream or timeout and fail
  255. // if the stream was not disconnected.
  256. select {
  257. case <-time.After(2 * time.Second):
  258. t.Fatal("stream was not closed after container was removed")
  259. case sr := <-bc:
  260. if sr.err != nil {
  261. t.Fatal(sr.err)
  262. }
  263. dec := json.NewDecoder(bytes.NewBuffer(sr.body))
  264. var s *types.Stats
  265. // decode only one object from the stream
  266. if err := dec.Decode(&s); err != nil {
  267. t.Fatal(err)
  268. }
  269. }
  270. logDone("container REST API - check GET containers/stats")
  271. }
  272. func TestGetStoppedContainerStats(t *testing.T) {
  273. defer deleteAllContainers()
  274. var (
  275. name = "statscontainer"
  276. runCmd = exec.Command(dockerBinary, "create", "--name", name, "busybox", "top")
  277. )
  278. out, _, err := runCommandWithOutput(runCmd)
  279. if err != nil {
  280. t.Fatalf("Error on container creation: %v, output: %q", err, out)
  281. }
  282. go func() {
  283. // We'll never get return for GET stats from sockRequest as of now,
  284. // just send request and see if panic or error would happen on daemon side.
  285. _, _, err := sockRequest("GET", "/containers/"+name+"/stats", nil)
  286. if err != nil {
  287. t.Fatal(err)
  288. }
  289. }()
  290. // allow some time to send request and let daemon deal with it
  291. time.Sleep(1 * time.Second)
  292. logDone("container REST API - check GET stopped containers/stats")
  293. }
  294. func TestBuildApiDockerfilePath(t *testing.T) {
  295. // Test to make sure we stop people from trying to leave the
  296. // build context when specifying the path to the dockerfile
  297. buffer := new(bytes.Buffer)
  298. tw := tar.NewWriter(buffer)
  299. defer tw.Close()
  300. dockerfile := []byte("FROM busybox")
  301. if err := tw.WriteHeader(&tar.Header{
  302. Name: "Dockerfile",
  303. Size: int64(len(dockerfile)),
  304. }); err != nil {
  305. t.Fatalf("failed to write tar file header: %v", err)
  306. }
  307. if _, err := tw.Write(dockerfile); err != nil {
  308. t.Fatalf("failed to write tar file content: %v", err)
  309. }
  310. if err := tw.Close(); err != nil {
  311. t.Fatalf("failed to close tar archive: %v", err)
  312. }
  313. _, body, err := sockRequestRaw("POST", "/build?dockerfile=../Dockerfile", buffer, "application/x-tar")
  314. if err == nil {
  315. out, _ := readBody(body)
  316. t.Fatalf("Build was supposed to fail: %s", out)
  317. }
  318. out, err := readBody(body)
  319. if err != nil {
  320. t.Fatal(err)
  321. }
  322. if !strings.Contains(string(out), "must be within the build context") {
  323. t.Fatalf("Didn't complain about leaving build context: %s", out)
  324. }
  325. logDone("container REST API - check build w/bad Dockerfile path")
  326. }
  327. func TestBuildApiDockerFileRemote(t *testing.T) {
  328. server, err := fakeStorage(map[string]string{
  329. "testD": `FROM busybox
  330. COPY * /tmp/
  331. RUN find / -name ba*
  332. RUN find /tmp/`,
  333. })
  334. if err != nil {
  335. t.Fatal(err)
  336. }
  337. defer server.Close()
  338. _, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+server.URL()+"/testD", nil, "application/json")
  339. if err != nil {
  340. t.Fatalf("Build failed: %s", err)
  341. }
  342. buf, err := readBody(body)
  343. if err != nil {
  344. t.Fatal(err)
  345. }
  346. // Make sure Dockerfile exists.
  347. // Make sure 'baz' doesn't exist ANYWHERE despite being mentioned in the URL
  348. out := string(buf)
  349. if !strings.Contains(out, "/tmp/Dockerfile") ||
  350. strings.Contains(out, "baz") {
  351. t.Fatalf("Incorrect output: %s", out)
  352. }
  353. logDone("container REST API - check build with -f from remote")
  354. }
  355. func TestBuildApiLowerDockerfile(t *testing.T) {
  356. git, err := fakeGIT("repo", map[string]string{
  357. "dockerfile": `FROM busybox
  358. RUN echo from dockerfile`,
  359. }, false)
  360. if err != nil {
  361. t.Fatal(err)
  362. }
  363. defer git.Close()
  364. _, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
  365. if err != nil {
  366. buf, _ := readBody(body)
  367. t.Fatalf("Build failed: %s\n%q", err, buf)
  368. }
  369. buf, err := readBody(body)
  370. if err != nil {
  371. t.Fatal(err)
  372. }
  373. out := string(buf)
  374. if !strings.Contains(out, "from dockerfile") {
  375. t.Fatalf("Incorrect output: %s", out)
  376. }
  377. logDone("container REST API - check build with lower dockerfile")
  378. }
  379. func TestBuildApiBuildGitWithF(t *testing.T) {
  380. git, err := fakeGIT("repo", map[string]string{
  381. "baz": `FROM busybox
  382. RUN echo from baz`,
  383. "Dockerfile": `FROM busybox
  384. RUN echo from Dockerfile`,
  385. }, false)
  386. if err != nil {
  387. t.Fatal(err)
  388. }
  389. defer git.Close()
  390. // Make sure it tries to 'dockerfile' query param value
  391. _, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+git.RepoURL, nil, "application/json")
  392. if err != nil {
  393. buf, _ := readBody(body)
  394. t.Fatalf("Build failed: %s\n%q", err, buf)
  395. }
  396. buf, err := readBody(body)
  397. if err != nil {
  398. t.Fatal(err)
  399. }
  400. out := string(buf)
  401. if !strings.Contains(out, "from baz") {
  402. t.Fatalf("Incorrect output: %s", out)
  403. }
  404. logDone("container REST API - check build from git w/F")
  405. }
  406. func TestBuildApiDoubleDockerfile(t *testing.T) {
  407. testRequires(t, UnixCli) // dockerfile overwrites Dockerfile on Windows
  408. git, err := fakeGIT("repo", map[string]string{
  409. "Dockerfile": `FROM busybox
  410. RUN echo from Dockerfile`,
  411. "dockerfile": `FROM busybox
  412. RUN echo from dockerfile`,
  413. }, false)
  414. if err != nil {
  415. t.Fatal(err)
  416. }
  417. defer git.Close()
  418. // Make sure it tries to 'dockerfile' query param value
  419. _, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json")
  420. if err != nil {
  421. t.Fatalf("Build failed: %s", err)
  422. }
  423. buf, err := readBody(body)
  424. if err != nil {
  425. t.Fatal(err)
  426. }
  427. out := string(buf)
  428. if !strings.Contains(out, "from Dockerfile") {
  429. t.Fatalf("Incorrect output: %s", out)
  430. }
  431. logDone("container REST API - check build with two dockerfiles")
  432. }
  433. func TestBuildApiDockerfileSymlink(t *testing.T) {
  434. // Test to make sure we stop people from trying to leave the
  435. // build context when specifying a symlink as the path to the dockerfile
  436. buffer := new(bytes.Buffer)
  437. tw := tar.NewWriter(buffer)
  438. defer tw.Close()
  439. if err := tw.WriteHeader(&tar.Header{
  440. Name: "Dockerfile",
  441. Typeflag: tar.TypeSymlink,
  442. Linkname: "/etc/passwd",
  443. }); err != nil {
  444. t.Fatalf("failed to write tar file header: %v", err)
  445. }
  446. if err := tw.Close(); err != nil {
  447. t.Fatalf("failed to close tar archive: %v", err)
  448. }
  449. _, body, err := sockRequestRaw("POST", "/build", buffer, "application/x-tar")
  450. if err == nil {
  451. out, _ := readBody(body)
  452. t.Fatalf("Build was supposed to fail: %s", out)
  453. }
  454. out, err := readBody(body)
  455. if err != nil {
  456. t.Fatal(err)
  457. }
  458. // The reason the error is "Cannot locate specified Dockerfile" is because
  459. // in the builder, the symlink is resolved within the context, therefore
  460. // Dockerfile -> /etc/passwd becomes etc/passwd from the context which is
  461. // a nonexistent file.
  462. if !strings.Contains(string(out), "Cannot locate specified Dockerfile: Dockerfile") {
  463. t.Fatalf("Didn't complain about leaving build context: %s", out)
  464. }
  465. logDone("container REST API - check build w/bad Dockerfile symlink path")
  466. }
  467. // #9981 - Allow a docker created volume (ie, one in /var/lib/docker/volumes) to be used to overwrite (via passing in Binds on api start) an existing volume
  468. func TestPostContainerBindNormalVolume(t *testing.T) {
  469. defer deleteAllContainers()
  470. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "create", "-v", "/foo", "--name=one", "busybox"))
  471. if err != nil {
  472. t.Fatal(err, out)
  473. }
  474. fooDir, err := inspectFieldMap("one", "Volumes", "/foo")
  475. if err != nil {
  476. t.Fatal(err)
  477. }
  478. out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "create", "-v", "/foo", "--name=two", "busybox"))
  479. if err != nil {
  480. t.Fatal(err, out)
  481. }
  482. bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}}
  483. if status, _, err := sockRequest("POST", "/containers/two/start", bindSpec); err != nil && status != http.StatusNoContent {
  484. t.Fatal(err)
  485. }
  486. fooDir2, err := inspectFieldMap("two", "Volumes", "/foo")
  487. if err != nil {
  488. t.Fatal(err)
  489. }
  490. if fooDir2 != fooDir {
  491. t.Fatalf("expected volume path to be %s, got: %s", fooDir, fooDir2)
  492. }
  493. logDone("container REST API - can use path from normal volume as bind-mount to overwrite another volume")
  494. }
  495. func TestContainerApiPause(t *testing.T) {
  496. defer deleteAllContainers()
  497. defer unpauseAllContainers()
  498. runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "sleep", "30")
  499. out, _, err := runCommandWithOutput(runCmd)
  500. if err != nil {
  501. t.Fatalf("failed to create a container: %s, %v", out, err)
  502. }
  503. ContainerID := strings.TrimSpace(out)
  504. if status, _, err := sockRequest("POST", "/containers/"+ContainerID+"/pause", nil); err != nil && status != http.StatusNoContent {
  505. t.Fatalf("POST a container pause: sockRequest failed: %v", err)
  506. }
  507. pausedContainers, err := getSliceOfPausedContainers()
  508. if err != nil {
  509. t.Fatalf("error thrown while checking if containers were paused: %v", err)
  510. }
  511. if len(pausedContainers) != 1 || stringid.TruncateID(ContainerID) != pausedContainers[0] {
  512. t.Fatalf("there should be one paused container and not %d", len(pausedContainers))
  513. }
  514. if status, _, err := sockRequest("POST", "/containers/"+ContainerID+"/unpause", nil); err != nil && status != http.StatusNoContent {
  515. t.Fatalf("POST a container pause: sockRequest failed: %v", err)
  516. }
  517. pausedContainers, err = getSliceOfPausedContainers()
  518. if err != nil {
  519. t.Fatalf("error thrown while checking if containers were paused: %v", err)
  520. }
  521. if pausedContainers != nil {
  522. t.Fatalf("There should be no paused container.")
  523. }
  524. logDone("container REST API - check POST containers/pause and unpause")
  525. }
  526. func TestContainerApiTop(t *testing.T) {
  527. defer deleteAllContainers()
  528. out, _ := dockerCmd(t, "run", "-d", "-i", "busybox", "/bin/sh", "-c", "cat")
  529. id := strings.TrimSpace(out)
  530. if err := waitRun(id); err != nil {
  531. t.Fatal(err)
  532. }
  533. type topResp struct {
  534. Titles []string
  535. Processes [][]string
  536. }
  537. var top topResp
  538. _, b, err := sockRequest("GET", "/containers/"+id+"/top?ps_args=aux", nil)
  539. if err != nil {
  540. t.Fatal(err)
  541. }
  542. if err := json.Unmarshal(b, &top); err != nil {
  543. t.Fatal(err)
  544. }
  545. if len(top.Titles) != 11 {
  546. t.Fatalf("expected 11 titles, found %d: %v", len(top.Titles), top.Titles)
  547. }
  548. if top.Titles[0] != "USER" || top.Titles[10] != "COMMAND" {
  549. t.Fatalf("expected `USER` at `Titles[0]` and `COMMAND` at Titles[10]: %v", top.Titles)
  550. }
  551. if len(top.Processes) != 2 {
  552. t.Fatalf("expeted 2 processes, found %d: %v", len(top.Processes), top.Processes)
  553. }
  554. if top.Processes[0][10] != "/bin/sh -c cat" {
  555. t.Fatalf("expected `/bin/sh -c cat`, found: %s", top.Processes[0][10])
  556. }
  557. if top.Processes[1][10] != "cat" {
  558. t.Fatalf("expected `cat`, found: %s", top.Processes[1][10])
  559. }
  560. logDone("containers REST API - GET /containers/<id>/top")
  561. }
  562. func TestContainerApiCommit(t *testing.T) {
  563. out, _ := dockerCmd(t, "run", "-d", "busybox", "/bin/sh", "-c", "touch /test")
  564. id := strings.TrimSpace(out)
  565. name := "testcommit"
  566. _, b, err := sockRequest("POST", "/commit?repo="+name+"&testtag=tag&container="+id, nil)
  567. if err != nil && !strings.Contains(err.Error(), "200 OK: 201") {
  568. t.Fatal(err)
  569. }
  570. type resp struct {
  571. Id string
  572. }
  573. var img resp
  574. if err := json.Unmarshal(b, &img); err != nil {
  575. t.Fatal(err)
  576. }
  577. defer deleteImages(img.Id)
  578. out, err = inspectField(img.Id, "Config.Cmd")
  579. if out != "[/bin/sh -c touch /test]" {
  580. t.Fatalf("got wrong Cmd from commit: %q", out)
  581. }
  582. // sanity check, make sure the image is what we think it is
  583. dockerCmd(t, "run", img.Id, "ls", "/test")
  584. logDone("containers REST API - POST /commit")
  585. }
  586. func TestContainerApiCreate(t *testing.T) {
  587. defer deleteAllContainers()
  588. config := map[string]interface{}{
  589. "Image": "busybox",
  590. "Cmd": []string{"/bin/sh", "-c", "touch /test && ls /test"},
  591. }
  592. _, b, err := sockRequest("POST", "/containers/create", config)
  593. if err != nil && !strings.Contains(err.Error(), "200 OK: 201") {
  594. t.Fatal(err)
  595. }
  596. type createResp struct {
  597. Id string
  598. }
  599. var container createResp
  600. if err := json.Unmarshal(b, &container); err != nil {
  601. t.Fatal(err)
  602. }
  603. out, _ := dockerCmd(t, "start", "-a", container.Id)
  604. if strings.TrimSpace(out) != "/test" {
  605. t.Fatalf("expected output `/test`, got %q", out)
  606. }
  607. logDone("containers REST API - POST /containers/create")
  608. }
  609. func TestContainerApiVerifyHeader(t *testing.T) {
  610. defer deleteAllContainers()
  611. config := map[string]interface{}{
  612. "Image": "busybox",
  613. }
  614. create := func(ct string) (int, io.ReadCloser, error) {
  615. jsonData := bytes.NewBuffer(nil)
  616. if err := json.NewEncoder(jsonData).Encode(config); err != nil {
  617. t.Fatal(err)
  618. }
  619. return sockRequestRaw("POST", "/containers/create", jsonData, ct)
  620. }
  621. // Try with no content-type
  622. _, body, err := create("")
  623. if err == nil {
  624. b, _ := readBody(body)
  625. t.Fatalf("expected error when content-type is not set: %q", string(b))
  626. }
  627. body.Close()
  628. // Try with wrong content-type
  629. _, body, err = create("application/xml")
  630. if err == nil {
  631. b, _ := readBody(body)
  632. t.Fatalf("expected error when content-type is not set: %q", string(b))
  633. }
  634. body.Close()
  635. // now application/json
  636. _, body, err = create("application/json")
  637. if err != nil && !strings.Contains(err.Error(), "200 OK: 201") {
  638. b, _ := readBody(body)
  639. t.Fatalf("%v - %q", err, string(b))
  640. }
  641. body.Close()
  642. logDone("containers REST API - verify create header")
  643. }
  644. // Issue 7941 - test to make sure a "null" in JSON is just ignored.
  645. // W/o this fix a null in JSON would be parsed into a string var as "null"
  646. func TestContainerApiPostCreateNull(t *testing.T) {
  647. config := `{
  648. "Hostname":"",
  649. "Domainname":"",
  650. "Memory":0,
  651. "MemorySwap":0,
  652. "CpuShares":0,
  653. "Cpuset":null,
  654. "AttachStdin":true,
  655. "AttachStdout":true,
  656. "AttachStderr":true,
  657. "PortSpecs":null,
  658. "ExposedPorts":{},
  659. "Tty":true,
  660. "OpenStdin":true,
  661. "StdinOnce":true,
  662. "Env":[],
  663. "Cmd":"ls",
  664. "Image":"busybox",
  665. "Volumes":{},
  666. "WorkingDir":"",
  667. "Entrypoint":null,
  668. "NetworkDisabled":false,
  669. "OnBuild":null}`
  670. _, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  671. if err != nil && !strings.Contains(err.Error(), "200 OK: 201") {
  672. b, _ := readBody(body)
  673. t.Fatal(err, string(b))
  674. }
  675. b, err := readBody(body)
  676. if err != nil {
  677. t.Fatal(err)
  678. }
  679. type createResp struct {
  680. Id string
  681. }
  682. var container createResp
  683. if err := json.Unmarshal(b, &container); err != nil {
  684. t.Fatal(err)
  685. }
  686. out, err := inspectField(container.Id, "HostConfig.CpusetCpus")
  687. if err != nil {
  688. t.Fatal(err, out)
  689. }
  690. if out != "" {
  691. t.Fatalf("expected empty string, got %q", out)
  692. }
  693. logDone("containers REST API - Create Null")
  694. }
  695. func TestCreateWithTooLowMemoryLimit(t *testing.T) {
  696. defer deleteAllContainers()
  697. config := `{
  698. "Image": "busybox",
  699. "Cmd": "ls",
  700. "OpenStdin": true,
  701. "CpuShares": 100,
  702. "Memory": 524287
  703. }`
  704. _, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json")
  705. b, err2 := readBody(body)
  706. if err2 != nil {
  707. t.Fatal(err2)
  708. }
  709. if err == nil || !strings.Contains(string(b), "Minimum memory limit allowed is 4MB") {
  710. t.Errorf("Memory limit is smaller than the allowed limit. Container creation should've failed!")
  711. }
  712. logDone("container REST API - create can't set too low memory limit")
  713. }
  714. func TestStartWithTooLowMemoryLimit(t *testing.T) {
  715. defer deleteAllContainers()
  716. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "create", "busybox"))
  717. if err != nil {
  718. t.Fatal(err, out)
  719. }
  720. containerID := strings.TrimSpace(out)
  721. config := `{
  722. "CpuShares": 100,
  723. "Memory": 524287
  724. }`
  725. _, body, err := sockRequestRaw("POST", "/containers/"+containerID+"/start", strings.NewReader(config), "application/json")
  726. b, err2 := readBody(body)
  727. if err2 != nil {
  728. t.Fatal(err2)
  729. }
  730. if err == nil || !strings.Contains(string(b), "Minimum memory limit allowed is 4MB") {
  731. t.Errorf("Memory limit is smaller than the allowed limit. Container creation should've failed!")
  732. }
  733. logDone("container REST API - start can't set too low memory limit")
  734. }