org.onlab.packet.IpAddress Java Examples

The following examples show how to use org.onlab.packet.IpAddress. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ControlPlaneRedirectManagerTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests adding while updating the networkConfig.
 */
@Test
public void testAddInterface() {
    ConnectPoint sw1eth4 = new ConnectPoint(DEVICE_ID, PortNumber.portNumber(4));
    List<InterfaceIpAddress> interfaceIpAddresses = new ArrayList<>();
    interfaceIpAddresses.add(
            new InterfaceIpAddress(IpAddress.valueOf("192.168.40.101"), IpPrefix.valueOf("192.168.40.0/24"))
    );
    interfaceIpAddresses.add(
            new InterfaceIpAddress(IpAddress.valueOf("2000::ff"), IpPrefix.valueOf("2000::ff/120"))
    );

    Interface sw1Eth4 = new Interface(sw1eth4.deviceId().toString(), sw1eth4, interfaceIpAddresses,
            MacAddress.valueOf("00:00:00:00:00:04"), VlanId.NONE);
    interfaces.add(sw1Eth4);

    EasyMock.reset(flowObjectiveService);
    expect(flowObjectiveService.allocateNextId()).andReturn(1).anyTimes();

    setUpInterfaceConfiguration(sw1Eth4, true);
    replay(flowObjectiveService);
    interfaceListener.event(new InterfaceEvent(InterfaceEvent.Type.INTERFACE_ADDED, sw1Eth4, 500L));
    verify(flowObjectiveService);
}
 
Example #2
Source File: VtnConfig.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Creates or update tunnel in the controller device.
 *
 * @param handler DriverHandler
 * @param srcIp the ipAddress of the local controller device
 */
public static void applyTunnelConfig(DriverHandler handler, IpAddress srcIp) {
    DefaultAnnotations.Builder optionBuilder = DefaultAnnotations.builder();
    for (String key : DEFAULT_TUNNEL_OPTIONS.keySet()) {
        optionBuilder.set(key, DEFAULT_TUNNEL_OPTIONS.get(key));
    }

    InterfaceConfig interfaceConfig = handler.behaviour(InterfaceConfig.class);
    TunnelDescription tunnel = DefaultTunnelDescription.builder()
            .deviceId(DEFAULT_BRIDGE_NAME)
            .ifaceName(DEFAULT_TUNNEL)
            .type(TunnelDescription.Type.VXLAN)
            .local(TunnelEndPoints.ipTunnelEndpoint(srcIp))
            .remote(TunnelEndPoints.flowTunnelEndpoint())
            .key(TunnelKeys.flowTunnelKey())
            .otherConfigs(optionBuilder.build())
            .build();
    interfaceConfig.addTunnelMode(DEFAULT_TUNNEL, tunnel);
}
 
Example #3
Source File: NiciraNatSerializer.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public NiciraNat read(Kryo kryo, Input input, Class<NiciraNat> type) {
    int natFlags = input.readInt();
    int natPresentFlags = input.readInt();
    int natPortMin = input.readInt();
    int natPortMax = input.readInt();

    // TODO: IPv6 address should also be supported
    byte[] minOcts = new byte[4];
    byte[] maxOcts = new byte[4];

    input.readBytes(minOcts);
    input.readBytes(maxOcts);

    IpAddress natIpAddressMin = IpAddress.valueOf(IpAddress.Version.INET, minOcts);
    IpAddress natIpAddressMax = IpAddress.valueOf(IpAddress.Version.INET, maxOcts);

    return new NiciraNat(natFlags, natPresentFlags, natPortMin, natPortMax,
            natIpAddressMin, natIpAddressMax);
}
 
Example #4
Source File: PeerConnectivityManagerTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests a corner case, when there is no Interface configured for one BGP
 * peer.
 */
@Test
public void testNoPeerInterface() {
    IpAddress ip = IpAddress.valueOf("1.1.1.1");
    bgpSpeakers.clear();
    bgpSpeakers.add(new BgpConfig.BgpSpeakerConfig(Optional.of("foo"),
            VlanId.NONE, s1Eth100, Collections.singleton(ip)));
    reset(interfaceService);
    interfaceService.addListener(anyObject(InterfaceListener.class));
    expect(interfaceService.getMatchingInterface(ip)).andReturn(null).anyTimes();
    replay(interfaceService);

    // We don't expect any intents in this case
    reset(intentSynchronizer);
    replay(intentSynchronizer);
    peerConnectivityManager.start();
    verify(intentSynchronizer);
}
 
Example #5
Source File: SubnetUpdateCommand.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
protected void doExecute() {
    SubnetService service = get(SubnetService.class);
    if (id == null || networkId == null || tenantId == null) {
        print("id,networkId,tenantId can not be null");
        return;
    }
    Subnet subnet = new DefaultSubnet(SubnetId.subnetId(id), subnetName,
                                      TenantNetworkId.networkId(networkId),
                                      TenantId.tenantId(tenantId), ipVersion,
                                      cidr == null ? null : IpPrefix.valueOf(cidr),
                                      gatewayIp == null ? null : IpAddress.valueOf(gatewayIp),
                                      dhcpEnabled, shared, hostRoutes,
                                      ipV6AddressMode == null ? null : Mode.valueOf(ipV6AddressMode),
                                      ipV6RaMode == null ? null : Mode.valueOf(ipV6RaMode),
                                      allocationPools);
    Set<Subnet> subnetsSet = Sets.newHashSet();
    subnetsSet.add(subnet);
    service.updateSubnets(subnetsSet);
}
 
Example #6
Source File: HostLocationProvider.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Updates IP address for an existing host.
 *
 * @param hid host ID
 * @param ip IP address
 */
private void updateHostIp(HostId hid, IpAddress ip) {
    Host host = hostService.getHost(hid);
    if (host == null) {
        log.warn("Fail to update IP for {}. Host does not exist", hid);
        return;
    }

    HostDescription desc = new DefaultHostDescription(hid.mac(), hid.vlanId(),
            host.locations(), Sets.newHashSet(ip), false);
    try {
        providerService.hostDetected(hid, desc, false);
    } catch (IllegalStateException e) {
        log.debug("Host {} suppressed", hid);
    }
}
 
Example #7
Source File: McastUtils.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Adds filtering objective for given device and port.
 *
 * @param deviceId device ID
 * @param port ingress port number
 * @param assignedVlan assigned VLAN ID
 * @param mcastIp the group address
 * @param mcastRole the role of the device
 * @param matchOnMac match or not on macaddress
 */
void addFilterToDevice(DeviceId deviceId, PortNumber port, VlanId assignedVlan,
                       IpAddress mcastIp, McastRole mcastRole, boolean matchOnMac) {
    if (!srManager.deviceConfiguration().isConfigured(deviceId)) {
        log.debug("skip update of fitering objective for unconfigured device: {}", deviceId);
        return;
    }
    MacAddress routerMac = getRouterMac(deviceId, port);

    if (MacAddress.NONE.equals(routerMac)) {
        return;
    }
    FilteringObjective.Builder filtObjBuilder = filterObjBuilder(port, assignedVlan, mcastIp,
                                                                 routerMac, mcastRole, matchOnMac);
    ObjectiveContext context = new DefaultObjectiveContext(
            (objective) -> log.debug("Successfully add filter on {}/{}, vlan {}",
                                     deviceId, port.toLong(), assignedVlan),
            (objective, error) ->
                    log.warn("Failed to add filter on {}/{}, vlan {}: {}",
                             deviceId, port.toLong(), assignedVlan, error));
    srManager.flowObjectiveService.filter(deviceId, filtObjBuilder.add(context));
}
 
Example #8
Source File: VbngManager.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public IpAddress createVbng(IpAddress privateIpAddress,
                            MacAddress hostMacAddress,
                            String hostName) {

    IpAddress publicIpAddress =
            vbngConfigurationService.getAvailablePublicIpAddress(
                                                 privateIpAddress);
    if (publicIpAddress == null) {
        log.info("Did not find an available public IP address to use.");
        return null;
    }
    log.info("[ADD] Private IP to Public IP mapping: {} --> {}",
             privateIpAddress, publicIpAddress);

    // Setup paths between the host configured with private IP and
    // next hop
    if (!setupForwardingPaths(privateIpAddress, publicIpAddress,
                              hostMacAddress, hostName)) {
        privateIpAddressMap.put(privateIpAddress,
                                new VcpeHost(hostMacAddress, hostName));
    }
    return publicIpAddress;
}
 
Example #9
Source File: K8sIpamManagerTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests if allocating IP address works correctly.
 */
@Test
public void testAllocateIp() {
    createBasicIpPool();

    assertEquals("Number of allocated IPs did not match", 0,
            target.allocatedIps(NETWORK_ID).size());
    assertEquals("Number of available IPs did not match", 2,
            target.availableIps(NETWORK_ID).size());

    IpAddress allocatedIp = target.allocateIp(NETWORK_ID);
    assertEquals("Number of allocated IPs did not match", 1,
            target.allocatedIps(NETWORK_ID).size());
    assertEquals("Number of available IPs did not match", 1,
            target.availableIps(NETWORK_ID).size());
    assertTrue("Allocated IP did not match",
            IP_ADDRESSES.contains(allocatedIp));
}
 
Example #10
Source File: FpmConnectionsList.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
protected void doExecute() {
    FpmInfoService fpmInfo = get(FpmInfoService.class);

    print(String.format("PD Pushing is %s.", fpmInfo.isPdPushEnabled() ? "enabled" : "disabled"));
    if (peerAddress != null) {
        IpAddress address = IpAddress.valueOf(peerAddress);
        fpmInfo.peers().entrySet().stream()
                .filter(peer -> peer.getKey().address().equals(address))
                .map(Map.Entry::getValue)
                .forEach(this::print);
    } else {
        fpmInfo.peers().entrySet().stream()
                .sorted(Comparator.<Map.Entry<FpmPeer, FpmPeerInfo>, IpAddress>comparing(e -> e.getKey().address())
                        .thenComparing(e -> e.getKey().port()))
                .map(Map.Entry::getValue)
                .forEach(this::print);
    }


}
 
Example #11
Source File: DefaultRestSBDevice.java    From onos with Apache License 2.0 6 votes vote down vote up
public DefaultRestSBDevice(IpAddress ip, int port, String name, String password,
                           String protocol, String url, boolean isActive, String testUrl, String manufacturer,
                           String hwVersion, String swVersion, boolean isProxy,
                           AuthenticationScheme authenticationScheme, String token) {
    Preconditions.checkNotNull(ip, "IP address cannot be null");
    Preconditions.checkArgument(port > 0, "Port address cannot be negative");
    Preconditions.checkNotNull(protocol, "protocol address cannot be null");
    this.ip = ip;
    this.port = port;
    this.username = name;
    this.password = StringUtils.isEmpty(password) ? null : password;
    this.isActive = isActive;
    this.protocol = protocol;
    this.url = StringUtils.isEmpty(url) ? null : url;
    this.authenticationScheme = authenticationScheme;
    this.token = token;
    this.manufacturer = StringUtils.isEmpty(manufacturer) ?
            Optional.empty() : Optional.ofNullable(manufacturer);
    this.hwVersion = StringUtils.isEmpty(hwVersion) ?
            Optional.empty() : Optional.ofNullable(hwVersion);
    this.swVersion = StringUtils.isEmpty(swVersion) ?
            Optional.empty() : Optional.ofNullable(swVersion);
    this.testUrl = StringUtils.isEmpty(testUrl) ?
            Optional.empty() : Optional.ofNullable(testUrl);
    this.isProxy = isProxy;
}
 
Example #12
Source File: DhcpRelayWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes the fpm route from fpm record.
 * Corresponding route from the route store
 *
 * @param prefix IpPrefix
 * @return 204 NO CONTENT, 404; 401
 */
@DELETE
@Path("fpm/{prefix}")
public Response dhcpFpmDelete(@PathParam("prefix") String prefix) {
    DhcpRelayService dhcpRelayService = get(DhcpRelayService.class);
    RouteStore routeStore = get(RouteStore.class);

    try {
        // removes fpm route from fpm record
        Optional<FpmRecord> fpmRecord = dhcpRelayService.removeFpmRecord(IpPrefix.valueOf(prefix));
        if (fpmRecord.isPresent()) {
            IpAddress nextHop = fpmRecord.get().nextHop();
            Route route = new Route(Route.Source.DHCP, IpPrefix.valueOf(prefix), nextHop);
            // removes DHCP route from route store
            routeStore.removeRoute(route);
        } else {
            LOG.warn("fpmRecord is not present");
        }
    } catch (IllegalArgumentException ex) {
        throw new IllegalArgumentException(ex);
    }

    return Response.noContent().build();
}
 
Example #13
Source File: BgpConfig.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Adds peering address to BGP speaker.
 *
 * @param speakerName name of BGP speaker
 * @param peerAddress peering address to be added
 */
public void addPeerToSpeaker(String speakerName, IpAddress peerAddress) {
    JsonNode speakersNode = object.get(SPEAKERS);
    speakersNode.forEach(jsonNode -> {
        if (jsonNode.hasNonNull(NAME) &&
                jsonNode.get(NAME).asText().equals(speakerName)) {
            ArrayNode peersNode = (ArrayNode) jsonNode.get(PEERS);
            for (int i = 0; i < peersNode.size(); i++) {
                if (peersNode.get(i).asText().equals(peerAddress.toString())) {
                    return; // Peer already exists.
                }
            }
            peersNode.add(peerAddress.toString());
        }
    });
}
 
Example #14
Source File: InstancePortCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public InstancePort decode(ObjectNode json, CodecContext context) {
    if (json == null || !json.isObject()) {
        return null;
    }

    String networkId = nullIsIllegal(json.get(NETWORK_ID).asText(),
            NETWORK_ID + MISSING_MESSAGE);
    String portId = nullIsIllegal(json.get(PORT_ID).asText(),
            PORT_ID + MISSING_MESSAGE);
    String macAddress = nullIsIllegal(json.get(MAC_ADDRESS).asText(),
            MAC_ADDRESS + MISSING_MESSAGE);
    String ipAddress = nullIsIllegal(json.get(IP_ADDRESS).asText(),
            IP_ADDRESS + MISSING_MESSAGE);
    String deviceId = nullIsIllegal(json.get(DEVICE_ID).asText(),
            DEVICE_ID + MISSING_MESSAGE);
    String portNumber = nullIsIllegal(json.get(PORT_NUMBER).asText(),
            PORT_NUMBER + MISSING_MESSAGE);
    String state = nullIsIllegal(json.get(STATE).asText(),
            STATE + MISSING_MESSAGE);

    return DefaultInstancePort.builder()
            .networkId(networkId)
            .portId(portId)
            .macAddress(MacAddress.valueOf(macAddress))
            .ipAddress(IpAddress.valueOf(ipAddress))
            .deviceId(DeviceId.deviceId(deviceId))
            .portNumber(PortNumber.fromString(portNumber))
            .state(InstancePort.State.valueOf(state)).build();
}
 
Example #15
Source File: OpenstackRoutingArpHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private boolean isExternalGatewaySourceIp(IpAddress targetIp) {
    return osNetworkAdminService.ports().stream()
            .filter(osPort -> Objects.equals(osPort.getDeviceOwner(),
                    DEVICE_OWNER_ROUTER_GW))
            .flatMap(osPort -> osPort.getFixedIps().stream())
            .anyMatch(ip -> IpAddress.valueOf(ip.getIpAddress()).equals(targetIp));
}
 
Example #16
Source File: K8sPortCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public K8sPort decode(ObjectNode json, CodecContext context) {
    if (json == null || !json.isObject()) {
        return null;
    }

    String networkId = nullIsIllegal(json.get(NETWORK_ID).asText(),
            NETWORK_ID + MISSING_MESSAGE);
    String portId = nullIsIllegal(json.get(PORT_ID).asText(),
            PORT_ID + MISSING_MESSAGE);
    String macAddress = nullIsIllegal(json.get(MAC_ADDRESS).asText(),
            MAC_ADDRESS + MISSING_MESSAGE);
    String ipAddress = nullIsIllegal(json.get(IP_ADDRESS).asText(),
            IP_ADDRESS + MISSING_MESSAGE);

    K8sPort.Builder builder = DefaultK8sPort.builder()
            .networkId(networkId)
            .portId(portId)
            .macAddress(MacAddress.valueOf(macAddress))
            .ipAddress(IpAddress.valueOf(ipAddress));

    JsonNode deviceIdJson = json.get(DEVICE_ID);
    if (deviceIdJson != null) {
        builder.deviceId(DeviceId.deviceId(deviceIdJson.asText()));
    }

    JsonNode portNumberJson = json.get(PORT_NUMBER);
    if (portNumberJson != null) {
        builder.portNumber(PortNumber.portNumber(portNumberJson.asText()));
    }

    JsonNode stateJson = json.get(STATE);
    if (stateJson != null) {
        builder.state(State.valueOf(stateJson.asText()));
    } else {
        builder.state(State.INACTIVE);
    }

    return builder.build();
}
 
Example #17
Source File: K8sIpamManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void reserveIp(String networkId, IpAddress ipAddress) {
    if (!allocatedIps(networkId).contains(ipAddress)) {
        String ipamId = networkId + "-" + ipAddress.toString();
        k8sIpamStore.removeAvailableIp(ipamId);
        k8sIpamStore.createAllocatedIp(
                new DefaultK8sIpam(ipamId, ipAddress, networkId));

        log.info("Reserved the IP {}", ipAddress.toString());
    }
}
 
Example #18
Source File: McastHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Process the ROUTE_ADDED event.
 *
 * @param mcastIp the group address
 */
private void processRouteAddedInternal(IpAddress mcastIp) {
    lastMcastChange.set(Instant.now());
    log.info("Processing route added for Multicast group {}", mcastIp);
    // Just elect a new leader
    mcastUtils.isLeader(mcastIp);
}
 
Example #19
Source File: RouteAddCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() {
    RouteAdminService service = AbstractShellCommand.get(RouteAdminService.class);

    IpPrefix prefix = IpPrefix.valueOf(prefixString);
    IpAddress nextHop = IpAddress.valueOf(nextHopString);

    service.update(Collections.singleton(new Route(Route.Source.STATIC, prefix, nextHop)));
}
 
Example #20
Source File: NetconfAccessInfo.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Builds NetconfAccessInfo from json.
 * @param root json root node for NetconfAccessinfo
 * @return NETCONF access information
 * @throws WorkflowException workflow exception
 */
public static NetconfAccessInfo valueOf(JsonNode root) throws WorkflowException {

    JsonNode node = root.at(ptr(REMOTE_IP));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid remoteIp for " + root);
    }
    IpAddress remoteIp = IpAddress.valueOf(node.asText());

    node = root.at(ptr(PORT));
    if (node == null || !(node instanceof NumericNode)) {
        throw new WorkflowException("invalid port for " + root);
    }
    TpPort tpPort = TpPort.tpPort(node.asInt());

    node = root.at(ptr(USER));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid user for " + root);
    }
    String strUser = node.asText();

    node = root.at(ptr(PASSWORD));
    if (node == null || !(node instanceof TextNode)) {
        throw new WorkflowException("invalid password for " + root);
    }
    String strPassword = node.asText();

    return new NetconfAccessInfo(remoteIp, tpPort, strUser, strPassword);
}
 
Example #21
Source File: PcepClientControllerImplTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Test
public void tunnelProviderAddedTest2() throws PcepParseException, PcepOutOfBoundMessageException {
    PccId pccId = PccId.pccId(IpAddress.valueOf("1.1.1.1"));

    byte[] reportMsg = new byte[] {0x20, 0x0a, 0x00, (byte) 0x50, 0x21, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00,
                                    0x00, 0x00, 0x00, 0x01, // SRP object
                                    0x00, 0x1c, 0x00, 0x04, // PATH-SETUP-TYPE TLV
                                    0x00, 0x00, 0x00, 0x00, 0x20, 0x10, 0x00, 0x24, 0x00, // LSP object
                                    0x00, 0x10, (byte) 0xAB,
                                    0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, // symbolic path tlv
                                    0x00, 0x12, 0x00, 0x10, // IPv4-LSP-IDENTIFIER-TLV
                                    0x01, 0x01, 0x01, 0x01, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x05,
                                    0x05, 0x05, 0x05,

                                    0x07, 0x10, 0x00, 0x14, // ERO object
                                    0x01, 0x08, (byte) 0x01, 0x01, 0x01, 0x01, 0x04, 0x00, // ERO IPv4 sub objects
                                    0x01, 0x08, (byte) 0x05, 0x05, 0x05, 0x05, 0x04, 0x00, };

    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
    buffer.writeBytes(reportMsg);

    PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
    PcepMessage message = reader.readFrom(buffer);

    PcepClientImpl pc = new PcepClientImpl();
    PcepPacketStats pktStats = new PcepPacketStatsImpl();

    pc.init(pccId, PcepVersion.PCEP_1, pktStats);
    pc.setChannel(channel);
    pc.setAgent(controllerImpl.agent());
    pc.setConnected(true);
    pc.setCapability(new ClientCapability(true, true, true, true, true));

    controllerImpl.agent().addConnectedClient(pccId, pc);
    controllerImpl.processClientMessage(pccId, message);

    pc.setLspDbSyncStatus(PcepSyncStatus.SYNCED);
    pc.setLabelDbSyncStatus(PcepSyncStatus.IN_SYNC);
    pc.setLabelDbSyncStatus(PcepSyncStatus.SYNCED);
}
 
Example #22
Source File: NdpReplyComponent.java    From ngsdn-tutorial with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all IPv6 addresses associated with the given interface.
 *
 * @param iface interface instance
 * @return collection of IPv6 addresses
 */
private Collection<Ip6Address> getIp6Addresses(Interface iface) {
    return iface.ipAddressesList()
            .stream()
            .map(InterfaceIpAddress::ipAddress)
            .filter(IpAddress::isIp6)
            .map(IpAddress::getIp6Address)
            .collect(Collectors.toSet());
}
 
Example #23
Source File: DeviceConfiguration.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if the host IP is in any of the subnet defined in the router with the
 * device ID given.
 *
 * @param deviceId device identification of the router
 * @param hostIp   host IP address to check
 * @return true if the given IP is within any of the subnet defined in the router,
 * false if no subnet is defined in the router or if the host is not
 * within any subnet defined in the router
 */
public boolean inSameSubnet(DeviceId deviceId, IpAddress hostIp) {
    Set<IpPrefix> subnets = getConfiguredSubnets(deviceId);
    if (subnets == null) {
        return false;
    }

    for (IpPrefix subnet: subnets) {
        // Exclude /0 since it is a special case used for default route
        if (subnet.prefixLength() != 0 && subnet.contains(hostIp)) {
            return true;
        }
    }
    return false;
}
 
Example #24
Source File: K8sIpamWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Requests for releasing the given IP address.
 *
 * @param netId     network identifier
 * @param ip        IP address
 * @return 204 NO CONTENT
 */
@DELETE
@Path("{netId}/{ip}")
public Response releaseIp(@PathParam("netId") String netId,
                          @PathParam("ip") String ip) {
    log.trace("Received IP release request of network " + netId);

    K8sNetwork network =
            nullIsNotFound(networkService.network(netId), NETWORK_ID_NOT_FOUND);

    ipamService.releaseIp(network.networkId(), IpAddress.valueOf(ip));

    return Response.noContent().build();
}
 
Example #25
Source File: LispMapServer.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Sends SMR (Solicit Map Request) to their subscribers.
 *
 * @param eidRecord the updated EID
 */
private void sendSmrMessage(LispEidRecord eidRecord) {

    RequestBuilder builder = new DefaultRequestBuilder();

    LispAfiAddress msAddress = null;
    try {
        msAddress = new LispIpv4Address(IpAddress.valueOf(InetAddress.getLocalHost()));
    } catch (UnknownHostException e) {
        log.warn("Source EID is not found, {}", e.getMessage());
    }

    LispMapRequest msg = builder.withIsSmr(true)
            .withIsSmrInvoked(true)
            .withIsProbe(false)
            .withIsPitr(false)
            .withIsAuthoritative(false)
            .withIsMapDataPresent(false)
            .withSourceEid(msAddress)
            .withEidRecords(ImmutableList.of(eidRecord))
            .build();

    LispRouterFactory routerFactory = LispRouterFactory.getInstance();
    Collection<LispRouter> routers = routerFactory.getRouters();
    routers.forEach(router -> {
        if (isInEidRecordRange(eidRecord, router.getEidRecords())) {
            router.sendMessage(msg);
        }
    });
}
 
Example #26
Source File: FlowInfoJsonCodecTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the flow info encoding.
 */
@Test
public void testEncode() {
    StatsInfo statsInfo = new DefaultStatsInfo.DefaultBuilder()
                                .withStartupTime(LONG_VALUE)
                                .withFstPktArrTime(LONG_VALUE)
                                .withLstPktOffset(INTEGER_VALUE)
                                .withPrevAccBytes(LONG_VALUE)
                                .withPrevAccPkts(INTEGER_VALUE)
                                .withCurrAccBytes(LONG_VALUE)
                                .withCurrAccPkts(INTEGER_VALUE)
                                .withErrorPkts(SHORT_VALUE)
                                .withDropPkts(SHORT_VALUE)
                                .build();
    FlowInfo flowInfo = new DefaultFlowInfo.DefaultBuilder()
                                .withFlowType((byte) FLOW_TYPE)
                                .withDeviceId(DeviceId.deviceId(DEVICE_ID))
                                .withInputInterfaceId(INPUT_INTERFACE_ID)
                                .withOutputInterfaceId(OUTPUT_INTERFACE_ID)
                                .withVlanId(VlanId.vlanId((short) VLAN_ID))
                                .withSrcIp(IpPrefix.valueOf(
                                        IpAddress.valueOf(SRC_IP_ADDRESS), SRC_IP_PREFIX))
                                .withDstIp(IpPrefix.valueOf(
                                        IpAddress.valueOf(DST_IP_ADDRESS), DST_IP_PREFIX))
                                .withSrcPort(TpPort.tpPort(SRC_PORT))
                                .withDstPort(TpPort.tpPort(DST_PORT))
                                .withProtocol((byte) PROTOCOL)
                                .withSrcMac(MacAddress.valueOf(SRC_MAC_ADDRESS))
                                .withDstMac(MacAddress.valueOf(DST_MAC_ADDRESS))
                                .withStatsInfo(statsInfo)
                                .build();

    ObjectNode nodeJson = flowInfoCodec.encode(flowInfo, context);
    assertThat(nodeJson, matchesFlowInfo(flowInfo));

    FlowInfo flowInfoDecoded = flowInfoCodec.decode(nodeJson, context);
    new EqualsTester().addEqualityGroup(flowInfo, flowInfoDecoded).testEquals();
}
 
Example #27
Source File: PIMAddrUnicast.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * PIM Encoded Source Address.
 *
 * @param addr IPv4 or IPv6
 */
public void setAddr(IpAddress addr) {
    this.addr = addr;
    if (this.addr.isIp4()) {
        this.family = PIM.ADDRESS_FAMILY_IP4;
    } else {
        this.family = PIM.ADDRESS_FAMILY_IP6;
    }
}
 
Example #28
Source File: HostMonitorTest.java    From onos with Apache License 2.0 5 votes vote down vote up
private void testMonitorHostExists(IpAddress hostIp) throws Exception {
    ProviderId id = new ProviderId("fake://", "id");

    Host host = createMock(Host.class);
    expect(host.providerId()).andReturn(id).anyTimes();
    replay(host);

    HostManager hostManager = createMock(HostManager.class);
    expect(hostManager.getHostsByIp(hostIp))
            .andReturn(Collections.singleton(host))
            .anyTimes();
    replay(hostManager);

    HostProvider hostProvider = createMock(HostProvider.class);
    expect(hostProvider.id()).andReturn(id).anyTimes();
    hostProvider.triggerProbe(host);
    expectLastCall().times(2);
    replay(hostProvider);

    hostMonitor = new HostMonitor(null, hostManager, null, edgePortService);

    hostMonitor.registerHostProvider(hostProvider);
    hostMonitor.addMonitoringFor(hostIp);

    hostMonitor.run();

    verify(hostProvider);
}
 
Example #29
Source File: McastUtils.java    From onos with Apache License 2.0 5 votes vote down vote up
Map<IpAddress, NodeId> getMcastLeaders(IpAddress mcastIp) {
    // If mcast ip is present
    if (mcastIp != null) {
        return mcastLeaderCache.entrySet().stream()
                .filter(entry -> entry.getKey().equals(mcastIp))
                .collect(Collectors.toMap(Map.Entry::getKey,
                                          Map.Entry::getValue));
    }
    // Otherwise take all the groups
    return ImmutableMap.copyOf(mcastLeaderCache);
}
 
Example #30
Source File: EvpnRouteTable.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<EvpnRoute> getRoutesForNextHop(IpAddress nextHop) {
    // TODO index
    return routes.values().stream()
            .flatMap(v -> v.value().stream())
            .filter(r -> r.nextHop().equals(nextHop))
            .collect(Collectors.toSet());
}