Validate if vDS Portgroup can be bound to vnic
436942
private void validateDVPortGroupForVNicConnection(DistributedVirtualPortgroupInfo dvPortgroupInfo) {
        if (dvPortgroupInfo.uplinkPortgroup) {
            throw new RuntimeException("The vDS portgroup's uplinkPortgroup should not be null");
        }

        DistributedVirtualPortgroupPortgroupType portgroupType = DistributedVirtualPortgroupPortgroupType.valueOf(dvPortgroupInfo.portgroupType);

        String prodLineId = vm.getServerConnection().getServiceInstance().getAboutInfo().getProductLineId();
        // standalone host cannot do early or late binding
        if (prodLineId.indexOf("ESX") != -1 &&
            (portgroupType == DistributedVirtualPortgroupPortgroupType.earlyBinding ||
                portgroupType == DistributedVirtualPortgroupPortgroupType.lateBinding)) {
            throw new RuntimeException("ESX does not support early or late binding!");
        }
    }
135982
def update_dvportgroup(portgroup_ref, spec):
    '''
    
    '''
    pg_name = get_managed_object_name(portgroup_ref)
    log.trace('Updating portgrouo %s', pg_name)
    try:
        task = portgroup_ref.ReconfigureDVPortgroup_Task(spec)
    except vim.fault.NoPermission as exc:
        log.exception(exc)
        raise salt.exceptions.VMwareApiError(
            'Not enough permissions. Required privilege: '
            '{0}'.format(exc.privilegeId))
    except vim.fault.VimFault as exc:
        log.exception(exc)
        raise salt.exceptions.VMwareApiError(exc.msg)
    except vmodl.RuntimeFault as exc:
        log.exception(exc)
        raise salt.exceptions.VMwareRuntimeError(exc.msg)
    wait_for_task(task, pg_name, six.text_type(task.__class__))
564925
def filter_by_vnic_type(query, vnic_type):
    """"""
    port_model = models_v2.Port
    binding_model = ml2_models.PortBinding
    dst_binding_model = ml2_models.DistributedPortBinding
    query = (query
             .outerjoin_if_necessary(
                 binding_model,
                 port_model.id == binding_model.port_id)
             .outerjoin_if_necessary(
                 dst_binding_model,
                 port_model.id == dst_binding_model.port_id)
             .filter(
                 (binding_model.vnic_type == vnic_type) |
                 (dst_binding_model.vnic_type == vnic_type)))
    return query
1123729
def get_device_spec(vnic, set_connected):
        
        nic_spec = VNicService.create_vnic_spec(vnic)
        VNicService.set_vnic_connectivity_status(nic_spec, to_connect=set_connected)
        return nic_spec
826726
def _port_action_vxlan(self, port, segment, func):
        """"""

        # If the segment is None, just log a warning message and return.
        if segment is None:
            self._log_missing_segment()
            return

        device_id = port.get('device_id')
        mcast_group = segment.get(api.PHYSICAL_NETWORK)
        host_id = port.get(bc.portbindings.HOST_ID)
        vni = segment.get(api.SEGMENTATION_ID)

        if vni and device_id and mcast_group and host_id:
            func(vni, device_id, mcast_group, host_id)
            return vni
        else:
            fields = "vni " if not vni else ""
            fields += "device_id " if not device_id else ""
            fields += "mcast_group " if not mcast_group else ""
            fields += "host_id" if not host_id else ""
            raise excep.NexusMissingRequiredFields(fields=fields)
1149368
def _validate(dns_proto, dns_servers, ip_proto, ip_addrs, gateway):
    '''
    
    '''
    errors = []
    # Validate DNS configuration
    if dns_proto == 'dhcp':
        if dns_servers is not None:
            errors.append(
                'The dns_servers param cannot be set if unless dns_proto is '
                'set to \'static\''
            )
    else:
        if str(dns_servers).lower() in ['none', '[]']:
            pass
        elif not isinstance(dns_servers, list):
            errors.append(
                'The dns_servers param must be formatted as a list'
            )
        else:
            bad_ips = [x for x in dns_servers
                       if not salt.utils.validate.net.ipv4_addr(x)]
            if bad_ips:
                errors.append('Invalid DNS server IPs: {0}'
                              .format(', '.join(bad_ips)))

    # Validate IP configuration
    if ip_proto == 'dhcp':
        if ip_addrs is not None:
            errors.append(
                'The ip_addrs param cannot be set if unless ip_proto is set '
                'to \'static\''
            )
        if gateway is not None:
            errors.append(
                'A gateway IP cannot be set if unless ip_proto is set to '
                '\'static\''
            )
    else:
        if not ip_addrs:
            errors.append(
                'The ip_addrs param is required to set static IPs'
            )
        elif not isinstance(ip_addrs, list):
            errors.append(
                'The ip_addrs param must be formatted as a list'
            )
        else:
            bad_ips = [x for x in ip_addrs
                       if not salt.utils.validate.net.ipv4_addr(x)]
            if bad_ips:
                errors.append('The following static IPs are invalid: '
                              '{0}'.format(', '.join(bad_ips)))

            # Validate default gateway
            if gateway is not None:
                if not salt.utils.validate.net.ipv4_addr(gateway):
                    errors.append('Gateway IP {0} is invalid'.format(gateway))

    return errors
619124
def cli(env, identifier, domain, userfile, tag, hostname, userdata,
        public_speed, private_speed):
    """"""

    if userdata and userfile:
        raise exceptions.ArgumentError(
            '[-u | --userdata] not allowed with [-F | --userfile]')

    data = {}

    if userdata:
        data['userdata'] = userdata
    elif userfile:
        with open(userfile, 'r') as userfile_obj:
            data['userdata'] = userfile_obj.read()

    data['hostname'] = hostname
    data['domain'] = domain

    if tag:
        data['tags'] = ','.join(tag)

    vsi = SoftLayer.VSManager(env.client)
    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
    if not vsi.edit(vs_id, **data):
        raise exceptions.CLIAbort("Failed to update virtual server")

    if public_speed is not None:
        vsi.change_port_speed(vs_id, True, int(public_speed))

    if private_speed is not None:
        vsi.change_port_speed(vs_id, False, int(private_speed))
1236923
def _port_bound(self, port_id, network_id, network_type, physical_network,
                    segmentation_id, port_security_enabled, set_port_sriov):
        """"""
        super(HyperVNeutronAgent, self)._port_bound(
            port_id, network_id, network_type, physical_network,
            segmentation_id, port_security_enabled, set_port_sriov
        )
        vswitch_map = self._network_vswitch_map[network_id]

        if network_type == h_constant.TYPE_VLAN:
            self._vlan_driver.bind_vlan_port(port_id, segmentation_id)
        elif network_type == h_constant.TYPE_NVGRE and self._nvgre_enabled:
            self._nvgre_ops.bind_nvgre_port(
                segmentation_id, vswitch_map['vswitch_name'], port_id)
        elif network_type == h_constant.TYPE_FLAT:
            pass    # Nothing to do
        elif network_type == h_constant.TYPE_LOCAL:
            pass    # Nothing to do
        else:
            LOG.error('Unsupported network type %s', network_type)

        if self._enable_metrics_collection:
            self._utils.add_metrics_collection_acls(port_id)
            self._port_metric_retries[port_id] = self._metrics_max_retries

        # check if security groups is enabled.
        # if not, teardown the security group rules
        if self._enable_security_groups:
            self._sec_groups_agent.refresh_firewall([port_id])
        else:
            self._utils.remove_all_security_rules(port_id)

        self._utils.set_vswitch_port_mac_spoofing(port_id,
                                                  port_security_enabled)
110295
def validate(config):
    '''
    
    '''
    vstatus = True
    vmsg = 'Valid beacon configuration'

    # Configuration for wtmp beacon should be a list of dicts
    if not isinstance(config, list):
        vstatus = False
        vmsg = ('Configuration for wtmp beacon must be a list.')
    else:
        _config = {}
        list(map(_config.update, config))

        if 'users' in _config:
            if not isinstance(_config['users'], dict):
                vstatus = False
                vmsg = ('User configuration for wtmp beacon must '
                        'be a dictionary.')
            else:
                for user in _config['users']:
                    _time_range = _config['users'][user].get('time_range', {})
                    vstatus, vmsg = _validate_time_range(_time_range,
                                                         vstatus,
                                                         vmsg)

            if not vstatus:
                return vstatus, vmsg

        if 'groups' in _config:
            if not isinstance(_config['groups'], dict):
                vstatus = False
                vmsg = ('Group configuration for wtmp beacon must '
                        'be a dictionary.')
            else:
                for group in _config['groups']:
                    _time_range = _config['groups'][group].get('time_range', {})
                    vstatus, vmsg = _validate_time_range(_time_range,
                                                         vstatus,
                                                         vmsg)
            if not vstatus:
                return vstatus, vmsg

        if 'defaults' in _config:
            if not isinstance(_config['defaults'], dict):
                vstatus = False
                vmsg = ('Defaults configuration for wtmp beacon must '
                        'be a dictionary.')
            else:
                _time_range = _config['defaults'].get('time_range', {})
                vstatus, vmsg = _validate_time_range(_time_range,
                                                     vstatus,
                                                     vmsg)
            if not vstatus:
                return vstatus, vmsg

    return vstatus, vmsg
721098
def enable_lldp(self, port_name, is_ncb=True, is_nb=False):
    

    if is_ncb:
        self.run_lldptool(["-L", "-i", port_name, "-g", "ncb",
                           "adminStatus=rxtx"])
    if is_nb:
        self.run_lldptool(["-L", "-i", port_name, "-g", "nb",
                           "adminStatus=rxtx"])
321340
def prepare_router_vm_msg(self, tenant_id, tenant_name, router_id, net_id,
                              subnet_id, seg, status):
        
        max_get_router_info_retry = True
        attempt = 0
        while max_get_router_info_retry:
            port_data = self.os_helper.get_router_port_subnet(subnet_id)
            if port_data is None:
                LOG.error("Unable to get router port data")
                return None
            if port_data.get('binding:host_id') == '':
                time.sleep(3)
                attempt += 1
                if attempt > 3:
                    max_get_router_info_retry = False
                    LOG.error("Unable to get router binding host data, "
                              "Max attempts reached")
            else:
                max_get_router_info_retry = False
        if status is 'up':
            event_type = 'service.vnic.create'
        else:
            event_type = 'service.vnic.delete'
        vnic_data = {'status': status, 'mac': port_data.get('mac_address'),
                     'segid': seg, 'host': port_data.get('binding:host_id')}
        if vnic_data['host'] == '':
            LOG.error("Null host for seg %(seg)s subnet %(subnet)s",
                      {'seg': seg, 'subnet': subnet_id})
            if self.tenant_dict.get(tenant_id).get('host') is None:
                LOG.error("Null host for tenant %(tenant)s seg %(seg)s "
                          "subnet %(subnet)s",
                          {'tenant': tenant_id, 'seg': seg,
                           'subnet': subnet_id})
                return None
            else:
                vnic_data['host'] = self.tenant_dict.get(tenant_id).get('host')
        else:
            self.tenant_dict[tenant_id]['host'] = vnic_data['host']
        vm_ip = port_data.get('fixed_ips')[0].get('ip_address')
        vnic_data.update({'port_id': port_data.get('id'), 'network_id': net_id,
                          'vm_name': 'FW_SRVC_RTR_' + tenant_name,
                          'vm_ip': vm_ip, 'vm_uuid': router_id, 'gw_mac': None,
                          'fwd_mod': 'anycast_gateway'})
        payload = {'service': vnic_data}
        data = (event_type, payload)
        return data
216544
private void registerScannedPorts(int PortType) {
        String[] CandidateDeviceNames;

        logger.fine("scanning device directory " + deviceDirectory + " for ports of type " + PortType);

        if (RXTXVersion.getOsName().equals("Windows CE")) {
            String[] temp
                    = {"COM1:", "COM2:", "COM3:", "COM4:",
                        "COM5:", "COM6:", "COM7:", "COM8:"};
            CandidateDeviceNames = temp;
        } else if (RXTXVersion.getOsName().toLowerCase().indexOf("windows") != -1) {
            String[] temp = new String[259];
            for (int i = 1; i <= 256; i++) {
                temp[i - 1] = "COM" + i;
            }
            for (int i = 1; i <= 3; i++) {
                temp[i + 255] = "LPT" + i;
            }
            CandidateDeviceNames = temp;
        } else if (RXTXVersion.getOsName().equals("Solaris") || RXTXVersion.getOsName().equals("SunOS")) {
            /* Solaris uses a few different ways to identify ports.
             They could be /dev/term/a /dev/term0 /dev/cua/a /dev/cuaa
             the /dev/???/a appears to be on more systems.

             The uucp lock files should not cause problems.
             */
            /*
             File dev = new File( "/dev/term" );
             String deva[] = dev.list();
             dev = new File( "/dev/cua" );
             String devb[] = dev.list();
             String[] temp = new String[ deva.length + devb.length ];
             for(int j =0;j<deva.length;j++)
             deva[j] = "term/" + deva[j];
             for(int j =0;j<devb.length;j++)
             devb[j] = "cua/" + devb[j];
             System.arraycopy( deva, 0, temp, 0, deva.length );
             System.arraycopy( devb, 0, temp,
             deva.length, devb.length );
             if( debug ) {
             for( int j = 0; j< temp.length;j++)
             System.out.println( temp[j] );
             }
             CandidateDeviceNames=temp;
             */

            /*

             ok..  Look the the dirctories representing the port
             kernel driver interface.

             If there are entries there are possibly ports we can
             use and need to enumerate.
             */
            String term[] = new String[2];
            int l = 0;
            File dev = null;

            dev = new File("/dev/term");
            if (dev.list().length > 0) {
                term[l++] = "term/";
            }
            /*
             dev = new File( "/dev/cua0" );
             if( dev.list().length > 0 )
             term[l++] = "cua/";
             */
            String[] temp = new String[l];
            for (l--; l >= 0; l--) {
                temp[l] = term[l];
            }
            CandidateDeviceNames = temp;
        } else {
            File dev = new File(deviceDirectory);
            String[] temp = dev.list();
            CandidateDeviceNames = temp;
        }
        if (CandidateDeviceNames == null) {

            logger.fine("RXTXCommDriver:registerScannedPorts() no Device files to check ");

            return;
        }

        String CandidatePortPrefixes[] = {};
        switch (PortType) {
            case CommPortIdentifier.PORT_SERIAL:

                logger.fine("scanning for serial ports for os " + RXTXVersion.getOsName());

                /*  There are _many_ possible ports that can be used
                 on Linux.  See below in the fake Linux-all-ports  
                 case for a list.  You may add additional ports
                 here but be warned that too many will significantly
                 slow down port enumeration.  Linux 2.6 has udev
                 support which should be faster as only ports the
                 kernel finds should be exposed in /dev

                 See also how to override port enumeration and
                 specifying port in INSTALL.

                 taj
                 */
                if (RXTXVersion.getOsName().equals("Linux")) {
                    String[] Temp = {
                        "ttyS", // linux Serial Ports
                        "ttyAMA", // for Raspberry Pi 2
                        "ttySA", // for the IPAQs
                        "ttyUSB", // for USB frobs
                        "rfcomm", // bluetooth serial device
                        "ttyircomm", // linux IrCommdevices (IrDA serial emu)
                    };
                    CandidatePortPrefixes = Temp;
                } else if (RXTXVersion.getOsName().equals("Linux-all-ports")) {
                    /* if you want to enumerate all ports ~5000
                     possible, then replace the above with this
                     */
                    String[] Temp = {
                        "comx", // linux COMMX synchronous serial card
                        "holter", // custom card for heart monitoring
                        "modem", // linux symbolic link to modem.
                        "rfcomm", // bluetooth serial device
                        "ttyircomm", // linux IrCommdevices (IrDA serial emu)
                        "ttycosa0c", // linux COSA/SRP synchronous serial card
                        "ttycosa1c", // linux COSA/SRP synchronous serial card
                        "ttyACM",// linux CDC ACM devices
                        "ttyC", // linux cyclades cards
                        "ttyCH",// linux Chase Research AT/PCI-Fast serial card
                        "ttyD", // linux Digiboard serial card
                        "ttyE", // linux Stallion serial card
                        "ttyF", // linux Computone IntelliPort serial card
                        "ttyH", // linux Chase serial card
                        "ttyI", // linux virtual modems
                        "ttyL", // linux SDL RISCom serial card
                        "ttyM", // linux PAM Software's multimodem boards
                        // linux ISI serial card
                        "ttyMX",// linux Moxa Smart IO cards
                        "ttyP", // linux Hayes ESP serial card
                        "ttyR", // linux comtrol cards
                        // linux Specialix RIO serial card
                        "ttyS", // linux Serial Ports
                        "ttySI",// linux SmartIO serial card
                        "ttySR",// linux Specialix RIO serial card 257+
                        "ttyT", // linux Technology Concepts serial card
                        "ttyUSB",//linux USB serial converters
                        "ttyV", // linux Comtrol VS-1000 serial controller
                        "ttyW", // linux specialix cards
                        "ttyX" // linux SpecialX serial card
                    };
                    CandidatePortPrefixes = Temp;
                } else if (RXTXVersion.getOsName().toLowerCase().indexOf("qnx") != -1) {
                    String[] Temp = {
                        "ser"
                    };
                    CandidatePortPrefixes = Temp;
                } else if (RXTXVersion.getOsName().equals("Irix")) {
                    String[] Temp = {
                        "ttyc", // irix raw character devices
                        "ttyd", // irix basic serial ports
                        "ttyf", // irix serial ports with hardware flow
                        "ttym", // irix modems
                        "ttyq", // irix pseudo ttys
                        "tty4d",// irix RS422
                        "tty4f",// irix RS422 with HSKo/HSki
                        "midi", // irix serial midi
                        "us" // irix mapped interface
                    };
                    CandidatePortPrefixes = Temp;
                } else if (RXTXVersion.getOsName().equals("FreeBSD")) //FIXME this is probably wrong
                {
                    String[] Temp = {
                        "ttyd", //general purpose serial ports
                        "cuaa", //dialout serial ports
                        "ttyA", //Specialix SI/XIO dialin ports
                        "cuaA", //Specialix SI/XIO dialout ports
                        "ttyD", //Digiboard - 16 dialin ports
                        "cuaD", //Digiboard - 16 dialout ports
                        "ttyE", //Stallion EasyIO (stl) dialin ports
                        "cuaE", //Stallion EasyIO (stl) dialout ports
                        "ttyF", //Stallion Brumby (stli) dialin ports
                        "cuaF", //Stallion Brumby (stli) dialout ports
                        "ttyR", //Rocketport dialin ports
                        "cuaR", //Rocketport dialout ports
                        "stl" //Stallion EasyIO board or Brumby N 
                    };
                    CandidatePortPrefixes = Temp;
                } else if (RXTXVersion.getOsName().equals("NetBSD")) // FIXME this is probably wrong
                {
                    String[] Temp = {
                        "tty0" // netbsd serial ports
                    };
                    CandidatePortPrefixes = Temp;
                } else if (RXTXVersion.getOsName().equals("Solaris") || RXTXVersion.getOsName().equals("SunOS")) {
                    String[] Temp = {
                        "term/",
                        "cua/"
                    };
                    CandidatePortPrefixes = Temp;
                } else if (RXTXVersion.getOsName().equals("HP-UX")) {
                    String[] Temp = {
                        "tty0p",// HP-UX serial ports
                        "tty1p" // HP-UX serial ports
                    };
                    CandidatePortPrefixes = Temp;
                } else if (RXTXVersion.getOsName().equals("UnixWare")                        || RXTXVersion.getOsName().equals("OpenUNIX")) {
                    String[] Temp = {
                        "tty00s", // UW7/OU8 serial ports
                        "tty01s",
                        "tty02s",
                        "tty03s"
                    };
                    CandidatePortPrefixes = Temp;
                } else if (RXTXVersion.getOsName().equals("OpenServer")) {
                    String[] Temp = {
                        "tty1A", // OSR5 serial ports
                        "tty2A",
                        "tty3A",
                        "tty4A",
                        "tty5A",
                        "tty6A",
                        "tty7A",
                        "tty8A",
                        "tty9A",
                        "tty10A",
                        "tty11A",
                        "tty12A",
                        "tty13A",
                        "tty14A",
                        "tty15A",
                        "tty16A",
                        "ttyu1A", // OSR5 USB-serial ports
                        "ttyu2A",
                        "ttyu3A",
                        "ttyu4A",
                        "ttyu5A",
                        "ttyu6A",
                        "ttyu7A",
                        "ttyu8A",
                        "ttyu9A",
                        "ttyu10A",
                        "ttyu11A",
                        "ttyu12A",
                        "ttyu13A",
                        "ttyu14A",
                        "ttyu15A",
                        "ttyu16A"
                    };
                    CandidatePortPrefixes = Temp;
                } else if (RXTXVersion.getOsName().equals("Compaq's Digital UNIX") || RXTXVersion.getOsName().equals("OSF1")) {
                    String[] Temp = {
                        "tty0" //  Digital Unix serial ports
                    };
                    CandidatePortPrefixes = Temp;
                } else if (RXTXVersion.getOsName().equals("BeOS")) {
                    String[] Temp = {
                        "serial" // BeOS serial ports
                    };
                    CandidatePortPrefixes = Temp;
                } else if (RXTXVersion.getOsName().equals("Mac OS X")) {
                    String[] Temp = {
                        // Keyspan USA-28X adapter, USB port 1
                        "cu.KeyUSA28X191.",
                        // Keyspan USA-28X adapter, USB port 1
                        "tty.KeyUSA28X191.",
                        // Keyspan USA-28X adapter, USB port 2
                        "cu.KeyUSA28X181.",
                        // Keyspan USA-28X adapter, USB port 2
                        "tty.KeyUSA28X181.",
                        // Keyspan USA-19 adapter
                        "cu.KeyUSA19181.",
                        // Keyspan USA-19 adapter
                        "tty.KeyUSA19181."
                    };
                    CandidatePortPrefixes = Temp;
                } else if (RXTXVersion.getOsName().toLowerCase().indexOf("windows") != -1) {
                    String[] Temp = {
                        "COM" // win32 serial ports
                    //"//./COM"    // win32 serial ports
                    };
                    CandidatePortPrefixes = Temp;
                } else {
                    logger.fine("No valid prefixes for serial ports have been entered for " + RXTXVersion.getOsName() + " in RXTXCommDriver.java.  This may just be a typo in the method registerScanPorts().");
                }
                break;

            case CommPortIdentifier.PORT_PARALLEL:
                logger.fine("scanning for parallel ports for os " + RXTXVersion.getOsName());
                /**
                 * Get the Parallel port prefixes for the running os Holger
                 * Lehmann July 12, 1999 IBM
                 */
                if (RXTXVersion.getOsName().equals("Linux") /*
                         || osName.equals("NetBSD") FIXME
                         || osName.equals("HP-UX")  FIXME
                         || osName.equals("Irix")   FIXME
                         || osName.equals("BeOS")   FIXME
                         || osName.equals("Compaq's Digital UNIX")   FIXME
                         */) {
                    String[] temp = {
                        "lp" // linux printer port
                    };
                    CandidatePortPrefixes = temp;
                } else if (RXTXVersion.getOsName().equals("FreeBSD")) {
                    String[] temp = {
                        "lpt"
                    };
                    CandidatePortPrefixes = temp;
                } else if (RXTXVersion.getOsName().toLowerCase().indexOf("windows") != -1) {
                    String[] temp = {
                        "LPT"
                    };
                    CandidatePortPrefixes = temp;
                } else /* printer support is green */ {
                    String[] temp = {};
                    CandidatePortPrefixes = temp;
                }
                break;
            default:
                logger.fine("Unknown PortType " + PortType + " passed to RXTXCommDriver.registerScannedPorts()");
        }
        registerValidPorts(CandidateDeviceNames, CandidatePortPrefixes, PortType);
    }
1229184
def _check_port(host, port, socket_type):
        
        if socket_type == "UDP":
            socket_type = socket.SOCK_DGRAM
        else:
            socket_type = socket.SOCK_STREAM

        for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket_type, 0, socket.AI_PASSIVE):
            af, socktype, proto, _, sa = res
            with socket.socket(af, socktype, proto) as s:
                s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                s.bind(sa)  # the port is available if bind is a success
            return True
50805
def _validate_single_port_string(port):
    
    if ' ' not in port or len(port.split(' ')) != 2:
        raise ValueError(
            "Port '{}' should have exactly one space in it".format(port)
        )
    (external, internal) = port.split(' ')
    try:
        external = int(external)
    except ValueError:
        raise ValueError(
            "Port '{}' external port isn't an int".format(port)
        )
    if ':' not in internal:
        raise ValueError(
            "Port '{}' local address should be 'IP:port'".format(port)
        )
    if not internal.startswith('unix:'):
        ip, localport = internal.split(':')
        if ip != 'localhost' and not _is_non_public_numeric_address(ip):
            raise ValueError(
                "Port '{}' internal IP '{}' should be a local "
                "address".format(port, ip)
            )
199943
def cli(env, identifier, no_vs, no_hardware):
    """"""

    mgr = SoftLayer.NetworkManager(env.client)
    subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids, identifier,
                                   name='subnet')
    subnet = mgr.get_subnet(subnet_id)

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    table.add_row(['id', subnet['id']])
    table.add_row(['identifier',
                   '%s/%s' % (subnet['networkIdentifier'],
                              str(subnet['cidr']))])
    table.add_row(['subnet type', subnet['subnetType']])
    table.add_row(['network space',
                   utils.lookup(subnet, 'networkVlan', 'networkSpace')])
    table.add_row(['gateway', subnet.get('gateway', formatting.blank())])
    table.add_row(['broadcast',
                   subnet.get('broadcastAddress', formatting.blank())])
    table.add_row(['datacenter', subnet['datacenter']['name']])
    table.add_row(['usable ips',
                   subnet.get('usableIpAddressCount', formatting.blank())])

    if not no_vs:
        if subnet['virtualGuests']:
            vs_table = formatting.Table(['hostname', 'domain', 'public_ip', 'private_ip'])
            for vsi in subnet['virtualGuests']:
                vs_table.add_row([vsi['hostname'],
                                  vsi['domain'],
                                  vsi.get('primaryIpAddress'),
                                  vsi.get('primaryBackendIpAddress')])
            table.add_row(['vs', vs_table])
        else:
            table.add_row(['vs', 'none'])

    if not no_hardware:
        if subnet['hardware']:
            hw_table = formatting.Table(['hostname', 'domain', 'public_ip', 'private_ip'])
            for hardware in subnet['hardware']:
                hw_table.add_row([hardware['hostname'],
                                  hardware['domain'],
                                  hardware.get('primaryIpAddress'),
                                  hardware.get('primaryBackendIpAddress')])
            table.add_row(['hardware', hw_table])
        else:
            table.add_row(['hardware', 'none'])

    env.fout(table)
596195
private static boolean isAvailable(int thePort) {
		ourLog.info("Testing a bind on thePort {}", thePort);
		try (ServerSocket ss = new ServerSocket()) {
			ss.setReuseAddress(true);
			ss.bind(new InetSocketAddress("0.0.0.0", thePort));
			try (DatagramSocket ds = new DatagramSocket()) {
				ds.setReuseAddress(true);
				ds.connect(new InetSocketAddress("127.0.0.1", thePort));
				ourLog.info("Successfully bound thePort {}", thePort);
			} catch (IOException e) {
				ourLog.info("Failed to bind thePort {}: {}", thePort, e.toString());
				return false;
			}
		} catch (IOException e) {
			ourLog.info("Failed to bind thePort {}: {}", thePort, e.toString());
			return false;
		}

		try (ServerSocket ss = new ServerSocket()) {
			ss.setReuseAddress(true);
			ss.bind(new InetSocketAddress("localhost", thePort));
		} catch (IOException e) {
			ourLog.info("Failed to bind thePort {}: {}", thePort, e.toString());
			return false;
		}

		return true;
	}
227385
def add_reserved_switch_binding(switch_ip, state):
    """"""

    # overload port_id to contain switch state
    add_nexusport_binding(
        state,
        const.NO_VLAN_OR_VNI_ID,
        const.NO_VLAN_OR_VNI_ID,
        switch_ip,
        const.RESERVED_NEXUS_SWITCH_DEVICE_ID_R1)