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