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

     1  package virtualbox
     2  
     3  import (
     4  	"github.com/sirupsen/logrus"
     5  	"github.com/emc-advanced-dev/pkg/errors"
     6  	"os"
     7  	"path/filepath"
     8  )
     9  
    10  func (p *VirtualboxProvider) DeleteImage(id string, force bool) error {
    11  	image, err := p.GetImage(id)
    12  	if err != nil {
    13  		return errors.New("retrieving image", err)
    14  	}
    15  	instances, err := p.ListInstances()
    16  	if err != nil {
    17  		return errors.New("retrieving list of instances", err)
    18  	}
    19  	for _, instance := range instances {
    20  		if instance.ImageId == image.Id {
    21  			if !force {
    22  				return errors.New("instance "+instance.Id+" found which uses image "+image.Id+"; try again with force=true", nil)
    23  			} else {
    24  				logrus.Warnf("deleting instance %s which belongs to image %s", instance.Id, image.Id)
    25  				err = p.DeleteInstance(instance.Id, true)
    26  				if err != nil {
    27  					return errors.New("failed to delete instance "+instance.Id+" which is using image "+image.Id, err)
    28  				}
    29  			}
    30  		}
    31  	}
    32  
    33  	imagePath := getImagePath(image.Name)
    34  	logrus.Warnf("deleting image file at %s", imagePath)
    35  	if err := os.RemoveAll(filepath.Dir(imagePath)); err != nil {
    36  		return errors.New("deleing image file at "+imagePath, err)
    37  	}
    38  
    39  	return p.state.RemoveImage(image)
    40  }