Skip to content

Added --export command #4405

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cmd/nerdctl/container/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ func Command() *cobra.Command {
StatsCommand(),
AttachCommand(),
HealthCheckCommand(),
ExportCommand(),
)
AddCpCommand(cmd)
return cmd
Expand Down
77 changes: 77 additions & 0 deletions cmd/nerdctl/container/container_export.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package container

import (
"fmt"
"os"

Check failure on line 6 in cmd/nerdctl/container/container_export.go

View workflow job for this annotation

GitHub Actions / go / linux

File is not properly formatted (gci)

Check failure on line 6 in cmd/nerdctl/container/container_export.go

View workflow job for this annotation

GitHub Actions / go / linux (go canary)

File is not properly formatted (gci)
"github.com/containerd/nerdctl/v2/cmd/nerdctl/completion"
"github.com/containerd/nerdctl/v2/cmd/nerdctl/helpers"
"github.com/containerd/nerdctl/v2/pkg/api/types"
"github.com/containerd/nerdctl/v2/pkg/clientutil"
"github.com/containerd/nerdctl/v2/pkg/cmd/container"
"github.com/mattn/go-isatty"
"github.com/spf13/cobra"
)

func ExportCommand() *cobra.Command {
var exportCommand = &cobra.Command{
Use: "export [OPTIONS] CONTAINER",
Args: cobra.MinimumNArgs(1),
Short: "Export a containers filesystem as a tar archive",
Long: "Export a containers filesystem as a tar archive",
RunE: exportAction,
ValidArgsFunction: exportShellComplete,
SilenceUsage: true,
SilenceErrors: true,
}
exportCommand.Flags().StringP("output", "o", "", "Write to a file, instead of STDOUT")

return exportCommand
}

func exportAction(cmd *cobra.Command, args []string) error {
globalOptions, err := helpers.ProcessRootCmdFlags(cmd)
if err != nil {
return err
}
if len(args) == 0 {
return fmt.Errorf("requires at least 1 argument")
}

output, err := cmd.Flags().GetString("output")
if err != nil {
return err
}

client, ctx, cancel, err := clientutil.NewClient(cmd.Context(), globalOptions.Namespace, globalOptions.Address)
if err != nil {
return err
}
defer cancel()

writer := cmd.OutOrStdout()
if output != "" {
f, err := os.OpenFile(output, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer f.Close()
writer = f
} else {
if isatty.IsTerminal(os.Stdout.Fd()) {
return fmt.Errorf("cowardly refusing to save to a terminal. Use the -o flag or redirect")
}
}

options := types.ContainerExportOptions{
Stdout: writer,
GOptions: globalOptions,
}

return container.Export(ctx, client, args[0], options)
}

func exportShellComplete(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
// show container names
return completion.ContainerNames(cmd, nil)
}
137 changes: 137 additions & 0 deletions cmd/nerdctl/container/container_export_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
/*
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 container

import (
"os"
"path/filepath"
"testing"

"gotest.tools/v3/assert"

"github.com/containerd/nerdctl/mod/tigron/test"
"github.com/containerd/nerdctl/mod/tigron/tig"

Check failure on line 27 in cmd/nerdctl/container/container_export_test.go

View workflow job for this annotation

GitHub Actions / go / linux

File is not properly formatted (gci)

Check failure on line 27 in cmd/nerdctl/container/container_export_test.go

View workflow job for this annotation

GitHub Actions / go / linux (go canary)

File is not properly formatted (gci)
"github.com/containerd/nerdctl/v2/pkg/testutil"
"github.com/containerd/nerdctl/v2/pkg/testutil/nerdtest"
)

// validateExportedTar checks that the tar file exists and has content
func validateExportedTar(outFile string) test.Comparator {
return func(stdout string, t tig.T) {
// Check if the tar file was created
_, err := os.Stat(outFile)
assert.Assert(t, !os.IsNotExist(err), "exported tar file %s was not created", outFile)

// Check if the tar file has some content (not empty)
statInfo, err := os.Stat(outFile)
assert.NilError(t, err, "failed to stat tar file %s", outFile)
assert.Assert(t, statInfo.Size() > 0, "exported tar file %s is empty", outFile)

t.Log("Export validation passed: tar file exists and has content")
}
}

func TestExportStoppedContainer(t *testing.T) {
testCase := nerdtest.Setup()
testCase.Setup = func(data test.Data, helpers test.Helpers) {
identifier := data.Identifier("container")
helpers.Ensure("create", "--name", identifier, testutil.CommonImage)
data.Labels().Set("cID", identifier)
data.Labels().Set("outFile", filepath.Join(os.TempDir(), identifier+".tar"))
}
testCase.Cleanup = func(data test.Data, helpers test.Helpers) {
helpers.Anyhow("container", "rm", "-f", data.Labels().Get("cID"))
helpers.Anyhow("rm", "-f", data.Labels().Get("cID"))
os.Remove(data.Labels().Get("outFile"))
}

testCase.SubTests = []*test.Case{
{
Description: "export command succeeds",
NoParallel: true,
Command: func(data test.Data, helpers test.Helpers) test.TestableCommand {
return helpers.Command("export", "-o", data.Labels().Get("outFile"), data.Labels().Get("cID"))
},
Expected: test.Expects(0, nil, nil),
},
{
Description: "tar file exists and has content",
NoParallel: true,
Command: func(data test.Data, helpers test.Helpers) test.TestableCommand {
// Use a simple command that always succeeds to trigger the validation
return helpers.Custom("echo", "validating tar file")
},
Expected: func(data test.Data, helpers test.Helpers) *test.Expected {
return &test.Expected{
ExitCode: 0,
Output: validateExportedTar(data.Labels().Get("outFile")),
}
},
},
}

testCase.Run(t)
}

func TestExportRunningContainer(t *testing.T) {
testCase := nerdtest.Setup()
testCase.Setup = func(data test.Data, helpers test.Helpers) {
identifier := data.Identifier("container")
helpers.Ensure("run", "-d", "--name", identifier, testutil.CommonImage, "sleep", nerdtest.Infinity)
data.Labels().Set("cID", identifier)
data.Labels().Set("outFile", filepath.Join(os.TempDir(), identifier+".tar"))
}
testCase.Cleanup = func(data test.Data, helpers test.Helpers) {
helpers.Anyhow("rm", "-f", data.Labels().Get("cID"))
os.Remove(data.Labels().Get("outFile"))
}

testCase.SubTests = []*test.Case{
{
Description: "export command succeeds",
NoParallel: true,
Command: func(data test.Data, helpers test.Helpers) test.TestableCommand {
return helpers.Command("export", "-o", data.Labels().Get("outFile"), data.Labels().Get("cID"))
},
Expected: test.Expects(0, nil, nil),
},
{
Description: "tar file exists and has content",
NoParallel: true,
Command: func(data test.Data, helpers test.Helpers) test.TestableCommand {
// Use a simple command that always succeeds to trigger the validation
return helpers.Custom("echo", "validating tar file")
},
Expected: func(data test.Data, helpers test.Helpers) *test.Expected {
return &test.Expected{
ExitCode: 0,
Output: validateExportedTar(data.Labels().Get("outFile")),
}
},
},
}

testCase.Run(t)
}

func TestExportNonexistentContainer(t *testing.T) {
testCase := nerdtest.Setup()
testCase.Command = test.Command("export", "nonexistent-container")
testCase.Expected = test.Expects(1, nil, nil)

testCase.Run(t)
}
1 change: 1 addition & 0 deletions cmd/nerdctl/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,7 @@ Config file ($NERDCTL_TOML): %s
container.PauseCommand(),
container.UnpauseCommand(),
container.CommitCommand(),
container.ExportCommand(),
container.WaitCommand(),
container.RenameCommand(),
container.AttachCommand(),
Expand Down
7 changes: 7 additions & 0 deletions pkg/api/types/container_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ type ContainerKillOptions struct {
KillSignal string
}

// ContainerExportOptions specifies options for `nerdctl (container) export`.
type ContainerExportOptions struct {
Stdout io.Writer
// GOptions is the global options
GOptions GlobalCommandOptions
}

// ContainerCreateOptions specifies options for `nerdctl (container) create` and `nerdctl (container) run`.
type ContainerCreateOptions struct {
Stdout io.Writer
Expand Down
Loading
Loading