github.com/sealerio/sealer@v0.11.1-0.20240507115618-f4f89c5853ae/pkg/imageengine/buildah/remove_container.go (about)

     1  // Copyright © 2022 Alibaba Group Holding Ltd.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package buildah
    16  
    17  import (
    18  	"fmt"
    19  	"os"
    20  
    21  	"github.com/containers/buildah"
    22  	"github.com/containers/buildah/util"
    23  	"github.com/pkg/errors"
    24  	"github.com/sirupsen/logrus"
    25  
    26  	"github.com/sealerio/sealer/pkg/define/options"
    27  )
    28  
    29  func (engine *Engine) RemoveContainer(opts *options.RemoveContainerOptions) error {
    30  	if len(opts.ContainerNamesOrIDs) == 0 && !opts.All {
    31  		return fmt.Errorf("container name of id must be specified")
    32  	}
    33  	if len(opts.ContainerNamesOrIDs) > 0 && opts.All {
    34  		return fmt.Errorf("all can't be true if the containers are specified")
    35  	}
    36  
    37  	var lastError error
    38  	var delContainerErrStr = "error removing container"
    39  	store := engine.ImageStore()
    40  	if opts.All {
    41  		builders, err := buildah.OpenAllBuilders(store)
    42  		if err != nil {
    43  			return errors.Wrapf(err, "error reading build containers")
    44  		}
    45  
    46  		for _, builder := range builders {
    47  			id := builder.ContainerID
    48  			if err = builder.Delete(); err != nil {
    49  				lastError = util.WriteError(os.Stderr, errors.Wrapf(err, "%s %q", delContainerErrStr, builder.Container), lastError)
    50  				continue
    51  			}
    52  			logrus.Debugf("%s", id)
    53  		}
    54  	} else {
    55  		for _, name := range opts.ContainerNamesOrIDs {
    56  			builder, err := OpenBuilder(getContext(), store, name)
    57  			if err != nil {
    58  				lastError = util.WriteError(os.Stderr, errors.Wrapf(err, "%s %q", delContainerErrStr, name), lastError)
    59  				continue
    60  			}
    61  			id := builder.ContainerID
    62  			if err = builder.Delete(); err != nil {
    63  				lastError = util.WriteError(os.Stderr, errors.Wrapf(err, "%s %q", delContainerErrStr, name), lastError)
    64  				continue
    65  			}
    66  			logrus.Debugf("%s", id)
    67  		}
    68  	}
    69  	return lastError
    70  }