github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/pkg/providers/vsphere/delete_instance.go (about) 1 package vsphere 2 3 import ( 4 "github.com/sirupsen/logrus" 5 "github.com/emc-advanced-dev/pkg/errors" 6 "github.com/solo-io/unik/pkg/types" 7 ) 8 9 func (p *VsphereProvider) DeleteInstance(id string, force bool) error { 10 instance, err := p.GetInstance(id) 11 if err != nil { 12 return errors.New("retrieving instance "+id, err) 13 } 14 if instance.State == types.InstanceState_Running { 15 if force { 16 if err := p.StopInstance(instance.Id); err != nil { 17 return errors.New("stopping instance for deletion", err) 18 } 19 } else { 20 return errors.New("instance "+instance.Id+"is still running. try again with --force or power off instance first", err) 21 } 22 } 23 image, err := p.GetImage(instance.ImageId) 24 if err != nil { 25 return errors.New("getting image for instance", err) 26 } 27 volumesToDetach := []*types.Volume{} 28 volumes, err := p.ListVolumes() 29 if err != nil { 30 return errors.New("getting volume list", err) 31 } 32 for _, volume := range volumes { 33 if volume.Attachment == instance.Id { 34 logrus.Debugf("detaching volume: %v", volume) 35 volumesToDetach = append(volumesToDetach, volume) 36 } 37 } 38 39 c := p.getClient() 40 for controllerPort, deviceMapping := range image.RunSpec.DeviceMappings { 41 if deviceMapping.MountPoint != "/" { 42 if err := c.DetachDisk(instance.Id, controllerPort, image.RunSpec.StorageDriver); err != nil { 43 return errors.New("detaching volume from instance", err) 44 } 45 } 46 } 47 err = c.DestroyVm(instance.Name) 48 if err != nil { 49 return errors.New("failed to terminate instance "+instance.Id, err) 50 } 51 return p.state.RemoveInstance(instance) 52 }