github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/pkg/providers/virtualbox/sync_state.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/common"
     7  	"github.com/solo-io/unik/pkg/providers/virtualbox/virtualboxclient"
     8  	"github.com/solo-io/unik/pkg/types"
     9  	unikutil "github.com/solo-io/unik/pkg/util"
    10  	"os"
    11  	"strings"
    12  	"time"
    13  )
    14  
    15  func (p *VirtualboxProvider) syncState() error {
    16  	if len(p.state.GetInstances()) < 1 {
    17  		return nil
    18  	}
    19  	for _, instance := range p.state.GetInstances() {
    20  		vm, err := virtualboxclient.GetVm(instance.Name)
    21  		if err != nil {
    22  			if strings.Contains(err.Error(), "Could not find a registered machine") {
    23  				logrus.Warnf("instance found in state that is no longer registered to Virtualbox")
    24  				os.RemoveAll(getInstanceDir(instance.Name))
    25  				p.state.RemoveInstance(instance)
    26  				continue
    27  			}
    28  			return errors.New("retrieving vm for instance id "+instance.Name, err)
    29  		}
    30  		macAddr := vm.MACAddr
    31  
    32  		if vm.Running {
    33  			instance.State = types.InstanceState_Running
    34  		} else {
    35  			instance.State = types.InstanceState_Stopped
    36  		}
    37  
    38  		var ipAddress string
    39  		unikutil.Retry(3, time.Duration(500*time.Millisecond), func() error {
    40  			if instance.Name == VboxUnikInstanceListener {
    41  				ipAddress = p.instanceListenerIp
    42  			} else {
    43  				var err error
    44  				ipAddress, err = common.GetInstanceIp(p.instanceListenerIp, 3000, macAddr)
    45  				if err != nil {
    46  					return err
    47  				}
    48  			}
    49  			return nil
    50  		})
    51  
    52  		if err := p.state.ModifyInstances(func(instances map[string]*types.Instance) error {
    53  			if _, ok := instances[instance.Id]; ok {
    54  				instances[instance.Id].IpAddress = ipAddress
    55  				instances[instance.Id].State = instance.State
    56  			}
    57  			return nil
    58  		}); err != nil {
    59  			return err
    60  		}
    61  	}
    62  	return nil
    63  }