github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/pkg/providers/virtualbox/pull_image.go (about)

     1  package virtualbox
     2  
     3  import (
     4  	"github.com/sirupsen/logrus"
     5  	"github.com/emc-advanced-dev/pkg/errors"
     6  	"github.com/solo-io/unik/pkg/providers/common"
     7  	"github.com/solo-io/unik/pkg/types"
     8  	"io/ioutil"
     9  	"os"
    10  	"path/filepath"
    11  )
    12  
    13  func (p *VirtualboxProvider) PullImage(params types.PullImagePararms) error {
    14  	images, err := p.ListImages()
    15  	if err != nil {
    16  		return errors.New("retrieving image list for existing image", err)
    17  	}
    18  	for _, image := range images {
    19  		if image.Name == params.ImageName {
    20  			if !params.Force {
    21  				return errors.New("an image already exists with name '"+params.ImageName+"', try again with --force", nil)
    22  			} else {
    23  				logrus.WithField("image", image).Warnf("force: deleting previous image with name " + params.ImageName)
    24  				if err := p.DeleteImage(image.Id, true); err != nil {
    25  					logrus.Warn(errors.New("failed removing previously existing image", err))
    26  				}
    27  			}
    28  		}
    29  	}
    30  
    31  	tmpImage, err := ioutil.TempFile("", "tmp-pull-image-"+params.ImageName)
    32  	if err != nil {
    33  		return errors.New("creating tmp file", err)
    34  	}
    35  	defer os.RemoveAll(tmpImage.Name())
    36  	image, err := common.PullImage(params.Config, params.ImageName, tmpImage)
    37  	if err != nil {
    38  		return errors.New("pulling image", err)
    39  	}
    40  	imagePath := getImagePath(image.Name)
    41  	os.MkdirAll(filepath.Dir(imagePath), 0755)
    42  	if err := os.Rename(tmpImage.Name(), imagePath); err != nil {
    43  		return errors.New("renaming tmp image to "+imagePath, err)
    44  	}
    45  
    46  	if err := p.state.ModifyImages(func(images map[string]*types.Image) error {
    47  		images[image.Name] = image
    48  		return nil
    49  	}); err != nil {
    50  		return errors.New("modifying image map in state", err)
    51  	}
    52  	logrus.Infof("image %v pulled successfully from %v", err)
    53  	return nil
    54  }