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

     1  package compat
     2  
     3  import (
     4  	"io/ioutil"
     5  	"net/http"
     6  	"os"
     7  
     8  	"github.com/hanks177/podman/v4/libpod"
     9  	"github.com/hanks177/podman/v4/pkg/api/handlers/utils"
    10  	api "github.com/hanks177/podman/v4/pkg/api/types"
    11  	"github.com/pkg/errors"
    12  )
    13  
    14  func ExportContainer(w http.ResponseWriter, r *http.Request) {
    15  	runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime)
    16  	name := utils.GetName(r)
    17  	con, err := runtime.LookupContainer(name)
    18  	if err != nil {
    19  		utils.ContainerNotFound(w, name, err)
    20  		return
    21  	}
    22  	tmpfile, err := ioutil.TempFile("", "api.tar")
    23  	if err != nil {
    24  		utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "unable to create tempfile"))
    25  		return
    26  	}
    27  	defer os.Remove(tmpfile.Name())
    28  	if err := tmpfile.Close(); err != nil {
    29  		utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "unable to close tempfile"))
    30  		return
    31  	}
    32  	if err := con.Export(tmpfile.Name()); err != nil {
    33  		utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "failed to save image"))
    34  		return
    35  	}
    36  	rdr, err := os.Open(tmpfile.Name())
    37  	if err != nil {
    38  		utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "failed to read the exported tarfile"))
    39  		return
    40  	}
    41  	defer rdr.Close()
    42  	utils.WriteResponse(w, http.StatusOK, rdr)
    43  }