github.com/lazyboychen7/engine@v17.12.1-ce-rc2+incompatible/integration-cli/docker_api_logs_test.go (about)

     1  package main
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"fmt"
     7  	"io"
     8  	"io/ioutil"
     9  	"net/http"
    10  	"strconv"
    11  	"strings"
    12  	"time"
    13  
    14  	"github.com/docker/docker/api/types"
    15  	"github.com/docker/docker/client"
    16  	"github.com/docker/docker/integration-cli/checker"
    17  	"github.com/docker/docker/integration-cli/request"
    18  	"github.com/docker/docker/pkg/stdcopy"
    19  	"github.com/go-check/check"
    20  	"golang.org/x/net/context"
    21  )
    22  
    23  func (s *DockerSuite) TestLogsAPIWithStdout(c *check.C) {
    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  	c.Assert(waitRun(id), checker.IsNil)
    27  
    28  	type logOut struct {
    29  		out string
    30  		err error
    31  	}
    32  
    33  	chLog := make(chan logOut)
    34  	res, body, err := request.Get(fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&timestamps=1", id))
    35  	c.Assert(err, checker.IsNil)
    36  	c.Assert(res.StatusCode, checker.Equals, 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  		c.Assert(l.err, checker.IsNil)
    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 *check.C) {
    60  	name := "logs_test"
    61  	dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh")
    62  	cli, err := client.NewEnvClient()
    63  	c.Assert(err, checker.IsNil)
    64  	defer cli.Close()
    65  
    66  	_, err = cli.ContainerLogs(context.Background(), name, types.ContainerLogsOptions{})
    67  	expected := "Bad parameters: you must choose at least one stream"
    68  	c.Assert(err.Error(), checker.Contains, expected)
    69  }
    70  
    71  // Regression test for #12704
    72  func (s *DockerSuite) TestLogsAPIFollowEmptyOutput(c *check.C) {
    73  	name := "logs_test"
    74  	t0 := time.Now()
    75  	dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "sleep", "10")
    76  
    77  	_, body, err := request.Get(fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&stderr=1&tail=all", name))
    78  	t1 := time.Now()
    79  	c.Assert(err, checker.IsNil)
    80  	body.Close()
    81  	elapsed := t1.Sub(t0).Seconds()
    82  	if elapsed > 20.0 {
    83  		c.Fatalf("HTTP response was not immediate (elapsed %.1fs)", elapsed)
    84  	}
    85  }
    86  
    87  func (s *DockerSuite) TestLogsAPIContainerNotFound(c *check.C) {
    88  	name := "nonExistentContainer"
    89  	resp, _, err := request.Get(fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&stderr=1&tail=all", name))
    90  	c.Assert(err, checker.IsNil)
    91  	c.Assert(resp.StatusCode, checker.Equals, http.StatusNotFound)
    92  }
    93  
    94  func (s *DockerSuite) TestLogsAPIUntilFutureFollow(c *check.C) {
    95  	testRequires(c, DaemonIsLinux)
    96  
    97  	name := "logsuntilfuturefollow"
    98  	dockerCmd(c, "run", "-d", "--name", name, "busybox", "/bin/sh", "-c", "while true; do date +%s; sleep 1; done")
    99  	c.Assert(waitRun(name), checker.IsNil)
   100  
   101  	untilSecs := 5
   102  	untilDur, err := time.ParseDuration(fmt.Sprintf("%ds", untilSecs))
   103  	c.Assert(err, checker.IsNil)
   104  	until := daemonTime(c).Add(untilDur)
   105  
   106  	client, err := request.NewClient()
   107  	if err != nil {
   108  		c.Fatal(err)
   109  	}
   110  
   111  	cfg := types.ContainerLogsOptions{Until: until.Format(time.RFC3339Nano), Follow: true, ShowStdout: true, Timestamps: true}
   112  	reader, err := client.ContainerLogs(context.Background(), name, cfg)
   113  	c.Assert(err, checker.IsNil)
   114  
   115  	type logOut struct {
   116  		out string
   117  		err error
   118  	}
   119  
   120  	chLog := make(chan logOut)
   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  				chLog <- logOut{"", err}
   132  				return
   133  			}
   134  
   135  			chLog <- logOut{strings.TrimSpace(string(out)), err}
   136  		}
   137  	}()
   138  
   139  	for i := 0; i < untilSecs; i++ {
   140  		select {
   141  		case l := <-chLog:
   142  			c.Assert(l.err, checker.IsNil)
   143  			i, err := strconv.ParseInt(strings.Split(l.out, " ")[1], 10, 64)
   144  			c.Assert(err, checker.IsNil)
   145  			c.Assert(time.Unix(i, 0).UnixNano(), checker.LessOrEqualThan, until.UnixNano())
   146  		case <-time.After(20 * time.Second):
   147  			c.Fatal("timeout waiting for logs to exit")
   148  		}
   149  	}
   150  }
   151  
   152  func (s *DockerSuite) TestLogsAPIUntil(c *check.C) {
   153  	name := "logsuntil"
   154  	dockerCmd(c, "run", "--name", name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do echo log$i; sleep 0.5; done")
   155  
   156  	client, err := request.NewClient()
   157  	if err != nil {
   158  		c.Fatal(err)
   159  	}
   160  
   161  	extractBody := func(c *check.C, cfg types.ContainerLogsOptions) []string {
   162  		reader, err := client.ContainerLogs(context.Background(), name, cfg)
   163  		c.Assert(err, checker.IsNil)
   164  
   165  		actualStdout := new(bytes.Buffer)
   166  		actualStderr := ioutil.Discard
   167  		_, err = stdcopy.StdCopy(actualStdout, actualStderr, reader)
   168  		c.Assert(err, checker.IsNil)
   169  
   170  		return strings.Split(actualStdout.String(), "\n")
   171  	}
   172  
   173  	// Get timestamp of second log line
   174  	allLogs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true})
   175  	t, err := time.Parse(time.RFC3339Nano, strings.Split(allLogs[1], " ")[0])
   176  	c.Assert(err, checker.IsNil)
   177  	until := t.Format(time.RFC3339Nano)
   178  
   179  	// Get logs until the timestamp of second line, i.e. first two lines
   180  	logs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true, Until: until})
   181  
   182  	// Ensure log lines after cut-off are excluded
   183  	logsString := strings.Join(logs, "\n")
   184  	c.Assert(logsString, checker.Not(checker.Contains), "log3", check.Commentf("unexpected log message returned, until=%v", until))
   185  }
   186  
   187  func (s *DockerSuite) TestLogsAPIUntilDefaultValue(c *check.C) {
   188  	name := "logsuntildefaultval"
   189  	dockerCmd(c, "run", "--name", name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do echo log$i; done")
   190  
   191  	client, err := request.NewClient()
   192  	if err != nil {
   193  		c.Fatal(err)
   194  	}
   195  
   196  	extractBody := func(c *check.C, cfg types.ContainerLogsOptions) []string {
   197  		reader, err := client.ContainerLogs(context.Background(), name, cfg)
   198  		c.Assert(err, checker.IsNil)
   199  
   200  		actualStdout := new(bytes.Buffer)
   201  		actualStderr := ioutil.Discard
   202  		_, err = stdcopy.StdCopy(actualStdout, actualStderr, reader)
   203  		c.Assert(err, checker.IsNil)
   204  
   205  		return strings.Split(actualStdout.String(), "\n")
   206  	}
   207  
   208  	// Get timestamp of second log line
   209  	allLogs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true})
   210  
   211  	// Test with default value specified and parameter omitted
   212  	defaultLogs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true, Until: "0"})
   213  	c.Assert(defaultLogs, checker.DeepEquals, allLogs)
   214  }