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