github.com/hanks177/podman/v4@v4.1.3-0.20220613032544-16d90015bc83/pkg/api/handlers/compat/images_prune.go (about)

     1  package compat
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"net/http"
     7  
     8  	"github.com/hanks177/podman/v4/libpod"
     9  	"github.com/hanks177/podman/v4/pkg/api/handlers"
    10  	"github.com/hanks177/podman/v4/pkg/api/handlers/utils"
    11  	api "github.com/hanks177/podman/v4/pkg/api/types"
    12  	"github.com/hanks177/podman/v4/pkg/domain/entities"
    13  	"github.com/hanks177/podman/v4/pkg/domain/infra/abi"
    14  	"github.com/hanks177/podman/v4/pkg/util"
    15  	"github.com/docker/docker/api/types"
    16  	"github.com/pkg/errors"
    17  )
    18  
    19  func PruneImages(w http.ResponseWriter, r *http.Request) {
    20  	var filters []string
    21  	runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime)
    22  
    23  	filterMap, err := util.PrepareFilters(r)
    24  	if err != nil {
    25  		utils.Error(w, http.StatusInternalServerError, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
    26  		return
    27  	}
    28  
    29  	for k, v := range *filterMap {
    30  		for _, val := range v {
    31  			filters = append(filters, fmt.Sprintf("%s=%s", k, val))
    32  		}
    33  	}
    34  
    35  	imageEngine := abi.ImageEngine{Libpod: runtime}
    36  
    37  	pruneOptions := entities.ImagePruneOptions{Filter: filters}
    38  	imagePruneReports, err := imageEngine.Prune(r.Context(), pruneOptions)
    39  	if err != nil {
    40  		utils.InternalServerError(w, err)
    41  		return
    42  	}
    43  
    44  	idr := make([]types.ImageDeleteResponseItem, 0, len(imagePruneReports))
    45  	var reclaimedSpace uint64
    46  	var errorMsg bytes.Buffer
    47  	for _, p := range imagePruneReports {
    48  		if p.Err != nil {
    49  			// Docker stops on first error vs. libpod which keeps going. Given API constraints, concatenate all errors
    50  			// and return that string.
    51  			errorMsg.WriteString(p.Err.Error())
    52  			errorMsg.WriteString("; ")
    53  			continue
    54  		}
    55  
    56  		idr = append(idr, types.ImageDeleteResponseItem{
    57  			Deleted: p.Id,
    58  		})
    59  		reclaimedSpace += p.Size
    60  	}
    61  	if errorMsg.Len() > 0 {
    62  		utils.InternalServerError(w, errors.New(errorMsg.String()))
    63  		return
    64  	}
    65  
    66  	payload := handlers.ImagesPruneReport{
    67  		ImagesPruneReport: types.ImagesPruneReport{
    68  			ImagesDeleted:  idr,
    69  			SpaceReclaimed: reclaimedSpace,
    70  		},
    71  	}
    72  	utils.WriteResponse(w, http.StatusOK, payload)
    73  }