github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/pkg/providers/vsphere/sync_state.go (about) 1 package vsphere 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/vsphere/vsphereclient" 8 "github.com/solo-io/unik/pkg/types" 9 unikutil "github.com/solo-io/unik/pkg/util" 10 "time" 11 ) 12 13 func (p *VsphereProvider) syncState() error { 14 if len(p.state.GetInstances()) < 1 { 15 return nil 16 } 17 c := p.getClient() 18 vms := []*vsphereclient.VirtualMachine{} 19 for instanceId := range p.state.GetInstances() { 20 vm, err := c.GetVmByUuid(instanceId) 21 if err != nil { 22 return errors.New("getting vm info for "+instanceId, err) 23 } 24 vms = append(vms, vm) 25 } 26 for _, vm := range vms { 27 //we use mac address as the vm id 28 macAddr := "" 29 for _, device := range vm.Config.Hardware.Device { 30 if len(device.MacAddress) > 0 { 31 macAddr = device.MacAddress 32 break 33 } 34 } 35 if macAddr == "" { 36 logrus.WithFields(logrus.Fields{"vm": vm}).Warnf("vm found, cannot identify mac addr") 37 continue 38 } 39 40 instanceId := vm.Config.UUID 41 instance, ok := p.state.GetInstances()[instanceId] 42 if !ok { 43 continue 44 } 45 46 switch vm.Summary.Runtime.PowerState { 47 case "poweredOn": 48 instance.State = types.InstanceState_Running 49 break 50 case "poweredOff": 51 case "suspended": 52 instance.State = types.InstanceState_Stopped 53 break 54 default: 55 instance.State = types.InstanceState_Unknown 56 break 57 } 58 59 var ipAddress string 60 unikutil.Retry(3, time.Duration(500*time.Millisecond), func() error { 61 if instance.Name == VsphereUnikInstanceListener { 62 ipAddress = p.instanceListenerIp 63 } else { 64 var err error 65 ipAddress, err = common.GetInstanceIp(p.instanceListenerIp, 3000, macAddr) 66 if err != nil { 67 return err 68 } 69 } 70 return nil 71 }) 72 73 if err := p.state.ModifyInstances(func(instances map[string]*types.Instance) error { 74 if _, ok := instances[instance.Id]; ok { 75 instances[instance.Id].IpAddress = ipAddress 76 instances[instance.Id].State = instance.State 77 } 78 return nil 79 }); err != nil { 80 return err 81 } 82 } 83 return nil 84 }