// getNodeVMSet gets the VMSet interface based on config.VMType and the real virtual machine type.
769690
func (c *controllerCommon) getNodeVMSet(nodeName types.NodeName) (VMSet, error) {
	// 1. vmType is standard, return cloud.vmSet directly.
	if c.cloud.VMType == vmTypeStandard {
		return c.cloud.vmSet, nil
	}

	// 2. vmType is Virtual Machine Scale Set (vmss), convert vmSet to scaleSet.
	ss, ok := c.cloud.vmSet.(*scaleSet)
	if !ok {
		return nil, fmt.Errorf("error of converting vmSet (%q) to scaleSet with vmType %q", c.cloud.vmSet, c.cloud.VMType)
	}

	// 3. If the node is managed by availability set, then return ss.availabilitySet.
	managedByAS, err := ss.isNodeManagedByAvailabilitySet(mapNodeNameToVMName(nodeName))
	if err != nil {
		return nil, err
	}
	if managedByAS {
		// vm is managed by availability set.
		return ss.availabilitySet, nil
	}

	// 4. Node is managed by vmss
	return ss, nil
}
350996
func getVMsServer(c context.Context) gce.ConfigurationServer {
	return c.Value(&vmsKey).(gce.ConfigurationServer)
}
973577
func (ss *scaleSet) GetPrimaryInterface(nodeName string) (network.Interface, error) {
	managedByAS, err := ss.isNodeManagedByAvailabilitySet(nodeName)
	if err != nil {
		klog.Errorf("Failed to check isNodeManagedByAvailabilitySet: %v", err)
		return network.Interface{}, err
	}
	if managedByAS {
		// vm is managed by availability set.
		return ss.availabilitySet.GetPrimaryInterface(nodeName)
	}

	ssName, instanceID, vm, err := ss.getVmssVM(nodeName)
	if err != nil {
		// VM is availability set, but not cached yet in availabilitySetNodesCache.
		if err == ErrorNotVmssInstance {
			return ss.availabilitySet.GetPrimaryInterface(nodeName)
		}

		klog.Errorf("error: ss.GetPrimaryInterface(%s), ss.getVmssVM(%s), err=%v", nodeName, nodeName, err)
		return network.Interface{}, err
	}

	primaryInterfaceID, err := ss.getPrimaryInterfaceID(vm)
	if err != nil {
		klog.Errorf("error: ss.GetPrimaryInterface(%s), ss.getPrimaryInterfaceID(), err=%v", nodeName, err)
		return network.Interface{}, err
	}

	nicName, err := getLastSegment(primaryInterfaceID)
	if err != nil {
		klog.Errorf("error: ss.GetPrimaryInterface(%s), getLastSegment(%s), err=%v", nodeName, primaryInterfaceID, err)
		return network.Interface{}, err
	}
	resourceGroup, err := extractResourceGroupByVMSSNicID(primaryInterfaceID)
	if err != nil {
		return network.Interface{}, err
	}

	ctx, cancel := getContextWithCancel()
	defer cancel()
	nic, err := ss.InterfacesClient.GetVirtualMachineScaleSetNetworkInterface(ctx, resourceGroup, ssName, instanceID, nicName, "")
	if err != nil {
		klog.Errorf("error: ss.GetPrimaryInterface(%s), ss.GetVirtualMachineScaleSetNetworkInterface.Get(%s, %s, %s), err=%v", nodeName, resourceGroup, ssName, nicName, err)
		return network.Interface{}, err
	}

	// Fix interface's location, which is required when updating the interface.
	// TODO: is this a bug of azure SDK?
	if nic.Location == nil || *nic.Location == "" {
		nic.Location = vm.Location
	}

	return nic, nil
}
1111042
func getVMIDbyIP(pc *PCCloud, IPAddress string) (string, error) {
	photonClient, err := getPhotonClient(pc)
	if err != nil {
		klog.Errorf("Photon Cloud Provider: Failed to get photon client for getVMIDbyNodename, error: [%v]", err)
		return "", err
	}

	vmList, err := photonClient.Projects.GetVMs(pc.projID, nil)
	if err != nil {
		klog.Errorf("Photon Cloud Provider: Failed to GetVMs for project %s. error: [%v]", pc.projID, err)
		return "", err
	}

	for _, vm := range vmList.Items {
		task, err := photonClient.VMs.GetNetworks(vm.ID)
		if err != nil {
			klog.Warningf("Photon Cloud Provider: GetNetworks failed for vm.ID %s, error [%v]", vm.ID, err)
		} else {
			task, err = photonClient.Tasks.Wait(task.ID)
			if err != nil {
				klog.Warningf("Photon Cloud Provider: Wait task for GetNetworks failed for vm.ID %s, error [%v]", vm.ID, err)
			} else {
				networkConnections := task.ResourceProperties.(map[string]interface{})
				networks := networkConnections["networkConnections"].([]interface{})
				for _, nt := range networks {
					network := nt.(map[string]interface{})
					if val, ok := network["ipAddress"]; ok && val != nil {
						ipAddr := val.(string)
						if ipAddr == IPAddress {
							return vm.ID, nil
						}
					}
				}
			}
		}
	}

	return "", fmt.Errorf("No matching VM is found with IP %s", IPAddress)
}
1090747
func (as *availabilitySet) GetZoneByNodeName(name string) (cloudprovider.Zone, error) {
	vm, err := as.getVirtualMachine(types.NodeName(name))
	if err != nil {
		return cloudprovider.Zone{}, err
	}

	var failureDomain string
	if vm.Zones != nil && len(*vm.Zones) > 0 {
		// Get availability zone for the node.
		zones := *vm.Zones
		zoneID, err := strconv.Atoi(zones[0])
		if err != nil {
			return cloudprovider.Zone{}, fmt.Errorf("failed to parse zone %q: %v", zones, err)
		}

		failureDomain = as.makeZone(zoneID)
	} else {
		// Availability zone is not used for the node, falling back to fault domain.
		failureDomain = strconv.Itoa(int(*vm.VirtualMachineProperties.InstanceView.PlatformFaultDomain))
	}

	zone := cloudprovider.Zone{
		FailureDomain: failureDomain,
		Region:        *(vm.Location),
	}
	return zone, nil
}
446802
func GetVHost(conn client.Connection, key VHostKey) (string, string, error) {
	pth := path.Join("/net/vhost", key.HostID, key.Subdomain)

	logger := plog.WithFields(log.Fields{
		"hostid":    key.HostID,
		"subdomain": key.Subdomain,
		"zkpath":    pth,
	})

	vhost := &VHost{}
	err := conn.Get(pth, vhost)
	if err == client.ErrNoNode {
		logger.WithError(err).Debug("Virtual host subdomain not found")
		return "", "", nil
	} else if err != nil {
		logger.WithError(err).Debug("Could not look up virtual host subdomain")
		return "", "", &RegistryError{
			Action:  "get",
			Path:    pth,
			Message: "could not look up virtual host subdomain",
		}
	}

	logger.WithFields(log.Fields{
		"tenantid":    vhost.TenantID,
		"application": vhost.Application,
	}).Debug("Found vhost subdomain")

	return vhost.ServiceID, vhost.Application, nil
}
1095674
func (ss *scaleSet) getVmssVMByInstanceID(resourceGroup, scaleSetName, instanceID string) (vm compute.VirtualMachineScaleSetVM, err error) {
	vmName := ss.makeVmssVMName(scaleSetName, instanceID)
	key := buildVmssCacheKey(resourceGroup, vmName)
	cachedVM, err := ss.vmssVMCache.Get(key)
	if err != nil {
		return vm, err
	}

	if cachedVM == nil {
		klog.Errorf("couldn't find vmss virtual machine by scaleSetName (%s) and instanceID (%s)", scaleSetName, instanceID)
		return vm, cloudprovider.InstanceNotFound
	}

	return *(cachedVM.(*compute.VirtualMachineScaleSetVM)), nil
}
605532
func (c *Client) GetDeploymentVMs(name string) ([]VM, error) {
	var task Task
	r := c.NewRequest("GET", "/deployments/"+name+"/vms?format=full")
	resp, err := c.DoRequest(r)

	if err != nil {
		log.Printf("Error requesting deployment vms %v", err)
		return nil, err
	}
	defer resp.Body.Close()

	resBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Printf("Error reading deployment vms request %v", resBody)
		return nil, err
	}
	err = json.Unmarshal(resBody, &task)
	if err != nil {
		log.Printf("Error unmarshaling tasks %v", err)
		return nil, err
	}
	for {
		taskStatus, err := c.GetTask(task.ID)
		if err != nil {
			log.Printf("Error getting task %v", err)
		}
		if taskStatus.State == "done" {
			break
		}
		time.Sleep(1 * time.Second)
	}

	vms := []VM{}
	output := c.GetTaskResult(task.ID)
	for _, value := range output {
		if len(value) > 0 {
			var vm VM
			err = json.Unmarshal([]byte(value), &vm)
			if err != nil {
				log.Printf("Error unmarshaling vms %v %v", value, err)
				return nil, err
			}
			vms = append(vms, vm)
		}
	}
	return vms, err
}
1219901
func (_class VUSBClass) GetVM(sessionID SessionRef, self VUSBRef) (_retval VMRef, _err error) {
	_method := "VUSB.get_VM"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertVUSBRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)
	if _err != nil {
		return
	}
	_retval, _err = convertVMRefToGo(_method + " -> ", _result.Value)
	return
}
948097
func (r Network_Monitor) GetIpAddressesByVirtualGuest(guest *datatypes.Virtual_Guest, partialIpAddress *string) (resp []datatypes.Network_Subnet_IpAddress, err error) {
	params := []interface{}{
		guest,
		partialIpAddress,
	}
	err = r.Session.DoRequest("SoftLayer_Network_Monitor", "getIpAddressesByVirtualGuest", params, &r.Options, &resp)
	return
}
926918
func (i ImportBinding) GetVirtualAddress(instanceID int) (string, error) {
	t := template.Must(template.New(i.Application).Funcs(funcs).Parse(i.VirtualAddress))

	var buffer bytes.Buffer
	if err := t.Execute(&buffer, struct{ InstanceID int }{instanceID}); err != nil {
		return "", &TemplateError{
			Application: i.Application,
			Field:       i.VirtualAddress,
			Message:     "could not interpret value",
		}
	}

	return buffer.String(), nil
}
52601
func (ss *scaleSet) GetInstanceTypeByNodeName(name string) (string, error) {
	managedByAS, err := ss.isNodeManagedByAvailabilitySet(name)
	if err != nil {
		klog.Errorf("Failed to check isNodeManagedByAvailabilitySet: %v", err)
		return "", err
	}
	if managedByAS {
		// vm is managed by availability set.
		return ss.availabilitySet.GetInstanceTypeByNodeName(name)
	}

	_, _, vm, err := ss.getVmssVM(name)
	if err != nil {
		return "", err
	}

	if vm.Sku != nil && vm.Sku.Name != nil {
		return *vm.Sku.Name, nil
	}

	return "", nil
}
978049
func (s *Service) GetVirtualHost(application, vhostName string) *servicedefinition.VHost {
	if s.Endpoints != nil {
		//find the matching endpoint
		for i := range s.Endpoints {
			ep := &s.Endpoints[i]

			if ep.Application == application && ep.Purpose == "export" {
				vhostNameLower := strings.ToLower(vhostName)
				for _, vhost := range ep.VHostList {
					if strings.ToLower(vhost.Name) == vhostNameLower {
						return &vhost
					}
				}
			}
		}
	}

	return nil
}
740315
func (s *SimAdapter) GetNode(id enode.ID) (*SimNode, bool) {
	s.mtx.RLock()
	defer s.mtx.RUnlock()
	node, ok := s.nodes[id]
	return node, ok
}
1002453
func (vm *VM) getNetworkInterfaces() []*compute.NetworkInterface {
	if len(vm.Attributes.GetNetworkInterface()) == 0 {
		return nil
	}
	nics := make([]*compute.NetworkInterface, len(vm.Attributes.NetworkInterface))
	for i, nic := range vm.Attributes.NetworkInterface {
		nics[i] = &compute.NetworkInterface{
			Network: nic.Network,
		}
		if len(nic.GetAccessConfig()) > 0 {
			nics[i].AccessConfigs = make([]*compute.AccessConfig, len(nic.AccessConfig))
			for j, cfg := range nic.AccessConfig {
				nics[i].AccessConfigs[j] = &compute.AccessConfig{
					Type: cfg.Type.String(),
				}
			}
		}
	}
	return nics
}
1180893
func (d *Domain) GetMetadata(tipus DomainMetadataType, uri string, flags DomainModificationImpact) (string, error) {
	var cUri *C.char
	if uri != "" {
		cUri = C.CString(uri)
		defer C.free(unsafe.Pointer(cUri))
	}

	var err C.virError
	result := C.virDomainGetMetadataWrapper(d.ptr, C.int(tipus), cUri, C.uint(flags), &err)
	if result == nil {
		return "", makeError(&err)

	}
	defer C.free(unsafe.Pointer(result))
	return C.GoString(result), nil
}
957883
func (d *Domain) GetVcpus() ([]DomainVcpuInfo, error) {
	var cnodeinfo C.virNodeInfo
	var err C.virError
	ret := C.virNodeGetInfoWrapper(C.virDomainGetConnect(d.ptr), &cnodeinfo, &err)
	if ret == -1 {
		return []DomainVcpuInfo{}, makeError(&err)
	}

	var cdominfo C.virDomainInfo
	ret = C.virDomainGetInfoWrapper(d.ptr, &cdominfo, &err)
	if ret == -1 {
		return []DomainVcpuInfo{}, makeError(&err)
	}

	nvcpus := int(cdominfo.nrVirtCpu)
	npcpus := int(cnodeinfo.nodes * cnodeinfo.sockets * cnodeinfo.cores * cnodeinfo.threads)
	maplen := ((npcpus + 7) / 8)
	ccpumaps := make([]C.uchar, maplen*nvcpus)
	cinfo := make([]C.virVcpuInfo, nvcpus)

	ret = C.virDomainGetVcpusWrapper(d.ptr, &cinfo[0], C.int(nvcpus), &ccpumaps[0], C.int(maplen), &err)
	if ret == -1 {
		return []DomainVcpuInfo{}, makeError(&err)
	}

	info := make([]DomainVcpuInfo, int(ret))
	for i := 0; i < int(ret); i++ {
		affinity := make([]bool, npcpus)
		for j := 0; j < npcpus; j++ {
			byte := (i * maplen) + (j / 8)
			bit := j % 8

			affinity[j] = (ccpumaps[byte] & (1 << uint(bit))) != 0
		}

		info[i] = DomainVcpuInfo{
			Number:  uint32(cinfo[i].number),
			State:   int32(cinfo[i].state),
			CpuTime: uint64(cinfo[i].cpuTime),
			Cpu:     int32(cinfo[i].cpu),
			CpuMap:  affinity,
		}
	}

	return info, nil
}