-
Notifications
You must be signed in to change notification settings - Fork 770
feat: add 'nerdctl container attach' #2108
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| /* | ||
| Copyright The containerd Authors. | ||
|
|
||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
| */ | ||
|
|
||
| package main | ||
|
|
||
| import ( | ||
| "github.com/containerd/containerd" | ||
| "github.com/containerd/nerdctl/pkg/api/types" | ||
| "github.com/containerd/nerdctl/pkg/clientutil" | ||
| "github.com/containerd/nerdctl/pkg/cmd/container" | ||
| "github.com/containerd/nerdctl/pkg/consoleutil" | ||
| "github.com/spf13/cobra" | ||
| ) | ||
|
|
||
| func newAttachCommand() *cobra.Command { | ||
| var attachCommand = &cobra.Command{ | ||
| Use: "attach [flags] CONTAINER", | ||
| Args: cobra.ExactArgs(1), | ||
| Short: `Attach stdin, stdout, and stderr to a running container. For example: | ||
|
|
||
| 1. 'nerdctl run -it --name test busybox' to start a container with a pty | ||
| 2. 'ctrl-p ctrl-q' to detach from the container | ||
| 3. 'nerdctl attach test' to attach to the container | ||
|
|
||
| Caveats: | ||
|
|
||
| - Currently only one attach session is allowed. When the second session tries to attach, currently no error will be returned from nerdctl. | ||
| However, since behind the scenes, there's only one FIFO for stdin, stdout, and stderr respectively, | ||
| if there are multiple sessions, all the sessions will be reading from and writing to the same 3 FIFOs, which will result in mixed input and partial output. | ||
| - Until dual logging (issue #1946) is implemented, | ||
| a container that is spun up by either 'nerdctl run -d' or 'nerdctl start' (without '--attach') cannot be attached to.`, | ||
| RunE: containerAttachAction, | ||
| ValidArgsFunction: attachShellComplete, | ||
| SilenceUsage: true, | ||
| SilenceErrors: true, | ||
| } | ||
| attachCommand.Flags().String("detach-keys", consoleutil.DefaultDetachKeys, "Override the default detach keys") | ||
| return attachCommand | ||
| } | ||
|
|
||
| func processContainerAttachOptions(cmd *cobra.Command) (types.ContainerAttachOptions, error) { | ||
| globalOptions, err := processRootCmdFlags(cmd) | ||
| if err != nil { | ||
| return types.ContainerAttachOptions{}, err | ||
| } | ||
| detachKeys, err := cmd.Flags().GetString("detach-keys") | ||
| if err != nil { | ||
| return types.ContainerAttachOptions{}, err | ||
| } | ||
| return types.ContainerAttachOptions{ | ||
| GOptions: globalOptions, | ||
| Stdin: cmd.InOrStdin(), | ||
| Stdout: cmd.OutOrStdout(), | ||
| Stderr: cmd.ErrOrStderr(), | ||
| DetachKeys: detachKeys, | ||
| }, nil | ||
| } | ||
|
|
||
| func containerAttachAction(cmd *cobra.Command, args []string) error { | ||
| options, err := processContainerAttachOptions(cmd) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| client, ctx, cancel, err := clientutil.NewClient(cmd.Context(), options.GOptions.Namespace, options.GOptions.Address) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| defer cancel() | ||
|
|
||
| return container.Attach(ctx, client, args[0], options) | ||
| } | ||
|
|
||
| func attachShellComplete(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { | ||
| statusFilterFn := func(st containerd.ProcessStatus) bool { | ||
| return st == containerd.Running | ||
| } | ||
| return shellCompleteContainerNames(cmd, statusFilterFn) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| /* | ||
| Copyright The containerd Authors. | ||
|
|
||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
| */ | ||
|
|
||
| package main | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/containerd/nerdctl/pkg/testutil" | ||
| "gotest.tools/v3/assert" | ||
| ) | ||
|
|
||
| // skipAttachForDocker should be called by attach-related tests that assert 'read detach keys' in stdout. | ||
| func skipAttachForDocker(t *testing.T) { | ||
| t.Helper() | ||
| if testutil.GetTarget() == testutil.Docker { | ||
| t.Skip("When detaching from a container, for a session started with 'docker attach'" + | ||
| ", it prints 'read escape sequence', but for one started with 'docker (run|start)', it prints nothing." + | ||
| " However, the flag is called '--detach-keys' in all cases" + | ||
| ", so nerdctl prints 'read detach keys' for all cases" + | ||
| ", and that's why this test is skipped for Docker.") | ||
| } | ||
| } | ||
|
|
||
| // prepareContainerToAttach spins up a container (entrypoint = shell) with `-it` and detaches from it | ||
| // so that it can be re-attached to later. | ||
| func prepareContainerToAttach(base *testutil.Base, containerName string) { | ||
| opts := []func(*testutil.Cmd){ | ||
| testutil.WithStdin(testutil.NewDelayOnceReader(bytes.NewReader( | ||
| []byte{16, 17}, // ctrl+p,ctrl+q, see https://www.physics.udel.edu/~watson/scen103/ascii.html | ||
| ))), | ||
| } | ||
| // unbuffer(1) emulates tty, which is required by `nerdctl run -t`. | ||
| // unbuffer(1) can be installed with `apt-get install expect`. | ||
| // | ||
| // "-p" is needed because we need unbuffer to read from stdin, and from [1]: | ||
| // "Normally, unbuffer does not read from stdin. This simplifies use of unbuffer in some situations. | ||
| // To use unbuffer in a pipeline, use the -p flag." | ||
| // | ||
| // [1] https://linux.die.net/man/1/unbuffer | ||
| base.CmdWithHelper([]string{"unbuffer", "-p"}, "run", "-it", "--name", containerName, testutil.CommonImage). | ||
| CmdOption(opts...).AssertOutContains("read detach keys") | ||
| container := base.InspectContainer(containerName) | ||
| assert.Equal(base.T, container.State.Running, true) | ||
| } | ||
|
|
||
| func TestAttach(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| skipAttachForDocker(t) | ||
|
|
||
| base := testutil.NewBase(t) | ||
| containerName := testutil.Identifier(t) | ||
|
|
||
| defer base.Cmd("container", "rm", "-f", containerName).AssertOK() | ||
| prepareContainerToAttach(base, containerName) | ||
|
|
||
| opts := []func(*testutil.Cmd){ | ||
| testutil.WithStdin(testutil.NewDelayOnceReader(strings.NewReader("expr 1 + 1\nexit\n"))), | ||
| } | ||
| // `unbuffer -p` returns 0 even if the underlying nerdctl process returns a non-zero exit code, | ||
| // so the exit code cannot be easily tested here. | ||
| base.CmdWithHelper([]string{"unbuffer", "-p"}, "attach", containerName).CmdOption(opts...).AssertOutContains("2") | ||
| container := base.InspectContainer(containerName) | ||
| assert.Equal(base.T, container.State.Running, false) | ||
| } | ||
|
|
||
| func TestAttachDetachKeys(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| skipAttachForDocker(t) | ||
|
|
||
| base := testutil.NewBase(t) | ||
| containerName := testutil.Identifier(t) | ||
|
|
||
| defer base.Cmd("container", "rm", "-f", containerName).AssertOK() | ||
| prepareContainerToAttach(base, containerName) | ||
|
|
||
| opts := []func(*testutil.Cmd){ | ||
| testutil.WithStdin(testutil.NewDelayOnceReader(bytes.NewReader( | ||
| []byte{1, 2}, // https://www.physics.udel.edu/~watson/scen103/ascii.html | ||
| ))), | ||
| } | ||
| base.CmdWithHelper([]string{"unbuffer", "-p"}, "attach", "--detach-keys=ctrl-a,ctrl-b", containerName). | ||
| CmdOption(opts...).AssertOutContains("read detach keys") | ||
| container := base.InspectContainer(containerName) | ||
| assert.Equal(base.T, container.State.Running, true) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Needs
t.Helper()