github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/pkg/providers/openstack/delete_image.go (about) 1 package openstack 2 3 import ( 4 "fmt" 5 "github.com/emc-advanced-dev/pkg/errors" 6 "github.com/solo-io/unik/pkg/types" 7 "github.com/rackspace/gophercloud" 8 "github.com/rackspace/gophercloud/openstack/imageservice/v2/images" 9 ) 10 11 func (p *OpenstackProvider) 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 17 // Delete instances of this image. 18 instances, err := p.ListInstances() 19 if err != nil { 20 return errors.New("failed to retrieve list of instances", err) 21 } 22 for _, instance := range instances { 23 if instance.ImageId == image.Id { 24 if !force { 25 return fmt.Errorf("instance '%s' found which uses image '%s'! Try again with --force.", instance.Id, image.Id) 26 } else { 27 err = p.DeleteInstance(instance.Id, true) 28 if err != nil { 29 return errors.New(fmt.Sprintf("failed to delete instance '%s' which uses image '%s'", instance.Id, image.Id), err) 30 } 31 } 32 } 33 } 34 35 clientGlance, err := p.newClientGlance() 36 if err != nil { 37 return err 38 } 39 40 if err := deleteImage(clientGlance, image.Id); err != nil { 41 return errors.New(fmt.Sprintf("failed to delete image '%s'", image.Id), err) 42 } 43 44 // Update state. 45 if err := p.state.ModifyImages(func(imageList map[string]*types.Image) error { 46 delete(imageList, image.Id) 47 return nil 48 }); err != nil { 49 return errors.New("failed to modify image map in state", err) 50 } 51 return nil 52 } 53 54 // deleteImage deletes image from OpenStack. 55 func deleteImage(clientGlance *gophercloud.ServiceClient, imageId string) error { 56 return images.Delete(clientGlance, imageId).Err 57 }