github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/pkg/providers/gcloud/list_instances.go (about)

     1  package gcloud
     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 *GcloudProvider) ListInstances() ([]*types.Instance, error) {
    10  	if len(p.state.GetInstances()) < 1 {
    11  		return []*types.Instance{}, nil
    12  	}
    13  
    14  	gInstances, err := p.compute().Instances.List(p.config.ProjectID, p.config.Zone).Do()
    15  	if err != nil {
    16  		return nil, errors.New("getting instance list from gcloud", err)
    17  	}
    18  
    19  	updatedInstances := []*types.Instance{}
    20  	for _, instance := range p.state.GetInstances() {
    21  		instanceFound := false
    22  		//find instance in list
    23  		for _, gInstance := range gInstances.Items {
    24  			if gInstance.Name == instance.Name {
    25  				instance.State = parseInstanceState(gInstance.Status)
    26  
    27  				//use first network interface, skip if unavailable
    28  				if len(gInstance.NetworkInterfaces) > 0 && len(gInstance.NetworkInterfaces[0].AccessConfigs) > 0 {
    29  					instance.IpAddress = gInstance.NetworkInterfaces[0].AccessConfigs[0].NatIP
    30  				}
    31  				p.state.ModifyInstances(func(instances map[string]*types.Instance) error {
    32  					instances[instance.Id] = instance
    33  					return nil
    34  				})
    35  				updatedInstances = append(updatedInstances, instance)
    36  				instanceFound = true
    37  				break
    38  			}
    39  		}
    40  		if !instanceFound {
    41  			logrus.Warnf("instance %v no longer found, cleaning it from state", instance.Name)
    42  			p.state.RemoveInstance(instance)
    43  		}
    44  	}
    45  
    46  	return updatedInstances, nil
    47  }
    48  
    49  func parseInstanceState(status string) types.InstanceState {
    50  	switch status {
    51  	case "RUNNING":
    52  		return types.InstanceState_Running
    53  	case "PROVISIONING":
    54  		fallthrough
    55  	case "STAGING":
    56  		return types.InstanceState_Pending
    57  	case "SUSPENDED":
    58  		fallthrough
    59  	case "STOPPING":
    60  		fallthrough
    61  	case "SUSPENDING":
    62  		fallthrough
    63  	case "STOPPED":
    64  		return types.InstanceState_Stopped
    65  	case "TERMINATED":
    66  		return types.InstanceState_Terminated
    67  	}
    68  	return types.InstanceState_Unknown
    69  }