org.onlab.packet.MacAddress Java Examples

The following examples show how to use org.onlab.packet.MacAddress. 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: LinkDiscovery.java    From onos with Apache License 2.0 6 votes vote down vote up
private Optional<Device> findSourceDeviceByChassisId(DeviceService deviceService, MacAddress srcChassisId) {
    Supplier<Stream<Device>> deviceStream = () ->
            StreamSupport.stream(deviceService.getAvailableDevices().spliterator(), false);
    Optional<Device> remoteDeviceOptional = deviceStream.get()
            .filter(device -> device.chassisId() != null
                    && MacAddress.valueOf(device.chassisId().value()).equals(srcChassisId))
            .findAny();

    if (remoteDeviceOptional.isPresent()) {
        log.debug("sourceDevice found by chassis id: {}", srcChassisId);
        return remoteDeviceOptional;
    } else {
        remoteDeviceOptional = deviceStream.get().filter(device ->
                Tools.stream(deviceService.getPorts(device.id()))
                        .anyMatch(port -> port.annotations().keys().contains(AnnotationKeys.PORT_MAC)
                                && MacAddress.valueOf(port.annotations().value(AnnotationKeys.PORT_MAC))
                                .equals(srcChassisId)))
                .findAny();
        if (remoteDeviceOptional.isPresent()) {
            log.debug("sourceDevice found by port mac: {}", srcChassisId);
            return remoteDeviceOptional;
        } else {
            return Optional.empty();
        }
    }
}
 
Example #2
Source File: VplsIntentTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Builds an intent Key either for a single-point to multi-point or
 * multi-point to single-point intent, based on a prefix that defines
 * the intent type, the connection point representing the source or the
 * destination and the VLAN Id representing the VPLS.
 *
 * @param prefix the key prefix
 * @param cPoint the ingress/egress connect point
 * @param vplsName the VPLS name
 * @param hostMac the ingress/egress MAC address
 * @return the key to identify the intent
 */
private Key buildKey(String prefix,
                     ConnectPoint cPoint,
                     String vplsName,
                     MacAddress hostMac) {
    String keyString = vplsName +
            DASH +
            prefix +
            DASH +
            cPoint.deviceId() +
            DASH +
            cPoint.port() +
            DASH +
            hostMac;

    return Key.of(keyString, APPID);
}
 
Example #3
Source File: BgpEvpnRouteType2Nlri.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the Evpn type 2 attributes.
 *
 * @param cb channel buffer
 * @return type2 route
 * @throws BgpParseException parse exception
 */
public static BgpEvpnRouteType2Nlri read(ChannelBuffer cb) throws BgpParseException {
    if (cb.readableBytes() == 0) {
        return null;
    }
    RouteDistinguisher rd = RouteDistinguisher.read(cb);
    BgpEvpnEsi esi = BgpEvpnEsi.read(cb);
    int ethernetTagID = cb.readInt();
    byte macAddressLength = cb.readByte();
    MacAddress macAddress = Validation.toMacAddress(macAddressLength / 8, cb);
    byte ipAddressLength = cb.readByte();
    InetAddress ipAddress = null;
    if (ipAddressLength > 0) {
        ipAddress = Validation.toInetAddress(ipAddressLength / 8, cb);
    }
    BgpEvpnLabel mplsLabel1 = BgpEvpnLabel.read(cb);
    BgpEvpnLabel mplsLabel2 = null;
    if (cb.readableBytes() > 0) {
        mplsLabel2 = BgpEvpnLabel.read(cb);
    }

    return new BgpEvpnRouteType2Nlri(rd, esi, ethernetTagID, macAddress,
                                     ipAddress, mplsLabel1,
                                     mplsLabel2);
}
 
Example #4
Source File: ArpHandler.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Sends an APR request for the target IP address to all ports except in-port.
 *
 * @param deviceId Switch device ID
 * @param targetAddress target IP address for ARP
 * @param inPort in-port
 */
public void sendArpRequest(DeviceId deviceId, IpAddress targetAddress, ConnectPoint inPort) {
    byte[] senderMacAddress = new byte[MacAddress.MAC_ADDRESS_LENGTH];
    byte[] senderIpAddress = new byte[Ip4Address.BYTE_LENGTH];
    /*
     * Retrieves device info.
     */
    if (!getSenderInfo(senderMacAddress, senderIpAddress, deviceId, targetAddress)) {
        log.warn("Aborting sendArpRequest, we cannot get all the information needed");
        return;
    }
    /*
     * Creates the request.
     */
    Ethernet arpRequest = ARP.buildArpRequest(
            senderMacAddress,
            senderIpAddress,
            targetAddress.toOctets(),
            VlanId.NO_VID
    );
    flood(arpRequest, inPort, targetAddress);
}
 
Example #5
Source File: AbstractTopoModelTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a default host connected at the given edge device and port. Note
 * that an identifying hex character ("a" - "f") should be supplied. This
 * will be included in the MAC address of the host (and equivalent value
 * as last byte in IP address).
 *
 * @param device  edge device
 * @param port    port number
 * @param hexChar identifying hex character
 * @return host connected at that location
 */
protected static Host createHost(Device device, int port, String hexChar) {
    DeviceId deviceId = device.id();
    String devNum = deviceId.toString().substring(1);

    MacAddress mac = MacAddress.valueOf(HOST_MAC_PREFIX + devNum + hexChar);
    HostId hostId = hostId(String.format("%s/-1", mac));

    int ipByte = Integer.valueOf(hexChar, 16);
    if (ipByte < 10 || ipByte > 15) {
        throw new IllegalArgumentException("hexChar must be a-f");
    }
    HostLocation loc = new HostLocation(deviceId, portNumber(port), 0);

    IpAddress ip = ip("10." + devNum + ".0." + ipByte);

    return new DefaultHost(ProviderId.NONE, hostId, mac, VlanId.NONE,
            loc, ImmutableSet.of(ip));
}
 
Example #6
Source File: IcmpHandler.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a NDP request for the target IP address to all ports except in-port.
 *
 * @param deviceId Switch device ID
 * @param targetAddress target IP address for ARP
 * @param inPort in-port
 */
public void sendNdpRequest(DeviceId deviceId, IpAddress targetAddress, ConnectPoint inPort) {
    byte[] senderMacAddress = new byte[MacAddress.MAC_ADDRESS_LENGTH];
    byte[] senderIpAddress = new byte[Ip6Address.BYTE_LENGTH];
    // Retrieves device info.
    if (!getSenderInfo(senderMacAddress, senderIpAddress, deviceId, targetAddress)) {
        log.warn("Aborting sendNdpRequest, we cannot get all the information needed");
        return;
    }
    // We have to compute the dst mac address and dst ip address.
    byte[] dstIp = IPv6.getSolicitNodeAddress(targetAddress.toOctets());
    byte[] dstMac = IPv6.getMCastMacAddress(dstIp);
    // Creates the request.
    Ethernet ndpRequest = NeighborSolicitation.buildNdpSolicit(
            targetAddress.getIp6Address(),
            Ip6Address.valueOf(senderIpAddress),
            Ip6Address.valueOf(dstIp),
            MacAddress.valueOf(senderMacAddress),
            MacAddress.valueOf(dstMac),
            VlanId.NONE
    );
    flood(ndpRequest, inPort, targetAddress);
}
 
Example #7
Source File: HostLocationProviderTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public InboundPacket inPacket() {
    RouterAdvertisement ns = new RouterAdvertisement();
    ICMP6 icmp6 = new ICMP6();
    icmp6.setPayload(ns);
    IPv6 ipv6 = new IPv6();
    ipv6.setPayload(icmp6);
    ipv6.setDestinationAddress(Ip6Address.valueOf("ff02::1").toOctets());
    ipv6.setSourceAddress(IP2);
    Ethernet eth = new Ethernet();
    eth.setEtherType(Ethernet.TYPE_IPV6)
            .setVlanID(VLAN.toShort())
            .setSourceMACAddress(MAC2.toBytes())
            .setDestinationMACAddress(MacAddress.valueOf("33:33:00:00:00:01"))
            .setPayload(ipv6);
    ConnectPoint receivedFrom = new ConnectPoint(deviceId(deviceId),
                                                 portNumber(INPORT));
    return new DefaultInboundPacket(receivedFrom, eth,
                                    ByteBuffer.wrap(eth.serialize()));
}
 
Example #8
Source File: InterfaceAddCommand.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
protected void doExecute() {
    InterfaceAdminService interfaceService = get(InterfaceAdminService.class);

    List<InterfaceIpAddress> ipAddresses = Lists.newArrayList();
    if (ips != null) {
        for (String strIp : ips) {
            ipAddresses.add(InterfaceIpAddress.valueOf(strIp));
        }
    }

    MacAddress macAddr = mac == null ? null : MacAddress.valueOf(mac);

    VlanId vlanId = vlan == null ? VlanId.NONE : VlanId.vlanId(Short.parseShort(vlan));

    Interface intf = new Interface(name,
            ConnectPoint.deviceConnectPoint(connectPoint),
            ipAddresses, macAddr, vlanId);

    interfaceService.add(intf);

    print("Interface added");
}
 
Example #9
Source File: VirtualPortWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a Object of the currently known infrastructure virtualPort.
 *
 * @param allowedAddressPairs the allowedAddressPairs json node
 * @return a collection of allowedAddressPair
 */
public Collection<AllowedAddressPair> jsonNodeToAllowedAddressPair(JsonNode allowedAddressPairs) {
    checkNotNull(allowedAddressPairs, JSON_NOT_NULL);
    ConcurrentMap<Integer, AllowedAddressPair> allowMaps = Maps
            .newConcurrentMap();
    int i = 0;
    for (JsonNode node : allowedAddressPairs) {
        IpAddress ip = IpAddress.valueOf(node.get("ip_address").asText());
        MacAddress mac = MacAddress.valueOf(node.get("mac_address")
                .asText());
        AllowedAddressPair allows = AllowedAddressPair
                .allowedAddressPair(ip, mac);
        allowMaps.put(i, allows);
        i++;
    }
    log.debug("The jsonNode of allowedAddressPairallow is {}"
            + allowedAddressPairs.toString());
    return Collections.unmodifiableCollection(allowMaps.values());
}
 
Example #10
Source File: TrafficTreatmentCodecTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests encoding of a traffic treatment object.
 */
@Test
public void testTrafficTreatmentEncode() {

    Instruction output = Instructions.createOutput(PortNumber.portNumber(0));
    Instruction modL2Src = Instructions.modL2Src(MacAddress.valueOf("11:22:33:44:55:66"));
    Instruction modL2Dst = Instructions.modL2Dst(MacAddress.valueOf("44:55:66:77:88:99"));
    MeterId meterId = MeterId.meterId(1);
    Instruction meter = Instructions.meterTraffic(meterId);
    Instruction transition = Instructions.transition(1);
    TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
    TrafficTreatment treatment = tBuilder
            .add(output)
            .add(modL2Src)
            .add(modL2Dst)
            .add(meter)
            .add(transition)
            .build();

    ObjectNode treatmentJson = trafficTreatmentCodec.encode(treatment, context);
    assertThat(treatmentJson, TrafficTreatmentJsonMatcher.matchesTrafficTreatment(treatment));
}
 
Example #11
Source File: OpenstackNetworkManager.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public MacAddress externalPeerRouterMac(ExternalGateway externalGateway) {
    IpAddress ipAddress = getExternalPeerRouterIp(externalGateway);

    if (ipAddress == null) {
        return null;
    }

    ExternalPeerRouter peerRouter =
            osNetworkStore.externalPeerRouter(ipAddress.toString());

    if (peerRouter == null) {
        throw new NoSuchElementException();
    } else {
        return peerRouter.macAddress();
    }
}
 
Example #12
Source File: DefaultFlowInfoTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests object construction.
 */
@Test
public void testConstruction() {
    FlowInfo info = info1;

    assertThat(info.flowType(), is((byte) STATIC_INTEGER_1));
    assertThat(info.inputInterfaceId(), is(STATIC_INTEGER_1));
    assertThat(info.outputInterfaceId(), is(STATIC_INTEGER_1));
    assertThat(info.deviceId(), is(DeviceId.deviceId(STATIC_STRING_1)));
    assertThat(info.srcIp(), is(IpPrefix.valueOf(
            IpAddress.valueOf(IP_ADDRESS_1), IP_PREFIX_LENGTH_1)));
    assertThat(info.dstIp(), is(IpPrefix.valueOf(
            IpAddress.valueOf(IP_ADDRESS_1), IP_PREFIX_LENGTH_1)));
    assertThat(info.srcPort(), is(TpPort.tpPort(PORT_1)));
    assertThat(info.dstPort(), is(TpPort.tpPort(PORT_1)));
    assertThat(info.protocol(), is((byte) STATIC_INTEGER_1));
    assertThat(info.vlanId(), is(VlanId.vlanId(STATIC_STRING_1)));
    assertThat(info.srcMac(), is(MacAddress.valueOf(MAC_ADDRESS_1)));
    assertThat(info.dstMac(), is(MacAddress.valueOf(MAC_ADDRESS_1)));
}
 
Example #13
Source File: HostToHostIntentCompilerTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
@Before
public void setUp() {
    super.setUp();
    Host hostOne = createMock(Host.class);
    expect(hostOne.mac()).andReturn(new MacAddress(HOST_ONE_MAC.getBytes())).anyTimes();
    expect(hostOne.vlan()).andReturn(VlanId.vlanId()).anyTimes();
    replay(hostOne);

    Host hostTwo = createMock(Host.class);
    expect(hostTwo.mac()).andReturn(new MacAddress(HOST_TWO_MAC.getBytes())).anyTimes();
    expect(hostTwo.vlan()).andReturn(VlanId.vlanId()).anyTimes();
    replay(hostTwo);

    mockHostService = createMock(HostService.class);
    expect(mockHostService.getHost(eq(hostOneId))).andReturn(hostOne).anyTimes();
    expect(mockHostService.getHost(eq(hostTwoId))).andReturn(hostTwo).anyTimes();
    replay(mockHostService);
}
 
Example #14
Source File: VplsIntentTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a list of the expected sp2mp intents for a VPLS.
 *
 * @param fcPoints the filtered connect point
 * @param name the name of the VPLS
 * @param encap the encapsulation type
 * @return the list of expected sp2mp intents for the given VPLS
 */
private List<SinglePointToMultiPointIntent>
generateVplsBrc(Set<FilteredConnectPoint> fcPoints, String name, EncapsulationType encap) {
    List<SinglePointToMultiPointIntent> intents = Lists.newArrayList();

    fcPoints.forEach(point -> {
        Set<FilteredConnectPoint> otherPoints =
                fcPoints.stream()
                        .filter(fcp -> !fcp.equals(point))
                        .collect(Collectors.toSet());

        Key brckey = buildKey(VplsIntentUtility.PREFIX_BROADCAST,
                              point.connectPoint(),
                              name,
                              MacAddress.BROADCAST);

        intents.add(buildBrcIntent(brckey, point, otherPoints, encap));
    });

    return intents;
}
 
Example #15
Source File: NdpReplyComponent.java    From onos-p4-tutorial with Apache License 2.0 5 votes vote down vote up
private FlowRule buildNdpReplyFlowRule(DeviceId deviceId,
                                       MacAddress deviceMac,
                                       Ip6Address targetIp) {
    PiCriterion match = PiCriterion.builder()
            .matchExact(PiMatchFieldId.of("hdr.ndp.target_addr"), targetIp.toOctets())
            .build();

    PiActionParam paramRouterMac = new PiActionParam(
            PiActionParamId.of("target_mac"), deviceMac.toBytes());
    PiAction action = PiAction.builder()
            .withId(PiActionId.of("IngressPipeImpl.ndp_ns_to_na"))
            .withParameter(paramRouterMac)
            .build();

    TrafficSelector selector = DefaultTrafficSelector.builder()
            .matchPi(match)
            .build();

    TrafficTreatment treatment = DefaultTrafficTreatment.builder()
            .piTableAction(action)
            .build();

    return DefaultFlowRule.builder()
            .forDevice(deviceId)
            .forTable(PiTableId.of("IngressPipeImpl.ndp_reply_table"))
            .fromApp(appId)
            .makePermanent()
            .withSelector(selector)
            .withTreatment(treatment)
            .withPriority(DEFAULT_FLOW_RULE_PRIORITY)
            .build();
}
 
Example #16
Source File: SimpleFabricRouting.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Emits the specified packet onto the network.
 */
private void forwardPacketToDstIp(PacketContext context, IpAddress nextHopIp,
                                  MacAddress srcMac, boolean updateMac) {
    Set<Host> hosts = hostService.getHostsByIp(nextHopIp);
    Host dstHost;
    if (!hosts.isEmpty()) {
        dstHost = hosts.iterator().next();
    } else {
        // NOTE: hostService.requestMac(nextHopIp); NOT IMPLEMENTED in ONOS HostManager.java; do it myself
        log.warn("forward packet nextHopIp host_mac unknown: nextHopIp={}", nextHopIp);
        hostService.startMonitoringIp(nextHopIp);
        simpleFabric.requestMac(nextHopIp);
        // CONSIDER: make flood on all port of the dstHost's DefaultFabricNetwork
        return;
    }
    TrafficTreatment treatment = DefaultTrafficTreatment.builder()
            .setOutput(dstHost.location().port()).build();
    OutboundPacket outPacket;
    if (updateMac) {
        // NOTE: eth address update by treatment is NOT applied, so update mac myself
        outPacket = new DefaultOutboundPacket(dstHost.location().deviceId(), treatment,
                            ByteBuffer.wrap(context.inPacket().parsed()
                                      .setSourceMACAddress(srcMac)
                                      .setDestinationMACAddress(dstHost.mac()).serialize()));
    } else {
        outPacket = new DefaultOutboundPacket(dstHost.location().deviceId(), treatment,
                            context.inPacket().unparsed());
    }
    // be quiet on normal situation
    log.info("forward packet: nextHopIP={} srcCP={} dstCP={}",
             nextHopIp, context.inPacket().receivedFrom(), dstHost.location());
    packetService.emit(outPacket);
}
 
Example #17
Source File: Ipv6RoutingComponent.java    From ngsdn-tutorial with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an ONOS SELECT group for the routing table to provide ECMP
 * forwarding for the given collection of next hop MAC addresses. ONOS
 * SELECT groups are equivalent to P4Runtime action selector groups.
 * <p>
 * This method will be called by the routing policy methods below to insert
 * groups in the L3 table
 *
 * @param nextHopMacs the collection of mac addresses of next hops
 * @param deviceId    the device where the group will be installed
 * @return a SELECT group
 */
private GroupDescription createNextHopGroup(int groupId,
                                            Collection<MacAddress> nextHopMacs,
                                            DeviceId deviceId) {

    String actionProfileId = "IngressPipeImpl.ecmp_selector";

    final List<PiAction> actions = Lists.newArrayList();

    // Build one "set next hop" action for each next hop
    final String tableId = "IngressPipeImpl.routing_v6_table";
    for (MacAddress nextHopMac : nextHopMacs) {
        final PiAction action = PiAction.builder()
                .withId(PiActionId.of("IngressPipeImpl.set_next_hop"))
                .withParameter(new PiActionParam(
                        // Action param name.
                        PiActionParamId.of("dmac"),
                        // Action param value.
                        nextHopMac.toBytes()))
                .build();

        actions.add(action);
    }

    return Utils.buildSelectGroup(
            deviceId, tableId, actionProfileId, groupId, actions, appId);
}
 
Example #18
Source File: AppConfigHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Processes Segment Routing App Config updated event.
 *
 * @param event network config updated event
 */
protected void processAppConfigUpdated(NetworkConfigEvent event) {
    log.info("Processing AppConfig CONFIG_UPDATED");
    SegmentRoutingAppConfig config = (SegmentRoutingAppConfig) event.config().get();
    SegmentRoutingAppConfig prevConfig = (SegmentRoutingAppConfig) event.prevConfig().get();
    deviceService.getAvailableDevices().forEach(device -> {
        Set<MacAddress> macAddresses = new HashSet<>(getMacAddresses(config));
        Set<MacAddress> prevMacAddresses = new HashSet<>(getMacAddresses(prevConfig));
        // Avoid removing and re-adding unchanged MAC addresses since
        // FlowObjective does not guarantee the execution order.
        Set<MacAddress> sameMacAddresses = new HashSet<>(macAddresses);
        sameMacAddresses.retainAll(prevMacAddresses);
        macAddresses.removeAll(sameMacAddresses);
        prevMacAddresses.removeAll(sameMacAddresses);

        revokeVRouter(device.id(), prevMacAddresses);
        populateVRouter(device.id(), macAddresses);
        Set<IpPrefix> toRemove = Sets.difference(prevConfig.blackholeIPs(), config.blackholeIPs());
        toRemove.forEach(ipPrefix -> {
            srManager.routingRulePopulator.removeDefaultRouteBlackhole(device.id(), ipPrefix);
        });
        Set<IpPrefix> toAdd = Sets.difference(config.blackholeIPs(), prevConfig.blackholeIPs());
        toAdd.forEach(ipPrefix -> {
            srManager.routingRulePopulator.populateDefaultRouteBlackhole(device.id(), ipPrefix);
        });
    });

}
 
Example #19
Source File: VplsIntentUtility.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a broadcast intent.
 *
 * @param key key to identify the intent
 * @param appId application ID for this Intent
 * @param src the source connect point
 * @param dsts the destination connect points
 * @param encap the encapsulation type
 * @param resourceGroup resource group for this Intent
 * @return the generated single-point to multi-point intent
 */
static SinglePointToMultiPointIntent buildBrcIntent(Key key,
                                                              ApplicationId appId,
                                                              FilteredConnectPoint src,
                                                              Set<FilteredConnectPoint> dsts,
                                                              EncapsulationType encap,
                                                              ResourceGroup resourceGroup) {
    log.debug("Building broadcast intent {} for source {}", SP2MP, src);

    SinglePointToMultiPointIntent.Builder intentBuilder;

    TrafficSelector selector = DefaultTrafficSelector.builder()
            .matchEthDst(MacAddress.BROADCAST)
            .build();

    intentBuilder = SinglePointToMultiPointIntent.builder()
            .appId(appId)
            .key(key)
            .selector(selector)
            .filteredIngressPoint(src)
            .filteredEgressPoints(dsts)
            .constraints(PARTIAL_FAILURE_CONSTRAINT)
            .priority(PRIORITY_OFFSET + PRIORITY_BRC)
            .resourceGroup(resourceGroup);

    setEncap(intentBuilder, PARTIAL_FAILURE_CONSTRAINT, encap);

    return intentBuilder.build();
}
 
Example #20
Source File: IsisNeighborTlv.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns TLV body of ISIS neighbor TLV.
 *
 * @return byteArray TLV body of area address TLV
 */
private byte[] tlvBodyAsBytes() {
    List<Byte> bytes = new ArrayList<>();
    for (MacAddress macAddress : this.neighbor) {
        bytes.addAll(Bytes.asList(macAddress.toBytes()));
    }
    return Bytes.toArray(bytes);
}
 
Example #21
Source File: FilteringObjectiveTranslator.java    From onos with Apache License 2.0 5 votes vote down vote up
private Collection<FlowRule> ipFwdClassifierRules(
        PortNumber inPort, MacAddress dstMac, FilteringObjective obj)
        throws FabricPipelinerException {
    final Collection<FlowRule> flowRules = Lists.newArrayList();
    flowRules.add(fwdClassifierRule(
            inPort, Ethernet.TYPE_IPV4, dstMac, null,
            fwdClassifierTreatment(FWD_IPV4_ROUTING), obj));
    flowRules.add(fwdClassifierRule(
            inPort, Ethernet.TYPE_IPV6, dstMac, null,
            fwdClassifierTreatment(FWD_IPV6_ROUTING), obj));
    return flowRules;
}
 
Example #22
Source File: VbngResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new virtual BNG connection.
 *
 * @param privateIp IP Address for the BNG private network
 * @param mac MAC address for the host
 * @param hostName name of the host
 * @return public IP address for the new connection
 */
@POST
@Path("{privateip}/{mac}/{hostname}")
public String privateIpAddNotification(@PathParam("privateip")
        String privateIp, @PathParam("mac") String mac,
        @PathParam("hostname") String hostName) {

    log.info("Received creating vBNG request, "
            + "privateIp= {}, mac={}, hostName= {}",
             privateIp, mac, hostName);

    if (privateIp == null || mac == null || hostName == null) {
        log.info("Parameters can not be null");
        return "0";
    }

    IpAddress privateIpAddress = IpAddress.valueOf(privateIp);
    MacAddress hostMacAddress = MacAddress.valueOf(mac);

    VbngService vbngService = get(VbngService.class);

    IpAddress publicIpAddress = null;
    // Create a virtual BNG
    publicIpAddress = vbngService.createVbng(privateIpAddress,
                                             hostMacAddress,
                                             hostName);

    if (publicIpAddress != null) {
        return publicIpAddress.toString();
    } else {
        return "0";
    }
}
 
Example #23
Source File: DeviceConfiguration.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the IPv6 Node segment id of a segment router given its Router mac address.
 *
 * @param routerMac router mac address
 * @return node segment id, or -1 if not found in config
 */
public int getIPv6SegmentId(MacAddress routerMac) {
    for (Map.Entry<DeviceId, SegmentRouterInfo> entry:
            deviceConfigMap.entrySet()) {
        if (entry.getValue().mac.equals(routerMac)) {
            return entry.getValue().ipv6NodeSid;
        }
    }

    return -1;
}
 
Example #24
Source File: SimpleGroupStoreTest.java    From onos with Apache License 2.0 5 votes vote down vote up
private void testSetBuckets(GroupKey currKey, GroupKey setKey) {
    List<GroupBucket> toSetBuckets = new ArrayList<>();

    short weight = 5;
    PortNumber portNumber = PortNumber.portNumber(42);
    TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
    tBuilder.setOutput(portNumber)
            .setEthDst(MacAddress.valueOf("00:00:00:00:00:03"))
            .setEthSrc(MacAddress.valueOf("00:00:00:00:00:01"))
            .pushMpls()
            .setMpls(MplsLabel.mplsLabel(106));
    toSetBuckets.add(DefaultGroupBucket.createSelectGroupBucket(
            tBuilder.build(), weight));

    GroupBuckets toSetGroupBuckets = new GroupBuckets(toSetBuckets);
    InternalGroupStoreDelegate updateGroupDescDelegate =
            new InternalGroupStoreDelegate(setKey,
                    toSetGroupBuckets,
                    GroupEvent.Type.GROUP_UPDATE_REQUESTED);
    simpleGroupStore.setDelegate(updateGroupDescDelegate);
    simpleGroupStore.updateGroupDescription(D1,
            currKey,
            UpdateType.SET,
            toSetGroupBuckets,
            setKey);
    simpleGroupStore.unsetDelegate(updateGroupDescDelegate);
}
 
Example #25
Source File: InterfaceManagerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddInterface() throws Exception {
    // Create a new InterfaceConfig which will get added
    VlanId vlanId = VlanId.vlanId((short) 1);
    ConnectPoint cp = ConnectPoint.deviceConnectPoint("of:0000000000000001/2");
    Interface newIntf = new Interface(Interface.NO_INTERFACE_NAME, cp,
            Collections.emptyList(),
            MacAddress.valueOf(100),
            vlanId);

    InterfaceConfig ic = new TestInterfaceConfig(cp, Collections.singleton(newIntf));

    subjects.add(cp);
    configs.put(cp, ic);
    interfaces.add(newIntf);

    NetworkConfigEvent event = new NetworkConfigEvent(
            NetworkConfigEvent.Type.CONFIG_ADDED, cp, ic, null, CONFIG_CLASS);

    assertEquals(NUM_INTERFACES, interfaceManager.getInterfaces().size());

    // Send in a config event containing a new interface config
    listener.event(event);

    // Check the new interface exists in the InterfaceManager's inventory
    assertEquals(interfaces, interfaceManager.getInterfaces());
    assertEquals(NUM_INTERFACES + 1, interfaceManager.getInterfaces().size());

    // There are now two interfaces with vlan ID 1
    Set<Interface> byVlan = Sets.newHashSet(createInterface(1), newIntf);
    assertEquals(byVlan, interfaceManager.getInterfacesByVlan(vlanId));
}
 
Example #26
Source File: RemoteMepEntryCodecTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception, CfmConfigException {
    mapper = new ObjectMapper();
    context = new CfmCodecContext();
    remoteMep1 = DefaultRemoteMepEntry
            .builder(MepId.valueOf((short) 10), RemoteMepState.RMEP_OK)
            .failedOrOkTime(Duration.ofMillis(546546546L))
            .interfaceStatusTlvType(InterfaceStatusTlvType.IS_LOWERLAYERDOWN)
            .macAddress(MacAddress.IPV4_MULTICAST)
            .portStatusTlvType(PortStatusTlvType.PS_NO_STATUS_TLV)
            .rdi(true)
            .senderIdTlvType(SenderIdTlvType.SI_NETWORK_ADDRESS)
            .build();
}
 
Example #27
Source File: OvsdbControllerImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Dispatches event to the north.
 *
 * @param clientService OvsdbClientService instance
 * @param row           a new row
 * @param eventType     type of event
 * @param dbSchema      ovsdb database schema
 */
private void dispatchInterfaceEvent(OvsdbClientService clientService,
                                    Row row,
                                    Type eventType,
                                    DatabaseSchema dbSchema) {

    long dpid = getDataPathid(clientService, dbSchema);
    Interface intf = (Interface) TableGenerator
            .getTable(dbSchema, row, OvsdbTable.INTERFACE);
    if (intf == null) {
        return;
    }

    String portType = (String) intf.getTypeColumn().data();
    long localPort = getOfPort(intf);
    if (localPort < 0) {
        return;
    }
    String[] macAndIfaceId = getMacAndIfaceid(intf);
    if (macAndIfaceId == null) {
        return;
    }

    EventSubject eventSubject = new DefaultEventSubject(MacAddress.valueOf(
            macAndIfaceId[0]),
            new HashSet<>(),
                                                        new OvsdbPortName(intf
                                                                                  .getName()),
                                                        new OvsdbPortNumber(localPort),
                                                        new OvsdbDatapathId(Long
                                                                                    .toString(dpid)),
                                                        new OvsdbPortType(portType),
                                                        new OvsdbIfaceId(macAndIfaceId[1]));
    for (OvsdbEventListener listener : ovsdbEventListener) {
        listener.handle(new OvsdbEvent<>(eventType,
                eventSubject));
    }
}
 
Example #28
Source File: RoutingRulePopulator.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Populates IP rules for a route that has direct connection to the switch.
 * This method should not be invoked directly without going through DefaultRoutingHandler.
 *
 * @param deviceId device ID of the device that next hop attaches to
 * @param prefix IP prefix of the route
 * @param hostMac MAC address of the next hop
 * @param hostVlanId Vlan ID of the nexthop
 * @param outPort port where the next hop attaches to
 * @param directHost host is of type direct or indirect
 * @return future that carries the flow objective if succeeded, null if otherwise
 */
CompletableFuture<Objective> populateRoute(DeviceId deviceId, IpPrefix prefix,
                          MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
    log.debug("Populate direct routing entry for route {} at {}:{}",
            prefix, deviceId, outPort);
    ForwardingObjective.Builder fwdBuilder;
    try {
        fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
                                          hostVlanId, outPort, null, null, directHost, false);
    } catch (DeviceConfigNotFoundException e) {
        log.warn(e.getMessage() + " Aborting direct populateRoute");
        return CompletableFuture.completedFuture(null);
    }
    if (fwdBuilder == null) {
        log.warn("Aborting host routing table entry due "
                + "to error for dev:{} route:{}", deviceId, prefix);
        return CompletableFuture.completedFuture(null);
    }

    int nextId = fwdBuilder.add().nextId();
    CompletableFuture<Objective> future = new CompletableFuture<>();
    ObjectiveContext context = new DefaultObjectiveContext(
            (objective) -> {
                log.debug("Direct routing rule for route {} populated. nextId={}", prefix, nextId);
                future.complete(objective);
            },
            (objective, error) -> {
                log.warn("Failed to populate direct routing rule for route {}: {}", prefix, error);
                future.complete(null);
            });
    srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
    rulePopulationCounter.incrementAndGet();
    return future;
}
 
Example #29
Source File: Dhcp6HandlerImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Find first ipaddress for a given Host info i.e.  mac and vlan.
 *
 * @param clientMac client mac
 * @param vlanId  packet's vlan
 * @return next-hop link-local ipaddress for a given host
 */
private IpAddress getFirstIpByHost(Boolean directConnFlag, MacAddress clientMac, VlanId vlanId) {
    IpAddress nextHopIp;
    // pick out the first link-local ip address
    HostId gwHostId = HostId.hostId(clientMac, vlanId);
    Host gwHost = hostService.getHost(gwHostId);
    if (gwHost == null) {
        log.warn("Can't find gateway host for hostId {}", gwHostId);
        return null;
    }
    if (directConnFlag) {
        nextHopIp = gwHost.ipAddresses()
                .stream()
                .filter(IpAddress::isIp6)
                .map(IpAddress::getIp6Address)
                .findFirst()
                .orElse(null);
    } else {
        nextHopIp = gwHost.ipAddresses()
                .stream()
                .filter(IpAddress::isIp6)
                .filter(ip6 -> ip6.isLinkLocal())
                .map(IpAddress::getIp6Address)
                .findFirst()
                .orElse(null);
    }
    return nextHopIp;
}
 
Example #30
Source File: DhcpWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Post a new static MAC/IP binding.
 * Registers a static binding to the DHCP server, and displays the current set of bindings.
 *
 * @onos.rsModel DhcpConfigPut
 * @param stream JSON stream
 * @return 200 OK
 */
@POST
@Path("mappings")
@Consumes(MediaType.APPLICATION_JSON)
public Response setMapping(InputStream stream) {
    ObjectNode root = mapper().createObjectNode();
    try {
        ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
        JsonNode macID = jsonTree.get("mac");
        JsonNode ip = jsonTree.get("ip");
        if (macID != null && ip != null) {
            IpAssignment ipAssignment = IpAssignment.builder()
                    .ipAddress(Ip4Address.valueOf(ip.asText()))
                    .leasePeriod(service.getLeaseTime())
                    .timestamp(new Date())
                    .assignmentStatus(Option_Requested)
                    .build();

            if (!service.setStaticMapping(MacAddress.valueOf(macID.asText()),
                                          ipAssignment)) {
                throw new IllegalArgumentException("Static Mapping Failed. " +
                                                           "The IP maybe unavailable.");
            }
        }

        final Map<HostId, IpAssignment> intents = service.listMapping();
        ArrayNode arrayNode = root.putArray("mappings");
        intents.entrySet().forEach(i -> arrayNode.add(mapper().createObjectNode()
                                                              .put("host", i.getKey().toString())
                                                              .put("ip", i.getValue().ipAddress().toString())));
    } catch (IOException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
    return ok(root).build();
}