Example usage for org.apache.commons.net.util SubnetUtils getInfo

List of usage examples for org.apache.commons.net.util SubnetUtils getInfo

Introduction

In this page you can find the example usage for org.apache.commons.net.util SubnetUtils getInfo.

Prototype

public final SubnetInfo getInfo() 

Source Link

Document

Return a SubnetInfo instance that contains subnet-specific statistics

Usage

From source file:org.opendaylight.vpnservice.dhcpservice.DhcpPktHandler.java

protected byte[] convertToClasslessRouteOption(String dest, String router) {
    ByteArrayOutputStream bArr = new ByteArrayOutputStream();
    if ((dest == null || router == null)) {
        return null;
    }//from w ww  .  j a  v a 2 s.  c o  m

    //get prefix
    Short prefix = null;
    String[] parts = dest.split("/");
    if (parts.length < 2) {
        prefix = new Short((short) 0);
    } else {
        prefix = Short.valueOf(parts[1]);
    }

    bArr.write(prefix.byteValue());
    SubnetUtils util = new SubnetUtils(dest);
    SubnetInfo info = util.getInfo();
    String strNetAddr = info.getNetworkAddress();
    try {
        byte[] netAddr = InetAddress.getByName(strNetAddr).getAddress();
        //Strip any trailing 0s from netAddr
        for (int i = 0; i < netAddr.length; i++) {
            if (netAddr[i] != 0) {
                bArr.write(netAddr, i, 1);
            }
        }
        bArr.write(InetAddress.getByName(router).getAddress());
    } catch (IOException e) {
        return null;
    }
    return bArr.toByteArray();
}

From source file:org.opendaylight.vpnservice.itm.cli.TepCommandHelper.java

private boolean validateIPs(String ipAddress, String subnetMask, String gatewayIp) {
    SubnetUtils utils = new SubnetUtils(subnetMask);
    if ((utils.getInfo().isInRange(ipAddress))
            && ((gatewayIp == null) || (utils.getInfo().isInRange(gatewayIp)))) {
        return true;
    } else {/*ww  w  .  j  a v a2s  .c om*/
        LOG.trace("InValid IP");
        return false;
    }
}

From source file:org.opendaylight.vpnservice.itm.confighelpers.ItmExternalTunnelAddWorker.java

public static List<ListenableFuture<Void>> buildTunnelsToExternalEndPoint(DataBroker dataBroker,
        IdManagerService idManagerService, List<DPNTEPsInfo> cfgDpnList, IpAddress extIp,
        Class<? extends TunnelTypeBase> tunType) {
    List<ListenableFuture<Void>> futures = new ArrayList<>();
    WriteTransaction t = dataBroker.newWriteOnlyTransaction();
    if (null != cfgDpnList) {
        for (DPNTEPsInfo teps : cfgDpnList) {
            // CHECK -- Assumption -- Only one End Point / Dpn for GRE/Vxlan Tunnels
            TunnelEndPoints firstEndPt = teps.getTunnelEndPoints().get(0);
            String interfaceName = firstEndPt.getInterfaceName();
            String tunTypeStr = tunType.getName();
            String trunkInterfaceName = ItmUtils.getTrunkInterfaceName(idManagerService, interfaceName,
                    firstEndPt.getIpAddress().getIpv4Address().getValue(), extIp.getIpv4Address().getValue(),
                    tunTypeStr);/*from w  w  w .ja  v a2s . c  om*/
            char[] subnetMaskArray = firstEndPt.getSubnetMask().getValue();
            String subnetMaskStr = String.valueOf(subnetMaskArray);
            SubnetUtils utils = new SubnetUtils(subnetMaskStr);
            String dcGwyIpStr = String.valueOf(extIp.getValue());
            IpAddress gatewayIpObj = new IpAddress("0.0.0.0".toCharArray());
            IpAddress gwyIpAddress = (utils.getInfo().isInRange(dcGwyIpStr)) ? gatewayIpObj
                    : firstEndPt.getGwIpAddress();
            logger.debug(
                    " Creating Trunk Interface with parameters trunk I/f Name - {}, parent I/f name - {}, source IP - {}, DC Gateway IP - {} gateway IP - {}",
                    trunkInterfaceName, interfaceName, firstEndPt.getIpAddress(), extIp, gwyIpAddress);
            Interface iface = ItmUtils.buildTunnelInterface(teps.getDPNID(), trunkInterfaceName,
                    String.format("%s %s", ItmUtils.convertTunnelTypetoString(tunType), "Trunk Interface"),
                    true, tunType, firstEndPt.getIpAddress(), extIp, gwyIpAddress, firstEndPt.getVLANID(),
                    false, false, null);
            logger.debug(" Trunk Interface builder - {} ", iface);
            InstanceIdentifier<Interface> trunkIdentifier = ItmUtils.buildId(trunkInterfaceName);
            logger.debug(" Trunk Interface Identifier - {} ", trunkIdentifier);
            logger.trace(" Writing Trunk Interface to Config DS {}, {} ", trunkIdentifier, iface);
            t.merge(LogicalDatastoreType.CONFIGURATION, trunkIdentifier, iface, true);
            // update external_tunnel_list ds
            InstanceIdentifier<ExternalTunnel> path = InstanceIdentifier.create(ExternalTunnelList.class).child(
                    ExternalTunnel.class,
                    new ExternalTunnelKey(extIp.toString(), teps.getDPNID().toString(), tunType));
            ExternalTunnel tnl = ItmUtils.buildExternalTunnel(teps.getDPNID().toString(), extIp.toString(),
                    tunType, trunkInterfaceName);
            t.merge(LogicalDatastoreType.CONFIGURATION, path, tnl, true);
        }
        futures.add(t.submit());
    }
    return futures;
}

From source file:org.opendaylight.vpnservice.itm.impl.ItmUtils.java

public static VtepConfigSchema validateVtepConfigSchema(VtepConfigSchema schema) {
    Preconditions.checkNotNull(schema);/*from w  ww.  j a v a  2  s.  c o  m*/
    Preconditions.checkArgument(StringUtils.isNotBlank(schema.getSchemaName()));
    Preconditions.checkArgument(StringUtils.isNotBlank(schema.getPortName()));
    Preconditions.checkArgument((schema.getVlanId() >= 0 && schema.getVlanId() < 4095),
            "Invalid VLAN ID, range (0-4094)");
    Preconditions.checkArgument(StringUtils.isNotBlank(schema.getTransportZoneName()));
    Preconditions.checkNotNull(schema.getSubnet());
    String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
    SubnetUtils subnetUtils = new SubnetUtils(subnetCidr);
    IpAddress gatewayIp = schema.getGatewayIp();
    if (gatewayIp != null) {
        String strGatewayIp = String.valueOf(gatewayIp.getValue());
        if (!strGatewayIp.equals(ITMConstants.DUMMY_IP_ADDRESS)
                && !subnetUtils.getInfo().isInRange(strGatewayIp)) {
            Preconditions.checkArgument(false, new StringBuilder("Gateway IP address ").append(strGatewayIp)
                    .append(" is not in subnet range ").append(subnetCidr).toString());
        }
    }
    ItmUtils.getExcludeIpAddresses(schema.getExcludeIpFilter(), subnetUtils.getInfo());
    return new VtepConfigSchemaBuilder(schema).setTunnelType(schema.getTunnelType()).build();
}

From source file:org.opendaylight.vpnservice.natservice.internal.NaptManager.java

/**
 * this method is used to inform this service of what external IP address to be used
 * as mapping when requested one for the internal IP address given in the input
 * @param segmentId  segmentation in which the mapping to be used. Eg; routerid
 * @param internal subnet prefix or ip address
 * @param external subnet prefix or ip address
 *//*from  w  w w. j  a  v a  2s  . c  o  m*/

public void registerMapping(long segmentId, IPAddress internal, IPAddress external) {

    LOG.debug(
            "NAPT Service : registerMapping called with segmentid {}, internalIp {}, prefix {}, externalIp {} and prefix {} ",
            segmentId, internal.getIpAddress(), internal.getPrefixLength(), external.getIpAddress(),
            external.getPrefixLength());
    // Create Pool per ExternalIp and not for all IPs in the subnet. Create new Pools during getExternalAddressMapping if exhausted.
    String externalIpPool;
    if (external.getPrefixLength() != 0 && external.getPrefixLength() != NatConstants.DEFAULT_PREFIX) { // subnet case
        String externalSubnet = new StringBuilder(64).append(external.getIpAddress()).append("/")
                .append(external.getPrefixLength()).toString();
        LOG.debug("NAPT Service : externalSubnet is : {}", externalSubnet);
        SubnetUtils subnetUtils = new SubnetUtils(externalSubnet);
        SubnetInfo subnetInfo = subnetUtils.getInfo();
        externalIpPool = subnetInfo.getLowAddress();
    } else { // ip case
        externalIpPool = external.getIpAddress();
    }
    createNaptPortPool(externalIpPool);

    // Store the ip to ip map in Operational DS
    String internalIp = internal.getIpAddress();
    if (internal.getPrefixLength() != 0) {
        internalIp = new StringBuilder(64).append(internal.getIpAddress()).append("/")
                .append(internal.getPrefixLength()).toString();
    }
    String externalIp = external.getIpAddress();
    if (external.getPrefixLength() != 0) {
        externalIp = new StringBuilder(64).append(external.getIpAddress()).append("/")
                .append(external.getPrefixLength()).toString();
    }
    updateCounter(segmentId, externalIp, true);
    //update the actual ip-map
    IpMap ipm = new IpMapBuilder().setKey(new IpMapKey(internalIp)).setInternalIp(internalIp)
            .setExternalIp(externalIp).build();
    MDSALUtil.syncWrite(broker, LogicalDatastoreType.OPERATIONAL, getIpMapIdentifier(segmentId, internalIp),
            ipm);
    LOG.debug("NAPT Service : registerMapping exit after updating DS with internalIP {}, externalIP {}",
            internalIp, externalIp);
}

From source file:org.opendaylight.vpnservice.natservice.internal.NaptManager.java

/**
 * method to get external ip/port mapping when provided with internal ip/port pair
 * If already a mapping exist for the given input, then the existing mapping is returned
 * instead of overwriting with new ip/port pair.
 * @param segmentId//w ww  .  j  a va 2  s .  c o  m
 * @param sourceAddress - internal ip address/port pair
 * @return external ip address/port
 */
public SessionAddress getExternalAddressMapping(long segmentId, SessionAddress sourceAddress,
        NAPTEntryEvent.Protocol protocol) {
    LOG.debug("NAPT Service : getExternalAddressMapping called with segmentId {}, internalIp {} and port {}",
            segmentId, sourceAddress.getIpAddress(), sourceAddress.getPortNumber());
    /*
     1. Get Internal IP, Port in IP:Port format
     2. Inside DB with routerId get the list of entries and check if it matches with existing IP:Port
     3. If True return SessionAddress of ExternalIp and Port
     4. Else check ip Map and Form the ExternalIp and Port and update DB and then return ExternalIp and Port
     */

    //SessionAddress externalIpPort = new SessionAddress();
    String internalIpPort = new StringBuilder(64).append(sourceAddress.getIpAddress()).append(":")
            .append(sourceAddress.getPortNumber()).toString();

    // First check existing Port Map.
    SessionAddress existingIpPort = checkIpPortMap(segmentId, internalIpPort, protocol);
    if (existingIpPort != null) {
        // populate externalIpPort from IpPortMap and return
        LOG.debug("NAPT Service : getExternalAddressMapping successfully returning existingIpPort as {} and {}",
                existingIpPort.getIpAddress(), existingIpPort.getPortNumber());
        return existingIpPort;
    } else {
        // Now check in ip-map
        String externalIp = checkIpMap(segmentId, sourceAddress.getIpAddress());
        if (externalIp == null) {
            LOG.error(
                    "NAPT Service : getExternalAddressMapping, Unexpected error, internal to external ip map does not exist");
            return null;
        } else {
            /* Logic assuming internalIp is always ip and not subnet
             * case 1: externalIp is ip
             *        a) goto externalIp pool and getPort and return
             *        b) else return error
             * case 2: externalIp is subnet
             *        a) Take first externalIp and goto that Pool and getPort
             *             if port -> return
             *             else Take second externalIp and create that Pool and getPort
             *             if port ->return
             *             else
             *             Continue same with third externalIp till we exhaust subnet
             *        b) Nothing worked return error
             */
            SubnetUtils externalIpSubnet;
            List<String> allIps = new ArrayList<String>();
            String subnetPrefix = "/" + String.valueOf(NatConstants.DEFAULT_PREFIX);
            if (!externalIp.contains(subnetPrefix)) {
                EXTSUBNET_FLAG = true;
                externalIpSubnet = new SubnetUtils(externalIp);
                allIps = Arrays.asList(externalIpSubnet.getInfo().getAllAddresses());
                LOG.debug("NAPT Service : total count of externalIps available {}",
                        externalIpSubnet.getInfo().getAddressCount());
            } else {
                LOG.debug("NAPT Service : getExternalAddress single ip case");
                if (externalIp.contains(subnetPrefix)) {
                    String[] externalIpSplit = externalIp.split("/");
                    String extIp = externalIpSplit[0];
                    externalIp = extIp; //remove /32 what we got from checkIpMap
                }
                allIps.add(externalIp);
            }

            for (String extIp : allIps) {
                LOG.info("NAPT Service : Looping externalIPs with externalIP now as {}", extIp);
                if (NEXT_EXTIP_FLAG) {
                    createNaptPortPool(extIp);
                    LOG.debug("NAPT Service : Created Pool for next Ext IP {}", extIp);
                }
                AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(extIp)
                        .setIdKey(internalIpPort).build();
                try {
                    Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
                    RpcResult<AllocateIdOutput> rpcResult;
                    if ((result != null) && (result.get().isSuccessful())) {
                        LOG.debug("NAPT Service : Got id from idManager");
                        rpcResult = result.get();
                    } else {
                        LOG.error(
                                "NAPT Service : getExternalAddressMapping, idManager could not allocate id retry if subnet");
                        if (!EXTSUBNET_FLAG) {
                            LOG.error(
                                    "NAPT Service : getExternalAddressMapping returning null for single IP case, may be ports exhausted");
                            return null;
                        }
                        LOG.debug(
                                "NAPT Service : Could be ports exhausted case, try with another externalIP if possible");
                        NEXT_EXTIP_FLAG = true;
                        continue;
                    }
                    int extPort = rpcResult.getResult().getIdValue().intValue();
                    SessionAddress externalIpPort = new SessionAddress(extIp, extPort);
                    // Write to ip-port-map before returning
                    IpPortExternalBuilder ipExt = new IpPortExternalBuilder();
                    IpPortExternal ipPortExt = ipExt.setIpAddress(extIp).setPortNum(extPort).build();
                    IpPortMap ipm = new IpPortMapBuilder().setKey(new IpPortMapKey(internalIpPort))
                            .setIpPortInternal(internalIpPort).setIpPortExternal(ipPortExt).build();
                    LOG.debug(
                            "NAPT Service : getExternalAddressMapping writing into ip-port-map with externalIP {} and port {}",
                            ipPortExt.getIpAddress(), ipPortExt.getPortNum());
                    try {
                        MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION,
                                getIpPortMapIdentifier(segmentId, internalIpPort, protocol), ipm);
                    } catch (UncheckedExecutionException uee) {
                        LOG.error("NAPT Service : Failed to write into ip-port-map with exception {}",
                                uee.getMessage());
                    }

                    // Write to snat-internal-ip-port-info
                    String internalIpAddress = sourceAddress.getIpAddress();
                    int ipPort = sourceAddress.getPortNumber();
                    ProtocolTypes protocolType = NatUtil.getProtocolType(protocol);
                    List<Integer> portList = NatUtil.getInternalIpPortListInfo(broker, segmentId,
                            internalIpAddress, protocolType);
                    if (portList == null) {
                        portList = Lists.newArrayList();
                    }
                    portList.add(ipPort);

                    IntIpProtoTypeBuilder builder = new IntIpProtoTypeBuilder();
                    IntIpProtoType intIpProtocolType = builder.setKey(new IntIpProtoTypeKey(protocolType))
                            .setPorts(portList).build();
                    try {
                        MDSALUtil.syncWrite(broker, LogicalDatastoreType.CONFIGURATION, NatUtil
                                .buildSnatIntIpPortIdentifier(segmentId, internalIpAddress, protocolType),
                                intIpProtocolType);
                    } catch (Exception ex) {
                        LOG.error(
                                "NAPT Service : Failed to write into snat-internal-ip-port-info with exception {}",
                                ex.getMessage());
                    }

                    LOG.debug(
                            "NAPT Service : getExternalAddressMapping successfully returning externalIP {} and port {}",
                            externalIpPort.getIpAddress(), externalIpPort.getPortNumber());
                    return externalIpPort;
                } catch (InterruptedException | ExecutionException e) {
                    LOG.error("NAPT Service : getExternalAddressMapping, Exception caught  {}", e);
                    return null;
                }
            } // end of for loop
        } // end of else ipmap present
    } // end of else check ipmap
    LOG.error(
            "NAPT Service: getExternalAddressMapping returning null, nothing worked or externalIPs exhausted");
    return null;
}

From source file:org.opendaylight.vpnservice.natservice.internal.NaptManager.java

protected String checkIpMap(long segmentId, String internalIp) {

    LOG.debug("NAPT Service : checkIpMap called with segmentId {} and internalIp {}", segmentId, internalIp);
    String externalIp;/*from w  w w  .  j a  v  a  2s . c  o m*/
    // check if ip-map node is there
    InstanceIdentifierBuilder<IpMapping> idBuilder = InstanceIdentifier.builder(IntextIpMap.class)
            .child(IpMapping.class, new IpMappingKey(segmentId));
    InstanceIdentifier<IpMapping> id = idBuilder.build();
    Optional<IpMapping> ipMapping = MDSALUtil.read(broker, LogicalDatastoreType.OPERATIONAL, id);
    if (ipMapping.isPresent()) {
        List<IpMap> ipMaps = ipMapping.get().getIpMap();
        for (IpMap ipMap : ipMaps) {
            if (ipMap.getInternalIp().equals(internalIp)) {
                LOG.debug("NAPT Service : IpMap : {}", ipMap);
                externalIp = ipMap.getExternalIp().toString();
                LOG.debug("NAPT Service : checkIpMap successfully returning externalIp {}", externalIp);
                return externalIp;
            } else if (ipMap.getInternalIp().contains("/")) { // subnet case
                SubnetUtils subnetUtils = new SubnetUtils(ipMap.getInternalIp());
                SubnetInfo subnetInfo = subnetUtils.getInfo();
                if (subnetInfo.isInRange(internalIp)) {
                    LOG.debug("NAPT Service : internalIp {} found to be IpMap of internalIpSubnet {}",
                            internalIp, ipMap.getInternalIp());
                    externalIp = ipMap.getExternalIp().toString();
                    LOG.debug("NAPT Service : checkIpMap successfully returning externalIp {}", externalIp);
                    return externalIp;
                }
            }
        }
    }
    // return null if not found
    LOG.error("NAPT Service : checkIpMap failed, returning NULL for segmentId {} and internalIp {}", segmentId,
            internalIp);
    return null;
}

From source file:org.opendaylight.vtn.javaapi.openstack.convertor.StaticRouteResourceGenerator.java

/**
 * Convert response for static-ip-route from UNC format to OpenStack format
 * /*from  w  w w  .j ava  2  s.c om*/
 * @param responseBody
 *            - UNC formatted response body
 * @return - OpenStack formatted response body
 */
public static JsonObject convertListResponseBody(JsonObject responseBody) {
    final JsonObject openStackResponse = new JsonObject();
    final JsonArray routes = new JsonArray();
    final JsonArray staticRoutes = responseBody.get(VtnServiceJsonConsts.STATIC_IPROUTES).getAsJsonArray();
    for (final JsonElement staticRoute : staticRoutes) {

        final String[] staticIpRouteId = staticRoute.getAsJsonObject().get(VtnServiceJsonConsts.STATICIPROUTEID)
                .getAsString().split(VtnServiceConsts.HYPHEN);

        final String destination = staticIpRouteId[0] + VtnServiceConsts.SLASH + staticIpRouteId[2];
        final String nexthop = staticIpRouteId[1];

        String routeId = null;
        if (staticIpRouteId[2].equals(VtnServiceConsts.ZERO)) {
            routeId = staticIpRouteId[0] + VtnServiceConsts.HYPHEN + staticIpRouteId[1]
                    + VtnServiceConsts.HYPHEN + VtnServiceConsts.DEFAULT_IP;
        } else {
            final SubnetUtils subnetUtils = new SubnetUtils(destination);
            routeId = staticIpRouteId[0] + VtnServiceConsts.HYPHEN + staticIpRouteId[1]
                    + VtnServiceConsts.HYPHEN + subnetUtils.getInfo().getNetmask();
        }

        final JsonObject route = new JsonObject();
        route.addProperty(VtnServiceOpenStackConsts.ID, routeId);
        route.addProperty(VtnServiceOpenStackConsts.DESTNATION, destination);
        route.addProperty(VtnServiceOpenStackConsts.NEXTHOP, nexthop);
        routes.add(route);
    }
    openStackResponse.add(VtnServiceOpenStackConsts.ROUTES, routes);
    return openStackResponse;
}

From source file:org.opendaylight.vtn.javaapi.resources.openstack.RouteResource.java

/**
 * Convert UNC formatted route_id from OpenStack formatted route_id
 * /*from   ww  w  .j av  a  2 s .co m*/
 * @param requestBody
 *            - OpenStack request body
 * @return - generated route_id
 */
private String convertRouteId(String osRouteId) {
    final String[] routeId = osRouteId.split(VtnServiceConsts.HYPHEN);
    String staticIpRouteId = null;
    if (routeId[2].equals(VtnServiceConsts.DEFAULT_IP)) {
        staticIpRouteId = routeId[0] + VtnServiceConsts.HYPHEN + routeId[1] + VtnServiceConsts.HYPHEN
                + VtnServiceConsts.ZERO;
    } else {
        final SubnetUtils subnetUtils = new SubnetUtils(routeId[0], routeId[2]);
        staticIpRouteId = routeId[0] + VtnServiceConsts.HYPHEN + routeId[1] + VtnServiceConsts.HYPHEN
                + subnetUtils.getInfo().getCidrSignature().split(VtnServiceConsts.SLASH)[1];
    }
    return staticIpRouteId;
}

From source file:org.opendaylight.vtn.javaapi.resources.openstack.RoutesResource.java

/**
 * Generate UNC formatted route_id//from   w  w  w  .j a  v a2  s. c  o  m
 * 
 * @param requestBody
 *            - OpenStack request body
 * @return - generated route_id
 */
private String convertRouteId(JsonObject requestBody) {
    String destination = requestBody.get(VtnServiceOpenStackConsts.DESTNATION).getAsString();
    String ipAndPrefix[] = destination.split(VtnServiceConsts.SLASH);

    int prefix = Integer.parseInt(ipAndPrefix[1]);
    String routeId = null;
    if (prefix == 0) {
        routeId = ipAndPrefix[0] + VtnServiceConsts.HYPHEN
                + requestBody.get(VtnServiceOpenStackConsts.NEXTHOP).getAsString() + VtnServiceConsts.HYPHEN
                + VtnServiceConsts.DEFAULT_IP;
    } else {
        final SubnetUtils subnetUtils = new SubnetUtils(destination);
        routeId = ipAndPrefix[0] + VtnServiceConsts.HYPHEN
                + requestBody.get(VtnServiceOpenStackConsts.NEXTHOP).getAsString() + VtnServiceConsts.HYPHEN
                + subnetUtils.getInfo().getNetmask();
    }
    return routeId;
}