github.com/containerd/nerdctl/v2@v2.0.0-beta.5.0.20240520001846-b5758f54fa28/pkg/cmd/container/prune.go (about)

     1  /*
     2     Copyright The containerd Authors.
     3  
     4     Licensed under the Apache License, Version 2.0 (the "License");
     5     you may not use this file except in compliance with the License.
     6     You may obtain a copy of the License at
     7  
     8         http://www.apache.org/licenses/LICENSE-2.0
     9  
    10     Unless required by applicable law or agreed to in writing, software
    11     distributed under the License is distributed on an "AS IS" BASIS,
    12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13     See the License for the specific language governing permissions and
    14     limitations under the License.
    15  */
    16  
    17  package container
    18  
    19  import (
    20  	"context"
    21  	"errors"
    22  	"fmt"
    23  	"strings"
    24  
    25  	"github.com/containerd/containerd"
    26  	"github.com/containerd/log"
    27  	"github.com/containerd/nerdctl/v2/pkg/api/types"
    28  )
    29  
    30  // Prune remove all stopped containers
    31  func Prune(ctx context.Context, client *containerd.Client, options types.ContainerPruneOptions) error {
    32  	containers, err := client.Containers(ctx)
    33  	if err != nil {
    34  		return err
    35  	}
    36  
    37  	var deleted []string
    38  	for _, c := range containers {
    39  		if err = RemoveContainer(ctx, c, options.GOptions, false, true, client); err == nil {
    40  			deleted = append(deleted, c.ID())
    41  			continue
    42  		}
    43  		if errors.As(err, &ErrContainerStatus{}) {
    44  			continue
    45  		}
    46  		log.G(ctx).WithError(err).Warnf("failed to remove container %s", c.ID())
    47  	}
    48  
    49  	if len(deleted) > 0 {
    50  		fmt.Fprintln(options.Stdout, "Deleted Containers:")
    51  		fmt.Fprintln(options.Stdout, strings.Join(deleted, "\n"))
    52  	}
    53  
    54  	return nil
    55  }