github.com/lacework-dev/go-moby@v20.10.12+incompatible/integration-cli/docker_api_logs_test.go (about)

     1  package main
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"context"
     7  	"fmt"
     8  	"io"
     9  	"io/ioutil"
    10  	"net/http"
    11  	"strconv"
    12  	"strings"
    13  	"testing"
    14  	"time"
    15  
    16  	"github.com/docker/docker/api/types"
    17  	"github.com/docker/docker/client"
    18  	"github.com/docker/docker/pkg/stdcopy"
    19  	"github.com/docker/docker/testutil/request"
    20  	"gotest.tools/v3/assert"
    21  )
    22  
    23  func (s *DockerSuite) TestLogsAPIWithStdout(c *testing.T) {
    24  	out, _ := dockerCmd(c, "run", "-d", "-t", "busybox", "/bin/sh", "-c", "while true; do echo hello; sleep 1; done")
    25  	id := strings.TrimSpace(out)
    26  	assert.NilError(c, waitRun(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(fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&timestamps=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 *DockerSuite) TestLogsAPINoStdoutNorStderr(c *testing.T) {
    60  	name := "logs_test"
    61  	dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh")
    62  	cli, err := client.NewClientWithOpts(client.FromEnv)
    63  	assert.NilError(c, err)
    64  	defer cli.Close()
    65  
    66  	_, err = cli.ContainerLogs(context.Background(), name, types.ContainerLogsOptions{})
    67  	assert.ErrorContains(c, err, "Bad parameters: you must choose at least one stream")
    68  }
    69  
    70  // Regression test for #12704
    71  func (s *DockerSuite) TestLogsAPIFollowEmptyOutput(c *testing.T) {
    72  	name := "logs_test"
    73  	t0 := time.Now()
    74  	dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "sleep", "10")
    75  
    76  	_, body, err := request.Get(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 *DockerSuite) TestLogsAPIContainerNotFound(c *testing.T) {
    87  	name := "nonExistentContainer"
    88  	resp, _, err := request.Get(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 *DockerSuite) TestLogsAPIUntilFutureFollow(c *testing.T) {
    94  	testRequires(c, DaemonIsLinux)
    95  	name := "logsuntilfuturefollow"
    96  	dockerCmd(c, "run", "-d", "--name", name, "busybox", "/bin/sh", "-c", "while true; do date +%s; sleep 1; done")
    97  	assert.NilError(c, waitRun(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  	client, err := client.NewClientWithOpts(client.FromEnv)
   105  	if err != nil {
   106  		c.Fatal(err)
   107  	}
   108  
   109  	cfg := types.ContainerLogsOptions{Until: until.Format(time.RFC3339Nano), Follow: true, ShowStdout: true, Timestamps: true}
   110  	reader, err := client.ContainerLogs(context.Background(), name, cfg)
   111  	assert.NilError(c, err)
   112  
   113  	type logOut struct {
   114  		out string
   115  		err error
   116  	}
   117  
   118  	chLog := make(chan logOut)
   119  	stop := make(chan struct{})
   120  	defer close(stop)
   121  
   122  	go func() {
   123  		bufReader := bufio.NewReader(reader)
   124  		defer reader.Close()
   125  		for i := 0; i < untilSecs; i++ {
   126  			out, _, err := bufReader.ReadLine()
   127  			if err != nil {
   128  				if err == io.EOF {
   129  					return
   130  				}
   131  				select {
   132  				case <-stop:
   133  					return
   134  				case chLog <- logOut{"", err}:
   135  				}
   136  
   137  				return
   138  			}
   139  
   140  			select {
   141  			case <-stop:
   142  				return
   143  			case chLog <- logOut{strings.TrimSpace(string(out)), err}:
   144  			}
   145  		}
   146  	}()
   147  
   148  	for i := 0; i < untilSecs; i++ {
   149  		select {
   150  		case l := <-chLog:
   151  			assert.NilError(c, l.err)
   152  			i, err := strconv.ParseInt(strings.Split(l.out, " ")[1], 10, 64)
   153  			assert.NilError(c, err)
   154  			assert.Assert(c, time.Unix(i, 0).UnixNano() <= until.UnixNano())
   155  		case <-time.After(20 * time.Second):
   156  			c.Fatal("timeout waiting for logs to exit")
   157  		}
   158  	}
   159  }
   160  
   161  func (s *DockerSuite) TestLogsAPIUntil(c *testing.T) {
   162  	testRequires(c, MinimumAPIVersion("1.34"))
   163  	name := "logsuntil"
   164  	dockerCmd(c, "run", "--name", name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do echo log$i; sleep 1; done")
   165  
   166  	client, err := client.NewClientWithOpts(client.FromEnv)
   167  	if err != nil {
   168  		c.Fatal(err)
   169  	}
   170  
   171  	extractBody := func(c *testing.T, cfg types.ContainerLogsOptions) []string {
   172  		reader, err := client.ContainerLogs(context.Background(), name, cfg)
   173  		assert.NilError(c, err)
   174  
   175  		actualStdout := new(bytes.Buffer)
   176  		actualStderr := ioutil.Discard
   177  		_, err = stdcopy.StdCopy(actualStdout, actualStderr, reader)
   178  		assert.NilError(c, err)
   179  
   180  		return strings.Split(actualStdout.String(), "\n")
   181  	}
   182  
   183  	// Get timestamp of second log line
   184  	allLogs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true})
   185  	assert.Assert(c, len(allLogs) >= 3)
   186  
   187  	t, err := time.Parse(time.RFC3339Nano, strings.Split(allLogs[1], " ")[0])
   188  	assert.NilError(c, err)
   189  	until := t.Format(time.RFC3339Nano)
   190  
   191  	// Get logs until the timestamp of second line, i.e. first two lines
   192  	logs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true, Until: until})
   193  
   194  	// Ensure log lines after cut-off are excluded
   195  	logsString := strings.Join(logs, "\n")
   196  	assert.Assert(c, !strings.Contains(logsString, "log3"), "unexpected log message returned, until=%v", until)
   197  }
   198  
   199  func (s *DockerSuite) TestLogsAPIUntilDefaultValue(c *testing.T) {
   200  	name := "logsuntildefaultval"
   201  	dockerCmd(c, "run", "--name", name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do echo log$i; done")
   202  
   203  	client, err := client.NewClientWithOpts(client.FromEnv)
   204  	if err != nil {
   205  		c.Fatal(err)
   206  	}
   207  
   208  	extractBody := func(c *testing.T, cfg types.ContainerLogsOptions) []string {
   209  		reader, err := client.ContainerLogs(context.Background(), name, cfg)
   210  		assert.NilError(c, err)
   211  
   212  		actualStdout := new(bytes.Buffer)
   213  		actualStderr := ioutil.Discard
   214  		_, err = stdcopy.StdCopy(actualStdout, actualStderr, reader)
   215  		assert.NilError(c, err)
   216  
   217  		return strings.Split(actualStdout.String(), "\n")
   218  	}
   219  
   220  	// Get timestamp of second log line
   221  	allLogs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true})
   222  
   223  	// Test with default value specified and parameter omitted
   224  	defaultLogs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true, Until: "0"})
   225  	assert.DeepEqual(c, defaultLogs, allLogs)
   226  }