docker_api_logs_test.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "strconv"
  11. "strings"
  12. "testing"
  13. "time"
  14. "github.com/docker/docker/api/types"
  15. "github.com/docker/docker/client"
  16. "github.com/docker/docker/pkg/stdcopy"
  17. "github.com/docker/docker/testutil/request"
  18. "gotest.tools/assert"
  19. )
  20. func (s *DockerSuite) TestLogsAPIWithStdout(c *testing.T) {
  21. out, _ := dockerCmd(c, "run", "-d", "-t", "busybox", "/bin/sh", "-c", "while true; do echo hello; sleep 1; done")
  22. id := strings.TrimSpace(out)
  23. assert.NilError(c, waitRun(id))
  24. type logOut struct {
  25. out string
  26. err error
  27. }
  28. chLog := make(chan logOut)
  29. res, body, err := request.Get(fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&timestamps=1", id))
  30. assert.NilError(c, err)
  31. assert.Equal(c, res.StatusCode, http.StatusOK)
  32. go func() {
  33. defer body.Close()
  34. out, err := bufio.NewReader(body).ReadString('\n')
  35. if err != nil {
  36. chLog <- logOut{"", err}
  37. return
  38. }
  39. chLog <- logOut{strings.TrimSpace(out), err}
  40. }()
  41. select {
  42. case l := <-chLog:
  43. assert.NilError(c, l.err)
  44. if !strings.HasSuffix(l.out, "hello") {
  45. c.Fatalf("expected log output to container 'hello', but it does not")
  46. }
  47. case <-time.After(30 * time.Second):
  48. c.Fatal("timeout waiting for logs to exit")
  49. }
  50. }
  51. func (s *DockerSuite) TestLogsAPINoStdoutNorStderr(c *testing.T) {
  52. name := "logs_test"
  53. dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh")
  54. cli, err := client.NewClientWithOpts(client.FromEnv)
  55. assert.NilError(c, err)
  56. defer cli.Close()
  57. _, err = cli.ContainerLogs(context.Background(), name, types.ContainerLogsOptions{})
  58. assert.ErrorContains(c, err, "Bad parameters: you must choose at least one stream")
  59. }
  60. // Regression test for #12704
  61. func (s *DockerSuite) TestLogsAPIFollowEmptyOutput(c *testing.T) {
  62. name := "logs_test"
  63. t0 := time.Now()
  64. dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "sleep", "10")
  65. _, body, err := request.Get(fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&stderr=1&tail=all", name))
  66. t1 := time.Now()
  67. assert.NilError(c, err)
  68. body.Close()
  69. elapsed := t1.Sub(t0).Seconds()
  70. if elapsed > 20.0 {
  71. c.Fatalf("HTTP response was not immediate (elapsed %.1fs)", elapsed)
  72. }
  73. }
  74. func (s *DockerSuite) TestLogsAPIContainerNotFound(c *testing.T) {
  75. name := "nonExistentContainer"
  76. resp, _, err := request.Get(fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&stderr=1&tail=all", name))
  77. assert.NilError(c, err)
  78. assert.Equal(c, resp.StatusCode, http.StatusNotFound)
  79. }
  80. func (s *DockerSuite) TestLogsAPIUntilFutureFollow(c *testing.T) {
  81. testRequires(c, DaemonIsLinux)
  82. name := "logsuntilfuturefollow"
  83. dockerCmd(c, "run", "-d", "--name", name, "busybox", "/bin/sh", "-c", "while true; do date +%s; sleep 1; done")
  84. assert.NilError(c, waitRun(name))
  85. untilSecs := 5
  86. untilDur, err := time.ParseDuration(fmt.Sprintf("%ds", untilSecs))
  87. assert.NilError(c, err)
  88. until := daemonTime(c).Add(untilDur)
  89. client, err := client.NewClientWithOpts(client.FromEnv)
  90. if err != nil {
  91. c.Fatal(err)
  92. }
  93. cfg := types.ContainerLogsOptions{Until: until.Format(time.RFC3339Nano), Follow: true, ShowStdout: true, Timestamps: true}
  94. reader, err := client.ContainerLogs(context.Background(), name, cfg)
  95. assert.NilError(c, err)
  96. type logOut struct {
  97. out string
  98. err error
  99. }
  100. chLog := make(chan logOut)
  101. go func() {
  102. bufReader := bufio.NewReader(reader)
  103. defer reader.Close()
  104. for i := 0; i < untilSecs; i++ {
  105. out, _, err := bufReader.ReadLine()
  106. if err != nil {
  107. if err == io.EOF {
  108. return
  109. }
  110. chLog <- logOut{"", err}
  111. return
  112. }
  113. chLog <- logOut{strings.TrimSpace(string(out)), err}
  114. }
  115. }()
  116. for i := 0; i < untilSecs; i++ {
  117. select {
  118. case l := <-chLog:
  119. assert.NilError(c, l.err)
  120. i, err := strconv.ParseInt(strings.Split(l.out, " ")[1], 10, 64)
  121. assert.NilError(c, err)
  122. assert.Assert(c, time.Unix(i, 0).UnixNano() <= until.UnixNano())
  123. case <-time.After(20 * time.Second):
  124. c.Fatal("timeout waiting for logs to exit")
  125. }
  126. }
  127. }
  128. func (s *DockerSuite) TestLogsAPIUntil(c *testing.T) {
  129. testRequires(c, MinimumAPIVersion("1.34"))
  130. name := "logsuntil"
  131. dockerCmd(c, "run", "--name", name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do echo log$i; sleep 1; done")
  132. client, err := client.NewClientWithOpts(client.FromEnv)
  133. if err != nil {
  134. c.Fatal(err)
  135. }
  136. extractBody := func(c *testing.T, cfg types.ContainerLogsOptions) []string {
  137. reader, err := client.ContainerLogs(context.Background(), name, cfg)
  138. assert.NilError(c, err)
  139. actualStdout := new(bytes.Buffer)
  140. actualStderr := ioutil.Discard
  141. _, err = stdcopy.StdCopy(actualStdout, actualStderr, reader)
  142. assert.NilError(c, err)
  143. return strings.Split(actualStdout.String(), "\n")
  144. }
  145. // Get timestamp of second log line
  146. allLogs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true})
  147. assert.Assert(c, len(allLogs) >= 3)
  148. t, err := time.Parse(time.RFC3339Nano, strings.Split(allLogs[1], " ")[0])
  149. assert.NilError(c, err)
  150. until := t.Format(time.RFC3339Nano)
  151. // Get logs until the timestamp of second line, i.e. first two lines
  152. logs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true, Until: until})
  153. // Ensure log lines after cut-off are excluded
  154. logsString := strings.Join(logs, "\n")
  155. assert.Assert(c, !strings.Contains(logsString, "log3"), "unexpected log message returned, until=%v", until)
  156. }
  157. func (s *DockerSuite) TestLogsAPIUntilDefaultValue(c *testing.T) {
  158. name := "logsuntildefaultval"
  159. dockerCmd(c, "run", "--name", name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do echo log$i; done")
  160. client, err := client.NewClientWithOpts(client.FromEnv)
  161. if err != nil {
  162. c.Fatal(err)
  163. }
  164. extractBody := func(c *testing.T, cfg types.ContainerLogsOptions) []string {
  165. reader, err := client.ContainerLogs(context.Background(), name, cfg)
  166. assert.NilError(c, err)
  167. actualStdout := new(bytes.Buffer)
  168. actualStderr := ioutil.Discard
  169. _, err = stdcopy.StdCopy(actualStdout, actualStderr, reader)
  170. assert.NilError(c, err)
  171. return strings.Split(actualStdout.String(), "\n")
  172. }
  173. // Get timestamp of second log line
  174. allLogs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true})
  175. // Test with default value specified and parameter omitted
  176. defaultLogs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true, Until: "0"})
  177. assert.DeepEqual(c, defaultLogs, allLogs)
  178. }