docker_cli_logs_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "os/exec"
  7. "regexp"
  8. "strings"
  9. "testing"
  10. "time"
  11. "github.com/containerd/log"
  12. "github.com/docker/docker/integration-cli/cli"
  13. "github.com/docker/docker/integration-cli/daemon"
  14. "github.com/docker/docker/testutil"
  15. testdaemon "github.com/docker/docker/testutil/daemon"
  16. "gotest.tools/v3/assert"
  17. "gotest.tools/v3/icmd"
  18. )
  19. type DockerCLILogsSuite struct {
  20. ds *DockerSuite
  21. }
  22. func (s *DockerCLILogsSuite) TearDownTest(ctx context.Context, c *testing.T) {
  23. s.ds.TearDownTest(ctx, c)
  24. }
  25. func (s *DockerCLILogsSuite) OnTimeout(c *testing.T) {
  26. s.ds.OnTimeout(c)
  27. }
  28. // This used to work, it test a log of PageSize-1 (gh#4851)
  29. func (s *DockerCLILogsSuite) TestLogsContainerSmallerThanPage(c *testing.T) {
  30. testLogsContainerPagination(c, 32767)
  31. }
  32. // Regression test: When going over the PageSize, it used to panic (gh#4851)
  33. func (s *DockerCLILogsSuite) TestLogsContainerBiggerThanPage(c *testing.T) {
  34. testLogsContainerPagination(c, 32768)
  35. }
  36. // Regression test: When going much over the PageSize, it used to block (gh#4851)
  37. func (s *DockerCLILogsSuite) TestLogsContainerMuchBiggerThanPage(c *testing.T) {
  38. testLogsContainerPagination(c, 33000)
  39. }
  40. func testLogsContainerPagination(c *testing.T, testLen int) {
  41. id := cli.DockerCmd(c, "run", "-d", "busybox", "sh", "-c", fmt.Sprintf("for i in $(seq 1 %d); do echo -n = >> a.a; done; echo >> a.a; cat a.a", testLen)).Stdout()
  42. id = strings.TrimSpace(id)
  43. cli.DockerCmd(c, "wait", id)
  44. out := cli.DockerCmd(c, "logs", id).Combined()
  45. assert.Equal(c, len(out), testLen+1)
  46. }
  47. func (s *DockerCLILogsSuite) TestLogsTimestamps(c *testing.T) {
  48. testLen := 100
  49. id := cli.DockerCmd(c, "run", "-d", "busybox", "sh", "-c", fmt.Sprintf("for i in $(seq 1 %d); do echo = >> a.a; done; cat a.a", testLen)).Stdout()
  50. id = strings.TrimSpace(id)
  51. cli.DockerCmd(c, "wait", id)
  52. out := cli.DockerCmd(c, "logs", "-t", id).Combined()
  53. lines := strings.Split(out, "\n")
  54. assert.Equal(c, len(lines), testLen+1)
  55. ts := regexp.MustCompile(`^.* `)
  56. for _, l := range lines {
  57. if l != "" {
  58. _, err := time.Parse(log.RFC3339NanoFixed+" ", ts.FindString(l))
  59. assert.NilError(c, err, "Failed to parse timestamp from %v", l)
  60. // ensure we have padded 0's
  61. assert.Equal(c, l[29], uint8('Z'))
  62. }
  63. }
  64. }
  65. func (s *DockerCLILogsSuite) TestLogsSeparateStderr(c *testing.T) {
  66. msg := "stderr_log"
  67. out := cli.DockerCmd(c, "run", "-d", "busybox", "sh", "-c", fmt.Sprintf("echo %s 1>&2", msg)).Combined()
  68. id := strings.TrimSpace(out)
  69. cli.DockerCmd(c, "wait", id)
  70. cli.DockerCmd(c, "logs", id).Assert(c, icmd.Expected{
  71. Out: "",
  72. Err: msg,
  73. })
  74. }
  75. func (s *DockerCLILogsSuite) TestLogsStderrInStdout(c *testing.T) {
  76. // TODO Windows: Needs investigation why this fails. Obtained string includes
  77. // a bunch of ANSI escape sequences before the "stderr_log" message.
  78. testRequires(c, DaemonIsLinux)
  79. msg := "stderr_log"
  80. out := cli.DockerCmd(c, "run", "-d", "-t", "busybox", "sh", "-c", fmt.Sprintf("echo %s 1>&2", msg)).Combined()
  81. id := strings.TrimSpace(out)
  82. cli.DockerCmd(c, "wait", id)
  83. cli.DockerCmd(c, "logs", id).Assert(c, icmd.Expected{
  84. Out: msg,
  85. Err: "",
  86. })
  87. }
  88. func (s *DockerCLILogsSuite) TestLogsTail(c *testing.T) {
  89. testLen := 100
  90. out := cli.DockerCmd(c, "run", "-d", "busybox", "sh", "-c", fmt.Sprintf("for i in $(seq 1 %d); do echo =; done;", testLen)).Combined()
  91. id := strings.TrimSpace(out)
  92. cli.DockerCmd(c, "wait", id)
  93. out = cli.DockerCmd(c, "logs", "--tail", "0", id).Combined()
  94. lines := strings.Split(out, "\n")
  95. assert.Equal(c, len(lines), 1)
  96. out = cli.DockerCmd(c, "logs", "--tail", "5", id).Combined()
  97. lines = strings.Split(out, "\n")
  98. assert.Equal(c, len(lines), 6)
  99. out = cli.DockerCmd(c, "logs", "--tail", "99", id).Combined()
  100. lines = strings.Split(out, "\n")
  101. assert.Equal(c, len(lines), 100)
  102. out = cli.DockerCmd(c, "logs", "--tail", "all", id).Combined()
  103. lines = strings.Split(out, "\n")
  104. assert.Equal(c, len(lines), testLen+1)
  105. out = cli.DockerCmd(c, "logs", "--tail", "-1", id).Combined()
  106. lines = strings.Split(out, "\n")
  107. assert.Equal(c, len(lines), testLen+1)
  108. out = cli.DockerCmd(c, "logs", "--tail", "random", id).Combined()
  109. lines = strings.Split(out, "\n")
  110. assert.Equal(c, len(lines), testLen+1)
  111. }
  112. func (s *DockerCLILogsSuite) TestLogsFollowStopped(c *testing.T) {
  113. cli.DockerCmd(c, "run", "--name=test", "busybox", "echo", "hello")
  114. id := getIDByName(c, "test")
  115. logsCmd := exec.Command(dockerBinary, "logs", "-f", id)
  116. assert.NilError(c, logsCmd.Start())
  117. errChan := make(chan error, 1)
  118. go func() {
  119. errChan <- logsCmd.Wait()
  120. close(errChan)
  121. }()
  122. select {
  123. case err := <-errChan:
  124. assert.NilError(c, err)
  125. case <-time.After(30 * time.Second):
  126. c.Fatal("Following logs is hanged")
  127. }
  128. }
  129. func (s *DockerCLILogsSuite) TestLogsSince(c *testing.T) {
  130. name := "testlogssince"
  131. cli.DockerCmd(c, "run", "--name="+name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do sleep 2; echo log$i; done")
  132. out := cli.DockerCmd(c, "logs", "-t", name).Combined()
  133. log2Line := strings.Split(strings.Split(out, "\n")[1], " ")
  134. t, err := time.Parse(time.RFC3339Nano, log2Line[0]) // the timestamp log2 is written
  135. assert.NilError(c, err)
  136. since := t.Unix() + 1 // add 1s so log1 & log2 doesn't show up
  137. out = cli.DockerCmd(c, "logs", "-t", fmt.Sprintf("--since=%v", since), name).Combined()
  138. // Skip 2 seconds
  139. unexpected := []string{"log1", "log2"}
  140. for _, v := range unexpected {
  141. assert.Check(c, !strings.Contains(out, v), "unexpected log message returned, since=%v", since)
  142. }
  143. // Test to make sure a bad since format is caught by the client
  144. out, _, _ = dockerCmdWithError("logs", "-t", "--since=2006-01-02T15:04:0Z", name)
  145. assert.Assert(c, strings.Contains(out, `cannot parse "0Z" as "05"`), "bad since format passed to server")
  146. // Test with default value specified and parameter omitted
  147. expected := []string{"log1", "log2", "log3"}
  148. for _, cmd := range [][]string{
  149. {"logs", "-t", name},
  150. {"logs", "-t", "--since=0", name},
  151. } {
  152. result := icmd.RunCommand(dockerBinary, cmd...)
  153. result.Assert(c, icmd.Success)
  154. for _, v := range expected {
  155. assert.Check(c, strings.Contains(result.Combined(), v))
  156. }
  157. }
  158. }
  159. func (s *DockerCLILogsSuite) TestLogsSinceFutureFollow(c *testing.T) {
  160. // TODO Windows TP5 - Figure out why this test is so flakey. Disabled for now.
  161. testRequires(c, DaemonIsLinux)
  162. name := "testlogssincefuturefollow"
  163. cli.DockerCmd(c, "run", "-d", "--name", name, "busybox", "/bin/sh", "-c", `for i in $(seq 1 5); do echo log$i; sleep 1; done`)
  164. // Extract one timestamp from the log file to give us a starting point for
  165. // our `--since` argument. Because the log producer runs in the background,
  166. // we need to check repeatedly for some output to be produced.
  167. var timestamp string
  168. for i := 0; i != 100 && timestamp == ""; i++ {
  169. if out := cli.DockerCmd(c, "logs", "-t", name).Combined(); out == "" {
  170. time.Sleep(time.Millisecond * 100) // Retry
  171. } else {
  172. timestamp = strings.Split(strings.Split(out, "\n")[0], " ")[0]
  173. }
  174. }
  175. assert.Assert(c, timestamp != "")
  176. t, err := time.Parse(time.RFC3339Nano, timestamp)
  177. assert.NilError(c, err)
  178. since := t.Unix() + 2
  179. out := cli.DockerCmd(c, "logs", "-t", "-f", fmt.Sprintf("--since=%v", since), name).Combined()
  180. assert.Assert(c, len(out) != 0, "cannot read from empty log")
  181. lines := strings.Split(strings.TrimSpace(out), "\n")
  182. for _, v := range lines {
  183. ts, err := time.Parse(time.RFC3339Nano, strings.Split(v, " ")[0])
  184. assert.NilError(c, err, "cannot parse timestamp output from log: '%v'", v)
  185. assert.Assert(c, ts.Unix() >= since, "earlier log found. since=%v logdate=%v", since, ts)
  186. }
  187. }
  188. // Regression test for #8832
  189. func (s *DockerCLILogsSuite) TestLogsFollowSlowStdoutConsumer(c *testing.T) {
  190. // TODO Windows: Fix this test for TP5.
  191. testRequires(c, DaemonIsLinux)
  192. expected := 150000
  193. id := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", fmt.Sprintf("usleep 600000; yes X | head -c %d", expected)).Stdout()
  194. id = strings.TrimSpace(id)
  195. stopSlowRead := make(chan bool)
  196. go func() {
  197. cli.DockerCmd(c, "wait", id)
  198. stopSlowRead <- true
  199. }()
  200. logCmd := exec.Command(dockerBinary, "logs", "-f", id)
  201. stdout, err := logCmd.StdoutPipe()
  202. assert.NilError(c, err)
  203. assert.NilError(c, logCmd.Start())
  204. defer func() { go logCmd.Wait() }()
  205. // First read slowly
  206. bytes1, err := ConsumeWithSpeed(stdout, 10, 50*time.Millisecond, stopSlowRead)
  207. assert.NilError(c, err)
  208. // After the container has finished we can continue reading fast
  209. bytes2, err := ConsumeWithSpeed(stdout, 32*1024, 0, nil)
  210. assert.NilError(c, err)
  211. assert.NilError(c, logCmd.Wait())
  212. actual := bytes1 + bytes2
  213. assert.Equal(c, actual, expected)
  214. }
  215. // ConsumeWithSpeed reads chunkSize bytes from reader before sleeping
  216. // for interval duration. Returns total read bytes. Send true to the
  217. // stop channel to return before reading to EOF on the reader.
  218. func ConsumeWithSpeed(reader io.Reader, chunkSize int, interval time.Duration, stop chan bool) (n int, err error) {
  219. buffer := make([]byte, chunkSize)
  220. for {
  221. var readBytes int
  222. readBytes, err = reader.Read(buffer)
  223. n += readBytes
  224. if err != nil {
  225. if err == io.EOF {
  226. err = nil
  227. }
  228. return
  229. }
  230. select {
  231. case <-stop:
  232. return
  233. case <-time.After(interval):
  234. }
  235. }
  236. }
  237. func (s *DockerCLILogsSuite) TestLogsFollowGoroutinesWithStdout(c *testing.T) {
  238. testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  239. c.Parallel()
  240. ctx := testutil.GetContext(c)
  241. d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvVars("OTEL_SDK_DISABLED=1"))
  242. defer func() {
  243. d.Stop(c)
  244. d.Cleanup(c)
  245. }()
  246. d.StartWithBusybox(ctx, c, "--iptables=false")
  247. out, err := d.Cmd("run", "-d", "busybox", "/bin/sh", "-c", "while true; do echo hello; sleep 2; done")
  248. assert.NilError(c, err)
  249. id := strings.TrimSpace(out)
  250. assert.NilError(c, d.WaitRun(id))
  251. client := d.NewClientT(c)
  252. nroutines := waitForStableGourtineCount(ctx, c, client)
  253. cmd := d.Command("logs", "-f", id)
  254. r, w := io.Pipe()
  255. defer r.Close()
  256. defer w.Close()
  257. cmd.Stdout = w
  258. res := icmd.StartCmd(cmd)
  259. assert.NilError(c, res.Error)
  260. defer res.Cmd.Process.Kill()
  261. finished := make(chan error)
  262. go func() {
  263. finished <- res.Cmd.Wait()
  264. }()
  265. // Make sure pipe is written to
  266. chErr := make(chan error)
  267. go func() {
  268. b := make([]byte, 1)
  269. _, err := r.Read(b)
  270. chErr <- err
  271. r.Close()
  272. }()
  273. // Check read from pipe succeeded
  274. assert.NilError(c, <-chErr)
  275. assert.NilError(c, res.Cmd.Process.Kill())
  276. <-finished
  277. // NGoroutines is not updated right away, so we need to wait before failing
  278. waitForGoroutines(ctx, c, client, nroutines)
  279. }
  280. func (s *DockerCLILogsSuite) TestLogsFollowGoroutinesNoOutput(c *testing.T) {
  281. testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  282. c.Parallel()
  283. d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvVars("OTEL_SDK_DISABLED=1"))
  284. defer func() {
  285. d.Stop(c)
  286. d.Cleanup(c)
  287. }()
  288. ctx := testutil.GetContext(c)
  289. d.StartWithBusybox(ctx, c, "--iptables=false")
  290. out, err := d.Cmd("run", "-d", "busybox", "/bin/sh", "-c", "while true; do sleep 2; done")
  291. assert.NilError(c, err)
  292. id := strings.TrimSpace(out)
  293. assert.NilError(c, d.WaitRun(id))
  294. client := d.NewClientT(c)
  295. nroutines := waitForStableGourtineCount(ctx, c, client)
  296. assert.NilError(c, err)
  297. cmd := d.Command("logs", "-f", id)
  298. res := icmd.StartCmd(cmd)
  299. assert.NilError(c, res.Error)
  300. finished := make(chan error)
  301. go func() {
  302. finished <- res.Cmd.Wait()
  303. }()
  304. time.Sleep(200 * time.Millisecond)
  305. assert.NilError(c, res.Cmd.Process.Kill())
  306. <-finished
  307. // NGoroutines is not updated right away, so we need to wait before failing
  308. waitForGoroutines(ctx, c, client, nroutines)
  309. }
  310. func (s *DockerCLILogsSuite) TestLogsCLIContainerNotFound(c *testing.T) {
  311. name := "testlogsnocontainer"
  312. out, _, _ := dockerCmdWithError("logs", name)
  313. message := fmt.Sprintf("No such container: %s\n", name)
  314. assert.Assert(c, strings.Contains(out, message))
  315. }
  316. func (s *DockerCLILogsSuite) TestLogsWithDetails(c *testing.T) {
  317. cli.DockerCmd(c, "run", "--name=test", "--label", "foo=bar", "-e", "baz=qux", "--log-opt", "labels=foo", "--log-opt", "env=baz", "busybox", "echo", "hello")
  318. out := cli.DockerCmd(c, "logs", "--details", "--timestamps", "test").Combined()
  319. logFields := strings.Fields(strings.TrimSpace(out))
  320. assert.Equal(c, len(logFields), 3, out)
  321. details := strings.Split(logFields[1], ",")
  322. assert.Equal(c, len(details), 2)
  323. assert.Equal(c, details[0], "baz=qux")
  324. assert.Equal(c, details[1], "foo=bar")
  325. }