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

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