Skip to content

Commit

Permalink
Added fix for container prune and volume prune(issue containerd#648) …
Browse files Browse the repository at this point in the history
…and added changes to README.md

Signed-off-by: Raymond Mathew <[email protected]>
  • Loading branch information
click2cloud-lamda committed Apr 25, 2022
1 parent 8385be4 commit 8080c87
Show file tree
Hide file tree
Showing 5 changed files with 237 additions and 1 deletion.
23 changes: 22 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ It does not necessarily mean that the corresponding features are missing in cont
- [:whale: :blue_square: nerdctl create](#whale-blue_square-nerdctl-create)
- [:whale: :blue_square: nerdctl ps](#whale-blue_square-nerdctl-ps)
- [:whale: :blue_square: nerdctl inspect](#whale-blue_square-nerdctl-inspect)
- [:whale: :blue_square: nerdctl container prune](#whale-blue_square-nerdctl-container-prune)
- [:whale: nerdctl logs](#whale-nerdctl-logs)
- [:whale: nerdctl port](#whale-nerdctl-port)
- [:whale: nerdctl rm](#whale-nerdctl-rm)
Expand Down Expand Up @@ -295,6 +296,7 @@ It does not necessarily mean that the corresponding features are missing in cont
- [:whale: nerdctl volume ls](#whale-nerdctl-volume-ls)
- [:whale: nerdctl volume inspect](#whale-nerdctl-volume-inspect)
- [:whale: nerdctl volume rm](#whale-nerdctl-volume-rm)
- [:whale: nerdctl volume prune](#whale-nerdctl-volume-prune)
- [Namespace management](#namespace-management)
- [:nerd_face: :blue_square: nerdctl namespace create](#nerd_face-blue_square-nerdctl-namespace-create)
- [:nerd_face: :blue_square: nerdctl namespace inspect](#nerd_face-blue_square-nerdctl-namespace-inspect)
Expand Down Expand Up @@ -660,6 +662,16 @@ Flags:

Unimplemented `docker inspect` flags: `--size`

### :whale: :blue_square: nerdctl container prune
Removes all stopped containers

Usage: `nerdctl container prune [OPTIONS] NAME|ID [NAME|ID...]`

Flags:
- :whale: `-f, --force`: Do not prompt for confirmation

Unimplemented `docker container prune` flags: `--filter`

### :whale: nerdctl logs
Fetch the logs of a container.

Expand Down Expand Up @@ -1101,6 +1113,16 @@ Usage: `nerdctl volume rm [OPTIONS] VOLUME [VOLUME...]`
- :whale: `-f, --force`: Force the removal of one or more volumes
- :warning: WIP: currently, volumes are always forcibly removed, even when `--force` is not specified.

### :whale: nerdctl volume prune
Remove all unused local volumes. Unused local volumes are those which are not referenced by any containers

Usage: `nerdctl volume prune [OPTIONS]`

Flags:
- :whale: `-f, --force`: Do not prompt for confirmation

Unimplemented `docker volume prune` flags: `--filter`

## Namespace management

### :nerd_face: :blue_square: nerdctl namespace create
Expand Down Expand Up @@ -1426,7 +1448,6 @@ Container management:
- `docker diff`
- `docker rename`

- `docker container prune`

- `docker checkpoint *`

Expand Down
1 change: 1 addition & 0 deletions cmd/nerdctl/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ func newContainerCommand() *cobra.Command {
newWaitCommand(),
newUnpauseCommand(),
newCommitCommand(),
newContainerPruneCommand(),
)
return containerCommand
}
Expand Down
103 changes: 103 additions & 0 deletions cmd/nerdctl/container_prune.go
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 (
"fmt"
"strings"

"github.com/containerd/containerd"
"github.com/containerd/containerd/namespaces"
"github.com/containerd/nerdctl/pkg/containerinspector"
"github.com/containerd/nerdctl/pkg/namestore"
"github.com/spf13/cobra"
)

func newContainerPruneCommand() *cobra.Command {
containerPruneCommand := &cobra.Command{
Use: "prune [flags]",
Short: "Removes all stopped containers",
RunE: containerPruneAction,
SilenceUsage: true,
SilenceErrors: true,
}
containerPruneCommand.Flags().BoolP("force", "f", false, "Do not prompt for confirmation")
containerPruneCommand.Flags().String("filter", "", "not yet been implemented")
return containerPruneCommand
}

func containerPruneAction(cmd *cobra.Command, _ []string) error {
client, ctx, cancel, err := newClient(cmd)
if err != nil {
return err
}
defer cancel()
dataStore, err := getDataStore(cmd)
if err != nil {
return err
}
force, err := cmd.Flags().GetBool("force")
if err != nil {
return err
}
if !force {
var confirm string
fmt.Fprintf(cmd.OutOrStdout(), "%s", "WARNING! This will remove all stopped containers.\nAre you sure you want to continue? [y/N] ")
fmt.Fscanf(cmd.InOrStdin(), "%s", &confirm)

if strings.ToLower(confirm) != "y" {
return nil
}
}
ns, err := cmd.Flags().GetString("namespace")
if err != nil {
return err
}

ctx = namespaces.WithNamespace(ctx, ns)
var deletedContainers []string
containers, err := client.Containers(ctx)
if err != nil {
return err
}
for _, container := range containers {
cont, _ := containerinspector.Inspect(ctx, container)
if cont.Process == nil || (cont.Process != nil && cont.Process.Status.Status != containerd.Running) {
containerNameStore, err := namestore.New(dataStore, ns)
if err != nil {
return err
}
stateDir, err := getContainerStateDirPath(cmd, dataStore, container.ID())
if err != nil {
return err
}
err = removeContainer(cmd, ctx, client, ns, container.ID(), "", force, dataStore, stateDir, containerNameStore, true)
if err != nil {
return err
}
deletedContainers = append(deletedContainers, container.ID())
}
}
if deletedContainers != nil {
fmt.Fprintf(cmd.OutOrStdout(), "Deleted Containers: \n")
for _, elem := range deletedContainers {
fmt.Fprintln(cmd.OutOrStdout(), elem)
}
}

return nil
}
1 change: 1 addition & 0 deletions cmd/nerdctl/volume.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ func newVolumeCommand() *cobra.Command {
newVolumeInspectCommand(),
newVolumeCreateCommand(),
newVolumeRmCommand(),
newVolumePruneCommand(),
)
return volumeCommand
}
Expand Down
110 changes: 110 additions & 0 deletions cmd/nerdctl/volume_prune.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
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 (
"encoding/json"
"fmt"
"strings"

"github.com/containerd/nerdctl/pkg/containerinspector"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

func newVolumePruneCommand() *cobra.Command {
volumeRmCommand := &cobra.Command{
Use: "prune",
Short: "Remove all unused local volumes. Unused local volumes are those which are not referenced by any containers.",
Long: "NOTE: volume in use is not deleted",
RunE: volumePruneAction,
SilenceUsage: true,
SilenceErrors: true,
}
volumeRmCommand.Flags().BoolP("force", "f", false, "Do not prompt for confirmation")
volumeRmCommand.Flags().String("filter", "", "not yet been implemented")
return volumeRmCommand
}

func volumePruneAction(cmd *cobra.Command, args []string) error {
client, ctx, cancel, err := newClient(cmd)
if err != nil {
return err
}
defer cancel()
force, err := cmd.Flags().GetBool("force")
if err != nil {
return err
}
if !force {
var confirm string
fmt.Fprintf(cmd.OutOrStdout(), "%s", "WARNING! This will remove all local volumes not used by at least one container.\nAre you sure you want to continue? [y/N] ")
fmt.Fscanf(cmd.InOrStdin(), "%s", &confirm)

if strings.ToLower(confirm) != "y" {
return nil
}
}
containers, err := client.Containers(ctx)
if err != nil {
return err
}
var mount *specs.Spec
var removedNames []string
volumes, err := getVolumes(cmd)
if err != nil {
return err
}
volStore, err := getVolumeStore(cmd)
if err != nil {
return err
}
for name, voldetails := range volumes {
var found bool
for _, container := range containers {
n, err := containerinspector.Inspect(ctx, container)
if err != nil {
return err
}
err = json.Unmarshal(n.Container.Spec.Value, &mount)
if err != nil {
return err
}
if found = checkVolume(&mount.Mounts, voldetails.Mountpoint); found {
found = true
logrus.WithError(fmt.Errorf("Volume %q is in use", name)).Error(fmt.Errorf("Remove Volume: %q failed", name))
break
}
}
if !found {
// volumes that are not mounted to any container
removedNames = append(removedNames, name)
}
}
if removedNames != nil {
rNames, err := volStore.Remove(removedNames)
if err != nil {
return err
}
fmt.Fprintln(cmd.OutOrStdout(), "Deleted Volumes:", rNames)
for _, elem := range rNames {
fmt.Fprintln(cmd.OutOrStdout(), elem)
}
}
return nil
}

0 comments on commit 8080c87

Please sign in to comment.