github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/pkg/providers/openstack/delete_instance.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/compute/v2/servers"
     9  )
    10  
    11  func (p *OpenstackProvider) DeleteInstance(id string, force bool) error {
    12  	instance, err := p.GetInstance(id)
    13  	if err != nil {
    14  		return errors.New(fmt.Sprintf("failed to retrieve instance '%s'", id), err)
    15  	}
    16  	if instance.State == types.InstanceState_Running && !force {
    17  		return errors.New(fmt.Sprintf("instance '%s' is still running. try again with --force or power off instance first", instance.Id), err)
    18  	}
    19  
    20  	clientNova, err := p.newClientNova()
    21  	if err != nil {
    22  		return err
    23  	}
    24  
    25  	if deleteErr := deleteServer(clientNova, instance.Id); deleteErr != nil {
    26  		return errors.New(fmt.Sprintf("failed to terminate instance '%s'", instance.Id), deleteErr)
    27  	}
    28  
    29  	// Update state.
    30  	if err := p.state.ModifyInstances(func(instances map[string]*types.Instance) error {
    31  		delete(instances, instance.Id)
    32  		return nil
    33  	}); err != nil {
    34  		return errors.New("failed to modify image map in state", err)
    35  	}
    36  	return nil
    37  }
    38  
    39  func deleteServer(clientNova *gophercloud.ServiceClient, instanceId string) error {
    40  	return servers.Delete(clientNova, instanceId).Err
    41  }