github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/pkg/providers/virtualbox/detach_volume.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/virtualbox/virtualboxclient" 7 "github.com/solo-io/unik/pkg/types" 8 "path/filepath" 9 "strconv" 10 ) 11 12 func (p *VirtualboxProvider) DetachVolume(id string) error { 13 volume, err := p.GetVolume(id) 14 if err != nil { 15 return errors.New("retrieving volume "+id, err) 16 } 17 if volume.Attachment == "" { 18 return errors.New("volume has no attachment", nil) 19 } 20 instanceId := volume.Attachment 21 instance, err := p.GetInstance(instanceId) 22 if err != nil { 23 return errors.New("retrieving instance "+instanceId, err) 24 } 25 image, err := p.GetImage(instance.ImageId) 26 if err != nil { 27 return errors.New("retrieving image "+instance.ImageId, err) 28 } 29 vm, err := virtualboxclient.GetVm(instance.Id) 30 if err != nil { 31 return errors.New("retreiving vm from virtualbox", err) 32 } 33 var controllerKey string 34 for _, device := range vm.Devices { 35 if filepath.Clean(device.DiskFile) == filepath.Clean(getVolumePath(volume.Name)) { 36 controllerKey = device.ControllerKey 37 } 38 } 39 if controllerKey == "" { 40 return errors.New("could not find device attached to "+instance.Name+" that matches volume "+getVolumePath(volume.Name), nil) 41 } 42 43 controllerPort, err := strconv.Atoi(controllerKey) 44 if err != nil { 45 return errors.New("could not convert "+controllerKey+" to int", err) 46 } 47 logrus.Debugf("using storage controller %s", image.RunSpec.StorageDriver) 48 49 if err := virtualboxclient.DetachDisk(instance.Id, controllerPort, image.RunSpec.StorageDriver); err != nil { 50 return errors.New("detaching disk from vm", err) 51 } 52 53 if err := p.state.ModifyVolumes(func(volumes map[string]*types.Volume) error { 54 volume, ok := volumes[volume.Id] 55 if !ok { 56 return errors.New("no record of "+volume.Id+" in the state", nil) 57 } 58 volume.Attachment = "" 59 return nil 60 }); err != nil { 61 return errors.New("modifying volume map in state", err) 62 } 63 return nil 64 }