Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
62 changes: 62 additions & 0 deletions cmd/nerdctl/image/image_list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,17 @@ import (
"github.com/containerd/nerdctl/v2/pkg/testutil/nerdtest"
)

// padRow widens a row of a table back to the width of its header, so that its last column can be
// read. tabutil indexes the columns by byte offset and slices without checking the bounds, and a
// row can be shorter than the header in two ways: the trailing column is empty, and the padding of
// the very last line is gone once the output has been trimmed.
func padRow(header, row string) string {
if pad := len(header) - len(row); pad > 0 {
return row + strings.Repeat(" ", pad)
}
return row
}

// TestNameFilterFor is a regression test for
// https://github.com/containerd/nerdctl/issues/5113: `nerdctl image ls
// myapp`, where myapp is a bare repository name, returned nothing unless
Expand Down Expand Up @@ -207,6 +218,57 @@ func TestImages(t *testing.T) {
}
},
},
{
Description: "In use survives a retag",
Setup: func(data test.Data, helpers test.Helpers) {
// Run a container off a private tag, then move that tag onto another image.
// The container still runs the original image, so that is the one that must
// stay marked as in use.
helpers.Ensure("tag", commonImage.String(), data.Identifier()+":moving")
helpers.Ensure("run", "-d", "--quiet", "--name", data.Identifier(),
data.Identifier()+":moving", "sleep", nerdtest.Infinity)
helpers.Ensure("tag", testutil.NginxAlpineImage, data.Identifier()+":moving")

nginx, _ := referenceutil.Parse(testutil.NginxAlpineImage)
data.Labels().Set("retaggedTo", nginx.FamiliarName()+":"+nginx.Tag)
},
Cleanup: func(data test.Data, helpers test.Helpers) {
helpers.Anyhow("rm", "-f", data.Identifier())
helpers.Anyhow("rmi", "-f", data.Identifier()+":moving")
},
Command: test.Command("images"),
Expected: func(data test.Data, helpers test.Helpers) *test.Expected {
return &test.Expected{
Output: func(stdout string, t tig.T) {
lines := strings.Split(strings.TrimSpace(stdout), "\n")
assert.Assert(t, len(lines) >= 2, "there should be at least two lines\n")
tab := tabutil.NewReader("IMAGE\tID\tDISK USAGE\tCONTENT SIZE\tEXTRA")
err := tab.ParseHeader(lines[0])
assert.NilError(t, err, "ParseHeader should not fail\n")

original := commonImage.FamiliarName() + ":" + commonImage.Tag
retagged := data.Labels().Get("retaggedTo")
seen := 0
for _, line := range lines[1:] {
line = padRow(lines[0], line)
image, _ := tab.ReadRow(line, "IMAGE")
extra, _ := tab.ReadRow(line, "EXTRA")
switch image {
case original:
assert.Equal(t, extra, "U",
"the image the container runs must stay in use: "+image)
seen++
case retagged:
assert.Equal(t, extra, "",
"the image the tag now points at is not in use: "+image)
seen++
}
}
assert.Equal(t, seen, 2, "both images should be listed\n")
},
}
},
},
},
}

Expand Down
1 change: 1 addition & 0 deletions cmd/nerdctl/system/system.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ func Command() *cobra.Command {
}
// versionCommand is not here
cmd.AddCommand(
dfCommand(),
EventsCommand(),
InfoCommand(),
pruneCommand(),
Expand Down
90 changes: 90 additions & 0 deletions cmd/nerdctl/system/system_df.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
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 system

import (
"github.com/spf13/cobra"

"github.com/containerd/log"

"github.com/containerd/nerdctl/v2/cmd/nerdctl/builder"
"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/system"
)

func dfCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "df [flags]",
Short: "Show nerdctl disk usage",
Args: cobra.NoArgs,
RunE: dfAction,
SilenceUsage: true,
SilenceErrors: true,
}
cmd.Flags().BoolP("verbose", "v", false, "Show detailed information on space usage")
cmd.Flags().String("format", "", "Format the output using the given Go template, e.g, '{{json .}}'")
return cmd
}

func dfOptions(cmd *cobra.Command) (types.SystemDfOptions, error) {
globalOptions, err := helpers.ProcessRootCmdFlags(cmd)
if err != nil {
return types.SystemDfOptions{}, err
}

verbose, err := cmd.Flags().GetBool("verbose")
if err != nil {
return types.SystemDfOptions{}, err
}

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

buildkitHost, err := builder.GetBuildkitHost(cmd, globalOptions.Namespace)
if err != nil {
log.L.WithError(err).Warn("BuildKit is not running. The build cache usage will be reported as empty.")
buildkitHost = ""
}

return types.SystemDfOptions{
Stdout: cmd.OutOrStdout(),
Stderr: cmd.ErrOrStderr(),
GOptions: globalOptions,
Format: format,
Verbose: verbose,
BuildKitHost: buildkitHost,
}, nil
}

func dfAction(cmd *cobra.Command, _ []string) error {
options, err := dfOptions(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 system.Df(ctx, client, options)
}
70 changes: 70 additions & 0 deletions cmd/nerdctl/system/system_df_linux_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
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 system

import (
"fmt"
"testing"

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

"github.com/containerd/nerdctl/v2/pkg/testutil"
"github.com/containerd/nerdctl/v2/pkg/testutil/nerdtest"
)

// TestSystemDfVolumes covers the Local Volumes row, which the rest of TestSystemDf cannot: a volume
// is only counted once a container mounts it, and the target of a mount is written differently on
// each platform.
func TestSystemDfVolumes(t *testing.T) {
testCase := nerdtest.Setup()

// The counts are only meaningful when nothing else is running against the same namespace.
testCase.NoParallel = true

testCase.SubTests = []*test.Case{
{
Description: "mounted volume is active",
Require: nerdtest.Private,
Setup: func(data test.Data, helpers test.Helpers) {
data.Labels().Set(baselineLabel, helpers.Capture("system", "df"))
helpers.Ensure("volume", "create", data.Identifier())
helpers.Ensure("run", "-d", "--name", data.Identifier(),
"-v", fmt.Sprintf("%s:/volume", data.Identifier()),
testutil.CommonImage, "sleep", nerdtest.Infinity)
},
Cleanup: func(data test.Data, helpers test.Helpers) {
helpers.Anyhow("rm", "-f", data.Identifier())
helpers.Anyhow("volume", "rm", "-f", data.Identifier())
},
Command: test.Command("system", "df"),
Expected: func(data test.Data, helpers test.Helpers) *test.Expected {
return &test.Expected{
ExitCode: 0,
Output: func(stdout string, t tig.T) {
// The volume is created by this test and the container it runs mounts it,
// so both counts went up by it.
dfGrewBy(t, data, stdout, "Local Volumes", totalColumn, 1)
dfGrewBy(t, data, stdout, "Local Volumes", activeColumn, 1)
},
}
},
},
}

testCase.Run(t)
}
Loading
Loading