Check network adapter type if it's supported by the guest OS
559257
private static VirtualNetworkAdapterType validateNicType(GuestOsDescriptor[] guestOsDescriptorList,
                                                             String guestId, VirtualNetworkAdapterType adapterType) throws DeviceNotSupported {
        VirtualNetworkAdapterType result = adapterType;

        GuestOsDescriptor guestOsInfo = null;

        for (GuestOsDescriptor desc : guestOsDescriptorList) {
            if (desc.getId().equalsIgnoreCase(guestId)) {
                guestOsInfo = desc;
                break;
            }
        }

        if (adapterType == VirtualNetworkAdapterType.Unknown) {
            result = TryGetNetworkAdapterType(guestOsInfo);
        }
        else {
            if (guestOsInfo.getSupportedEthernetCard() != null) {
                boolean supported = false;
                List<String> supportedTypeList = new ArrayList<String>();

                for (String supportedAdapterName : guestOsInfo.getSupportedEthernetCard()) {
                    VirtualNetworkAdapterType supportedAdapterType = GetNetworkAdapterTypeByApiType(supportedAdapterName);
                    supportedTypeList.add(supportedAdapterType.toString());

                    if (supportedAdapterType == adapterType) {
                        supported = true;
                        break;
                    }
                }

                if (!supported) {
                    DeviceNotSupported dns = new DeviceNotSupported();
                    dns.setDevice("Virtual NIC");
                    dns.setReason("The requested NIC is not supported in this OS.");
                    throw dns;
                }
            }
        }
        return result;
    }
963009
public static boolean isHostInNetworkCard(String host) {
        try {
            InetAddress addr = InetAddress.getByName(host);
            return NetworkInterface.getByInetAddress(addr) != null;
        } catch (Exception e) {
            return false;
        }
    }
227284
def _ifconfig_getnode():
    """"""

    # This works on Linux ('' or '-a'), Tru64 ('-av'), but not all Unixes.
    for args in ('', '-a', '-av'):
        mac = _find_mac('ifconfig', args, ['hwaddr', 'ether'], lambda i: i+1)
        if mac:
            return mac

    import socket
    ip_addr = socket.gethostbyname(socket.gethostname())

    # Try getting the MAC addr from arp based on our IP address (Solaris).
    mac = _find_mac('arp', '-an', [ip_addr], lambda i: -1)
    if mac:
        return mac

    # This might work on HP-UX.
    mac = _find_mac('lanscan', '-ai', ['lan0'], lambda i: 0)
    if mac:
        return mac

    return None
983666
def _get_interface_info(interface):
    '''
    
    '''
    adapter_mode = _get_adapter_mode_info(interface.name)
    if adapter_mode == 'disabled':
        return _get_base_interface_info(interface)
    elif adapter_mode == 'ethercat':
        return _get_ethercat_interface_info(interface)
    return _get_tcpip_interface_info(interface)
176368
def interface_by_macaddr(self, macaddr):
        '''
        
        '''
        macaddr = EthAddr(macaddr)
        for devname,iface in self._devinfo.items():
            if iface.ethaddr == macaddr:
                return iface
        raise KeyError("No device has MAC address {}".format(macaddr))
885634
def create_network(userid, os_version, network_info):
    
    print("\nConfiguring network interface for %s ..." % userid)
    network_create_info = client.send_request('guest_create_network_interface', 
                                              userid, os_version, network_info)

    if network_create_info['overallRC']:
        raise RuntimeError("Failed to create network for guest %s!\n%s" % 
                           (userid, network_create_info))
    else:
        print("Succeeded to create network for guest %s!" % userid)
1368307
def _look_for_vboxnet(self, interface_number):
        

        result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"])
        for info in result.splitlines():
            if '=' in info:
                name, value = info.split('=', 1)
                if name == "hostonlyadapter{}".format(interface_number):
                    return value.strip('"')
        return None
103863
def get_addr(iface='lo0', iface_type='link'):
    
    if platform.system() in ['Darwin', 'Linux']:
        if iface_type == 'link':
            _AF_FAMILY = psutil.AF_LINK
        elif iface_type in ['inet', 'inet6']:
            _AF_FAMILY = getattr(socket, 'AF_{}'.format(iface_type.upper()))
        else:
            raise SystemError('Not valid address FAMILY')
    else:
        raise SystemExit('Unsupported System. Only Mac/Linux Supported')

    addrs = psutil.net_if_addrs()
    for n in addrs[iface]:
        if n.family == _AF_FAMILY:
            return n.address
192270
def modify_adapter
      parent_machine.with_open_session do |session|
        machine = session.machine
        yield machine.get_network_adapter(slot)
      end
    end
362676
def _map_device_on_host_networks(provider_nets, devices):
    """"""
    networks = copy.deepcopy(provider_nets)
    for network in networks:
        for device in devices:
            network.setdefault('device', None)
            ip_set = IPSet([network['cidr']])
            if 'ipv4' not in device:
                continue
            ips = device['ipv4']
            if not isinstance(ips, list):
                ips = [ips]
            if len(ips) < 1:
                continue
            ip = IPAddress(ips[0]['address'])
            if ip in ip_set:
                network['device'] = device['device']
                continue
    return networks
80421
def _port_action_vlan(self, port, segment, func, vni):
        """"""

        # Verify segment.
        if not self._is_valid_segment(segment):
            return

        device_id = self._get_port_uuid(port)

        if nexus_help.is_baremetal(port):
            host_id = port.get('dns_name')
        else:
            host_id = port.get(bc.portbindings.HOST_ID)

        vlan_id = segment.get(api.SEGMENTATION_ID)
        is_provider = nxos_db.is_provider_vlan(vlan_id)

        settings = {"vlan_id": vlan_id,
                    "device_id": device_id,
                    "host_id": host_id}
        missing_fields = [field for field, value in settings.items()
                          if (field != 'host_id' and not value)]
        if not missing_fields:
            func(port, vlan_id, device_id, host_id, vni, is_provider)
        else:
            raise excep.NexusMissingRequiredFields(
                fields=' '.join(missing_fields))
111187
def _interfaces_ipconfig(out):
    '''
    
    '''
    ifaces = dict()
    iface = None
    adapter_iface_regex = re.compile(r'adapter (\S.+):$')

    for line in out.splitlines():
        if not line:
            continue
        # TODO what does Windows call Infiniband and 10/40gige adapters
        if line.startswith('Ethernet'):
            iface = ifaces[adapter_iface_regex.search(line).group(1)]
            iface['up'] = True
            addr = None
            continue
        if iface:
            key, val = line.split(',', 1)
            key = key.strip(' .')
            val = val.strip()
            if addr and key == 'Subnet Mask':
                addr['netmask'] = val
            elif key in ('IP Address', 'IPv4 Address'):
                if 'inet' not in iface:
                    iface['inet'] = list()
                addr = {'address': val.rstrip('(Preferred)'),
                        'netmask': None,
                        'broadcast': None}  # TODO find the broadcast
                iface['inet'].append(addr)
            elif 'IPv6 Address' in key:
                if 'inet6' not in iface:
                    iface['inet'] = list()
                # XXX What is the prefixlen!?
                addr = {'address': val.rstrip('(Preferred)'),
                        'prefixlen': None}
                iface['inet6'].append(addr)
            elif key == 'Physical Address':
                iface['hwaddr'] = val
            elif key == 'Media State':
                # XXX seen used for tunnel adaptors
                # might be useful
                iface['up'] = (val != 'Media disconnected')
12225
def adapter_type(self, adapter_type):
        

        self._adapter_type = adapter_type
        log.info("VMware VM '{name}' [{id}]: adapter type changed to {adapter_type}".format(name=self.name,
                                                                                            id=self.id,
                                                                                            adapter_type=adapter_type))
129896
def DbGetExportdDeviceListForClass(self, argin):
        
        self._log.debug("In DbGetExportdDeviceListForClass()")
        argin = replace_wildcard(argin)
        return self.db.get_exported_device_list_for_class(argin)
19996
def _get_nics(dom):
    '''
    
    '''
    nics = {}
    doc = ElementTree.fromstring(dom.XMLDesc(0))
    for iface_node in doc.findall('devices/interface'):
        nic = {}
        nic['type'] = iface_node.get('type')
        for v_node in iface_node:
            if v_node.tag == 'mac':
                nic['mac'] = v_node.get('address')
            if v_node.tag == 'model':
                nic['model'] = v_node.get('type')
            if v_node.tag == 'target':
                nic['target'] = v_node.get('dev')
            # driver, source, and match can all have optional attributes
            if re.match('(driver|source|address)', v_node.tag):
                temp = {}
                for key, value in six.iteritems(v_node.attrib):
                    temp[key] = value
                nic[v_node.tag] = temp
            # virtualport needs to be handled separately, to pick up the
            # type attribute of the virtualport itself
            if v_node.tag == 'virtualport':
                temp = {}
                temp['type'] = v_node.get('type')
                for key, value in six.iteritems(v_node.attrib):
                    temp[key] = value
                nic['virtualport'] = temp
        if 'mac' not in nic:
            continue
        nics[nic['mac']] = nic
    return nics
848276
def device_info(self):
        
        # get hostname, model, and version from 'show version'
        resp = self._session.get_software_information(format='xml')

        hostname = resp.xpath('//software-information/host-name')[0].text
        model = resp.xpath('//software-information/product-model')[0].text

        version = 'Unknown'
        if resp.xpath('//junos-version'):
            """ case:
                <junos-version>15.1</junos-version>
            """
            try:
                version = resp.xpath('//junos-version')[0].text
            except IndexError:
                pass
        elif resp.xpath("//package-information[name = 'junos-version']"):
            """ case:
                <package-information>
                    <name>junos-version</name>
                    <comment>Junos: 14.2R4</comment>
                </package-information>
           """
            try:
                version = (resp.xpath(
                    "//package-information[name = 'junos-version']/comment"
                    )[0].text).split()[1]
            except IndexError:
                pass
        else:
            """ case:
                <package-information>
                    <name>junos</name>
                    <comment>JUNOS Base OS boot [12.3R5]</comment>
                </package-information>
            """
            try:
                version = ((resp.xpath(
                    '//software-information/package-information/comment'
                    )[0].text.split('[')[1].split(']')[0]))
            except IndexError:
                pass

        # try looking for 'junos-version' for >= 14.2
#        for element in resp.xpath('//software-information'):
#            version = element.findtext('junos-version')

#        if not version:
#            try:
#                version = ((resp.xpath(
#                    '//software-information/package-information/comment')
#                    [0].text.split('[')[1].split(']')[0]))
#            except IndexError:
#                version = 'Unknown'

        # get uptime from 'show system uptime'
        resp = self._session.get_system_uptime_information(format='xml')
        try:
            current_time = resp.xpath('//current-time/date-time')[0].text
        except IndexError:
            current_time = 'Unknown'
        try:
            uptime = resp.xpath('//uptime-information/up-time')[0].text
        except IndexError:
            uptime = 'Unknown'
        # get serial number from 'show chassis hardware'
        show_hardware = self._session.get_chassis_inventory(format='xml')
        # If we're hitting an EX, grab each Routing Engine Serial number
        # to get all RE SNs in a VC
        try:
            chassis_module = show_hardware.xpath(
                '//chassis-inventory/chassis/chassis-module/description'
                )[0].text
        except IndexError:
            chassis_module = 'Unknown'

        if ('EX' or 'ex' or 'Ex') in chassis_module:
            serial_num = ''
            for eng in show_hardware.xpath(
                    '//chassis-inventory/chassis/chassis-module'):
                if 'Routing Engine' in eng.xpath('name')[0].text:
                    serial_num += (eng.xpath('name')[0].text + ' Serial #: ' +
                                   eng.xpath('serial-number')[0].text)
        else:  # Any other device type, just grab chassis SN
            try:
                serial_num = ('Chassis Serial Number: ' + show_hardware.xpath(
                    '//chassis-inventory/chassis/serial-number')[0].text)
            except IndexError:
                serial_num = 'Chassis Serial Number: ' \
                    + 'Unknown (virtual machine?)'
        return ('Hostname: %s\nModel: %s\nJunos Version: %s\n%s\nCurrent Time:'
                ' %s\nUptime: %s\n' %
                (hostname, model, version, serial_num, current_time, uptime))
982506
def device_info(self):
        """"""
        return {
            'connections': {('mac', self.device['device_mac'])},
            'identifieres': self.device['device_id'],
            'manufacturer': 'Minut',
            'model': 'Point v{}'.format(self.device['hardware_version']),
            'name': self.device['description'],
            'sw_version': self.device['firmware']['installed'],
        }