Compare commits

...

13 Commits

Author SHA1 Message Date
Laura Brehm 1bd8fd83ce
Merge f632123c41 into da9e984231 2024-10-18 10:43:46 +01:00
Sebastiaan van Stijn da9e984231
Merge pull request #5541 from thaJeztah/template_coverage
templates: add test for HeaderFunctions
2024-10-18 11:42:00 +02:00
Paweł Gronowski 38653277af
Merge pull request #5539 from thaJeztah/bump_swarmkit
vendor: github.com/moby/swarmkit/v2 v2.0.0-20241017191044-e8ecf83ee08e
2024-10-18 10:44:41 +02:00
Sebastiaan van Stijn 12dcc6e25c
templates: add test for HeaderFunctions
Before:

    go test -test.coverprofile -
    PASS
    coverage: 65.2% of statements
    ok  	github.com/docker/cli/templates	0.607s

After:

    go test -test.coverprofile -
    PASS
    coverage: 95.7% of statements
    ok  	github.com/docker/cli/templates	0.259s

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-18 10:07:33 +02:00
Sebastiaan van Stijn cbbb917323
vendor: github.com/moby/swarmkit/v2 v2.0.0-20241017191044-e8ecf83ee08e
- add Unwrap error to custom error types
- removes dependency on github.com/rexray/gocsi
- fix CSI plugin load issue

full diff: ea1a7cec35...e8ecf83ee0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-17 23:01:19 +02:00
Paweł Gronowski 3590f946a3
Merge pull request #5535 from dvdksn/fix-image-tag-spec
docs: update prose about image tag/name format
2024-10-17 12:46:46 +02:00
David Karlsson 2c6b80491b docs: update prose about image tag/name format
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-10-17 12:36:32 +02:00
Paweł Gronowski 09e16fc9c6
Merge pull request #5537 from dvdksn/correct_events_limit
docs: corrected the max events returned
2024-10-17 11:26:09 +02:00
Laura Brehm dba4b15d6b
Merge pull request #5534 from thaJeztah/container_testfixes 2024-10-16 22:08:22 +01:00
David Karlsson 50ef0c58c2 docs: corrected the max events returned
Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
2024-10-16 12:21:51 +02:00
Sebastiaan van Stijn 35d7b1a7a6
cli/command/container: TestWaitExitOrRemoved use subtests
=== RUN   TestWaitExitOrRemoved
    === RUN   TestWaitExitOrRemoved/normal-container
    === RUN   TestWaitExitOrRemoved/give-me-exit-code-42
    === RUN   TestWaitExitOrRemoved/i-want-a-wait-error
    time="2024-10-13T18:48:14+02:00" level=error msg="Error waiting for container: removal failed"
    === RUN   TestWaitExitOrRemoved/non-existent-container-id
    time="2024-10-13T18:48:14+02:00" level=error msg="error waiting for container: no such container: non-existent-container-id"
    --- PASS: TestWaitExitOrRemoved (0.00s)
        --- PASS: TestWaitExitOrRemoved/normal-container (0.00s)
        --- PASS: TestWaitExitOrRemoved/give-me-exit-code-42 (0.00s)
        --- PASS: TestWaitExitOrRemoved/i-want-a-wait-error (0.00s)
        --- PASS: TestWaitExitOrRemoved/non-existent-container-id (0.00s)
    PASS

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-16 12:03:17 +02:00
Sebastiaan van Stijn 3b38dc67be
cli/command/container: set empty args in tests and discard output
Prevent some tests from failing when running from a pre-compiled
testbinary, and discard output to make the output less noisy.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-10-16 12:01:25 +02:00
Laura Brehm f632123c41
WIP: add configurable detach delay to logs
Signed-off-by: Laura Brehm <laurabrehm@hey.com>
2024-07-30 15:01:19 +01:00
13 changed files with 225 additions and 41 deletions

View File

@ -127,7 +127,6 @@ func TestContainerListBuildContainerListOptions(t *testing.T) {
func TestContainerListErrors(t *testing.T) {
testCases := []struct {
args []string
flags map[string]string
containerListFunc func(container.ListOptions) ([]container.Summary, error)
expectedError string
@ -157,10 +156,10 @@ func TestContainerListErrors(t *testing.T) {
containerListFunc: tc.containerListFunc,
}),
)
cmd.SetArgs(tc.args)
for key, value := range tc.flags {
assert.Check(t, cmd.Flags().Set(key, value))
}
cmd.SetArgs([]string{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
@ -180,6 +179,9 @@ func TestContainerListWithoutFormat(t *testing.T) {
},
})
cmd := newListCommand(cli)
cmd.SetArgs([]string{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
assert.NilError(t, cmd.Execute())
golden.Assert(t, cli.OutBuffer().String(), "container-list-without-format.golden")
}
@ -194,6 +196,9 @@ func TestContainerListNoTrunc(t *testing.T) {
},
})
cmd := newListCommand(cli)
cmd.SetArgs([]string{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
assert.Check(t, cmd.Flags().Set("no-trunc", "true"))
assert.NilError(t, cmd.Execute())
golden.Assert(t, cli.OutBuffer().String(), "container-list-without-format-no-trunc.golden")
@ -210,6 +215,9 @@ func TestContainerListNamesMultipleTime(t *testing.T) {
},
})
cmd := newListCommand(cli)
cmd.SetArgs([]string{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
assert.Check(t, cmd.Flags().Set("format", "{{.Names}} {{.Names}}"))
assert.NilError(t, cmd.Execute())
golden.Assert(t, cli.OutBuffer().String(), "container-list-format-name-name.golden")
@ -226,6 +234,9 @@ func TestContainerListFormatTemplateWithArg(t *testing.T) {
},
})
cmd := newListCommand(cli)
cmd.SetArgs([]string{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
assert.Check(t, cmd.Flags().Set("format", `{{.Names}} {{.Label "some.label"}}`))
assert.NilError(t, cmd.Execute())
golden.Assert(t, cli.OutBuffer().String(), "container-list-format-with-arg.golden")
@ -275,6 +286,9 @@ func TestContainerListFormatSizeSetsOption(t *testing.T) {
},
})
cmd := newListCommand(cli)
cmd.SetArgs([]string{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
assert.Check(t, cmd.Flags().Set("format", tc.format))
if tc.sizeFlag != "" {
assert.Check(t, cmd.Flags().Set("size", tc.sizeFlag))
@ -297,6 +311,9 @@ func TestContainerListWithConfigFormat(t *testing.T) {
PsFormat: "{{ .Names }} {{ .Image }} {{ .Labels }} {{ .Size}}",
})
cmd := newListCommand(cli)
cmd.SetArgs([]string{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
assert.NilError(t, cmd.Execute())
golden.Assert(t, cli.OutBuffer().String(), "container-list-with-config-format.golden")
}
@ -314,6 +331,9 @@ func TestContainerListWithFormat(t *testing.T) {
t.Run("with format", func(t *testing.T) {
cli.OutBuffer().Reset()
cmd := newListCommand(cli)
cmd.SetArgs([]string{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
assert.Check(t, cmd.Flags().Set("format", "{{ .Names }} {{ .Image }} {{ .Labels }}"))
assert.NilError(t, cmd.Execute())
golden.Assert(t, cli.OutBuffer().String(), "container-list-with-format.golden")
@ -322,6 +342,9 @@ func TestContainerListWithFormat(t *testing.T) {
t.Run("with format and quiet", func(t *testing.T) {
cli.OutBuffer().Reset()
cmd := newListCommand(cli)
cmd.SetArgs([]string{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
assert.Check(t, cmd.Flags().Set("format", "{{ .Names }} {{ .Image }} {{ .Labels }}"))
assert.Check(t, cmd.Flags().Set("quiet", "true"))
assert.NilError(t, cmd.Execute())

View File

@ -3,11 +3,14 @@ package container
import (
"context"
"io"
"strconv"
"time"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/events"
"github.com/docker/docker/pkg/stdcopy"
"github.com/spf13/cobra"
)
@ -20,6 +23,8 @@ type logsOptions struct {
details bool
tail string
detachDelay int
container string
}
@ -49,6 +54,7 @@ func NewLogsCommand(dockerCli command.Cli) *cobra.Command {
flags.BoolVarP(&opts.timestamps, "timestamps", "t", false, "Show timestamps")
flags.BoolVar(&opts.details, "details", false, "Show extra details provided to logs")
flags.StringVarP(&opts.tail, "tail", "n", "all", "Number of lines to show from the end of the logs")
flags.IntVarP(&opts.detachDelay, "delay", "d", 0, "Number of seconds to wait for container restart before exiting")
return cmd
}
@ -58,6 +64,45 @@ func runLogs(ctx context.Context, dockerCli command.Cli, opts *logsOptions) erro
return err
}
since := opts.since
for {
restarting := make(chan events.Message)
if opts.detachDelay != 0 {
go func() {
eventsCtx, eventsCtxCancel := context.WithCancel(ctx)
eventC, eventErrs := dockerCli.Client().Events(eventsCtx, events.ListOptions{})
defer eventsCtxCancel()
for {
select {
case event := <-eventC:
if event.Action == events.ActionRestart && event.Actor.ID == c.ID {
restarting <- event
return
}
case <-eventErrs:
return
}
}
}()
}
opts.since = since
err = streamLogs(ctx, dockerCli, opts, c)
if opts.detachDelay == 0 {
return err
}
select {
case restartEvent := <-restarting:
since = strconv.FormatInt(restartEvent.Time, 10)
case <-time.After(time.Duration(opts.detachDelay) * time.Second):
return err
}
}
}
func streamLogs(ctx context.Context, dockerCli command.Cli, opts *logsOptions, c container.InspectResponse) error {
responseBody, err := dockerCli.Client().ContainerLogs(ctx, c.ID, container.LogsOptions{
ShowStdout: true,
ShowStderr: true,
@ -78,5 +123,6 @@ func runLogs(ctx context.Context, dockerCli command.Cli, opts *logsOptions) erro
} else {
_, err = stdcopy.StdCopy(dockerCli.Out(), dockerCli.Err(), responseBody)
}
return err
}

View File

@ -21,6 +21,7 @@ func TestContainerPrunePromptTermination(t *testing.T) {
},
})
cmd := NewPruneCommand(cli)
cmd.SetArgs([]string{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
test.TerminatePrompt(ctx, t, cmd, cli)

View File

@ -38,7 +38,7 @@ func waitFn(cid string) (<-chan container.WaitResponse, <-chan error) {
}
func TestWaitExitOrRemoved(t *testing.T) {
testcases := []struct {
tests := []struct {
cid string
exitCode int
}{
@ -61,9 +61,11 @@ func TestWaitExitOrRemoved(t *testing.T) {
}
client := &fakeClient{waitFunc: waitFn, Version: api.DefaultVersion}
for _, testcase := range testcases {
statusC := waitExitOrRemoved(context.Background(), client, testcase.cid, true)
exitCode := <-statusC
assert.Check(t, is.Equal(testcase.exitCode, exitCode))
for _, tc := range tests {
t.Run(tc.cid, func(t *testing.T) {
statusC := waitExitOrRemoved(context.Background(), client, tc.cid, true)
exitCode := <-statusC
assert.Check(t, is.Equal(tc.exitCode, exitCode))
})
}
}

View File

@ -11,6 +11,7 @@ Fetch the logs of a container
| Name | Type | Default | Description |
|:---------------------|:---------|:--------|:---------------------------------------------------------------------------------------------------|
| `-d`, `--delay` | `int` | `0` | Number of seconds to wait for container restart before exiting |
| `--details` | `bool` | | Show extra details provided to logs |
| `-f`, `--follow` | `bool` | | Follow log output |
| `--since` | `string` | | Show logs since timestamp (e.g. `2013-01-02T13:23:37Z`) or relative (e.g. `42m` for 42 minutes) |

View File

@ -12,38 +12,50 @@ Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
## Description
A full image name has the following format and components:
A Docker image reference consists of several components that describe where the
image is stored and its identity. These components are:
`[HOST[:PORT_NUMBER]/]PATH`
```text
[HOST[:PORT]/]NAMESPACE/REPOSITORY[:TAG]
```
- `HOST`: The optional registry hostname specifies where the image is located.
The hostname must comply with standard DNS rules, but may not contain
underscores. If you don't specify a hostname, the command uses Docker's public
registry at `registry-1.docker.io` by default. Note that `docker.io` is the
canonical reference for Docker's public registry.
- `PORT_NUMBER`: If a hostname is present, it may optionally be followed by a
registry port number in the format `:8080`.
- `PATH`: The path consists of slash-separated components. Each
component may contain lowercase letters, digits and separators. A separator is
defined as a period, one or two underscores, or one or more hyphens. A component
may not start or end with a separator. While the
[OCI Distribution Specification](https://github.com/opencontainers/distribution-spec)
supports more than two slash-separated components, most registries only support
two slash-separated components. For Docker's public registry, the path format is
as follows:
- `[NAMESPACE/]REPOSITORY`: The first, optional component is typically a
user's or an organization's namespace. The second, mandatory component is the
repository name. When the namespace is not present, Docker uses `library`
as the default namespace.
`HOST`
: Specifies the registry location where the image resides. If omitted, Docker
defaults to Docker Hub (`docker.io`).
After the image name, the optional `TAG` is a custom, human-readable manifest
identifier that's typically a specific version or variant of an image. The tag
must be valid ASCII and can contain lowercase and uppercase letters, digits,
underscores, periods, and hyphens. It can't start with a period or hyphen and
must be no longer than 128 characters. If you don't specify a tag, the command uses `latest` by default.
`PORT`
: An optional port number for the registry, if necessary (for example, `:5000`).
You can group your images together using names and tags, and then
[push](image_push.md) them to a registry.
`NAMESPACE/REPOSITORY`
: The namespace (optional) usually represents a user or organization. The
repository is required and identifies the specific image. If the namespace is
omitted, Docker defaults to `library`, the namespace reserved for Docker
Official Images.
`TAG`
: An optional identifier used to specify a particular version or variant of the
image. If no tag is provided, Docker defaults to `latest`.
### Example image references
`example.com:5000/team/my-app:2.0`
- Host: `example.com`
- Port: `5000`
- Namespace: `team`
- Repository: `my-app`
- Tag: `2.0`
`alpine`
- Host: `docker.io` (default)
- Namespace: `library` (default)
- Repository: `alpine`
- Tag: `latest` (default)
For more information on the structure and rules of image naming, refer to the
[Distribution reference](https://pkg.go.dev/github.com/distribution/reference#pkg-overview)
as the canonical definition of the format.
## Examples

View File

@ -11,6 +11,7 @@ Fetch the logs of a container
| Name | Type | Default | Description |
|:---------------------|:---------|:--------|:---------------------------------------------------------------------------------------------------|
| `-d`, `--delay` | `int` | `0` | Number of seconds to wait for container restart before exiting |
| `--details` | `bool` | | Show extra details provided to logs |
| `-f`, `--follow` | `bool` | | Follow log output |
| `--since` | `string` | | Show logs since timestamp (e.g. `2013-01-02T13:23:37Z`) or relative (e.g. `42m` for 42 minutes) |

View File

@ -26,7 +26,7 @@ per Docker object type. Different event types have different scopes. Local
scoped events are only seen on the node they take place on, and Swarm scoped
events are seen on all managers.
Only the last 1000 log events are returned. You can use filters to further limit
Only the last 256 log events are returned. You can use filters to further limit
the number of events returned.
### Object types
@ -156,7 +156,7 @@ that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap
seconds (aka Unix epoch or Unix time), and the optional .nanoseconds field is a
fraction of a second no more than nine digits long.
Only the last 1000 log events are returned. You can use filters to further limit
Only the last 256 log events are returned. You can use filters to further limit
the number of events returned.
#### <a name="filter"></a> Filtering (--filter)

View File

@ -0,0 +1,46 @@
package container
import (
"strings"
"testing"
"time"
"github.com/docker/cli/e2e/internal/fixtures"
"gotest.tools/v3/icmd"
"gotest.tools/v3/poll"
)
func TestLogsReattach(t *testing.T) {
result := icmd.RunCommand("docker", "run", "-d", fixtures.AlpineImage,
"sh", "-c", "echo hi; while true; do sleep 1; done")
result.Assert(t, icmd.Success)
containerID := strings.TrimSpace(result.Stdout())
cmd := icmd.Command("docker", "logs", "-f", "-d", "5", containerID)
// cmd := icmd.Command("docker", "logs", containerID)
result = icmd.StartCmd(cmd)
poll.WaitOn(t, func(t poll.LogT) poll.Result {
if strings.Contains(result.Stdout(), "hi") {
return poll.Success()
}
return poll.Continue("waiting")
}, poll.WithDelay(1*time.Second), poll.WithTimeout(5*time.Second))
icmd.RunCommand("docker", "restart", containerID).Assert(t, icmd.Success)
poll.WaitOn(t, func(t poll.LogT) poll.Result {
// if there is another "hi" then the container was successfully restarted,
// printed "hi" again and `docker logs` stayed attached
if strings.Contains(result.Stdout(), "hi\nhi") { //nolint:dupword
return poll.Success()
}
return poll.Continue(result.Stdout())
}, poll.WithDelay(1*time.Second), poll.WithTimeout(10*time.Second))
icmd.RunCommand("docker", "stop", containerID).Assert(t, icmd.Success)
icmd.WaitOnCmd(time.Second*10, result).Assert(t, icmd.Expected{
ExitCode: 0,
})
}

View File

@ -89,3 +89,55 @@ func TestParseTruncateFunction(t *testing.T) {
})
}
}
func TestHeaderFunctions(t *testing.T) {
const source = "hello world"
tests := []struct {
doc string
template string
}{
{
doc: "json",
template: `{{ json .}}`,
},
{
doc: "split",
template: `{{ split . ","}}`,
},
{
doc: "join",
template: `{{ join . ","}}`,
},
{
doc: "title",
template: `{{ title .}}`,
},
{
doc: "lower",
template: `{{ lower .}}`,
},
{
doc: "upper",
template: `{{ upper .}}`,
},
{
doc: "truncate",
template: `{{ truncate . 2}}`,
},
}
for _, tc := range tests {
t.Run(tc.doc, func(t *testing.T) {
tmpl, err := New("").Funcs(HeaderFunctions).Parse(tc.template)
assert.NilError(t, err)
var b bytes.Buffer
assert.NilError(t, tmpl.Execute(&b, source))
// All header-functions are currently stubs, and don't modify the input.
expected := source
assert.Equal(t, expected, b.String())
})
}
}

View File

@ -25,7 +25,7 @@ require (
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510
github.com/mattn/go-runewidth v0.0.15
github.com/moby/patternmatcher v0.6.0
github.com/moby/swarmkit/v2 v2.0.0-20240611172349-ea1a7cec35cb
github.com/moby/swarmkit/v2 v2.0.0-20241017191044-e8ecf83ee08e
github.com/moby/sys/capability v0.3.0
github.com/moby/sys/sequential v0.6.0
github.com/moby/sys/signal v0.7.1

View File

@ -180,8 +180,8 @@ github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3N
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
github.com/moby/patternmatcher v0.6.0 h1:GmP9lR19aU5GqSSFko+5pRqHi+Ohk1O69aFiKkVGiPk=
github.com/moby/patternmatcher v0.6.0/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc=
github.com/moby/swarmkit/v2 v2.0.0-20240611172349-ea1a7cec35cb h1:1UTTg2EgO3nuyV03wREDzldqqePzQ4+0a5G1C1y1bIo=
github.com/moby/swarmkit/v2 v2.0.0-20240611172349-ea1a7cec35cb/go.mod h1:kNy225f/gWAnF8wPftteMc5nbAHhrH+HUfvyjmhFjeQ=
github.com/moby/swarmkit/v2 v2.0.0-20241017191044-e8ecf83ee08e h1:1yC8fRqStY6NirU/swI74fsrHvZVMbtxsHcvl8YpzDg=
github.com/moby/swarmkit/v2 v2.0.0-20241017191044-e8ecf83ee08e/go.mod h1:mTTGIAz/59OGZR5Qe+QByIe3Nxc+sSuJkrsStFhr6Lg=
github.com/moby/sys/capability v0.3.0 h1:kEP+y6te0gEXIaeQhIi0s7vKs/w0RPoH1qPa6jROcVg=
github.com/moby/sys/capability v0.3.0/go.mod h1:4g9IK291rVkms3LKCDOoYlnV8xKwoDTpIrNEE35Wq0I=
github.com/moby/sys/sequential v0.6.0 h1:qrx7XFUd/5DxtqcoH1h438hF5TmOvzC/lspjy7zgvCU=

2
vendor/modules.txt vendored
View File

@ -197,7 +197,7 @@ github.com/moby/docker-image-spec/specs-go/v1
## explicit; go 1.19
github.com/moby/patternmatcher
github.com/moby/patternmatcher/ignorefile
# github.com/moby/swarmkit/v2 v2.0.0-20240611172349-ea1a7cec35cb
# github.com/moby/swarmkit/v2 v2.0.0-20241017191044-e8ecf83ee08e
## explicit; go 1.18
github.com/moby/swarmkit/v2/api
github.com/moby/swarmkit/v2/api/deepcopy