Java Code Examples for org.onlab.packet.MacAddress#valueOf()

The following examples show how to use org.onlab.packet.MacAddress#valueOf() . 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: Dhcp4HandlerImpl.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Writes DHCP record to the store according to the request DHCP packet (Discover, Request).
 *
 * @param location the location which DHCP packet comes from
 * @param ethernet the DHCP packet
 * @param dhcpPayload the DHCP payload
 */
private void writeRequestDhcpRecord(ConnectPoint location,
                                    Ethernet ethernet,
                                    DHCP dhcpPayload) {
    VlanId vlanId = VlanId.vlanId(ethernet.getVlanID());
    MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
    HostId hostId = HostId.hostId(macAddress, vlanId);
    DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
    if (record == null) {
        record = new DhcpRecord(HostId.hostId(macAddress, vlanId));
    } else {
        record = record.clone();
    }
    record.addLocation(new HostLocation(location, System.currentTimeMillis()));
    record.ip4Status(dhcpPayload.getPacketType());
    record.setDirectlyConnected(directlyConnected(dhcpPayload));
    if (!directlyConnected(dhcpPayload)) {
        // Update gateway mac address if the host is not directly connected
        record.nextHop(ethernet.getSourceMAC());
    }
    record.updateLastSeen();
    dhcpRelayStore.updateDhcpRecord(HostId.hostId(macAddress, vlanId), record);
}
 
Example 2
Source File: PiCriterionTranslatorsTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Test
public void testArpHaCriterionn() throws Exception {
    MacAddress mac = MacAddress.valueOf(random.nextLong());
    int bitWidth = mac.toBytes().length * 8;

    ArpHaCriterion criterion = (ArpHaCriterion) Criteria.matchArpTha(mac);

    PiExactFieldMatch exactMatch = (PiExactFieldMatch) translateCriterion(criterion, fieldId, EXACT, bitWidth);

    assertThat(exactMatch.value().asArray(), is(criterion.mac().toBytes()));
}
 
Example 3
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 4
Source File: Dhcp4HandlerImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Writes DHCP record to the store according to the response DHCP packet (Offer, Ack).
 *
 * @param ethernet the DHCP packet
 * @param dhcpPayload the DHCP payload
 */
private void writeResponseDhcpRecord(Ethernet ethernet,
                                     DHCP dhcpPayload) {
    Optional<Interface> outInterface = getClientInterface(ethernet, dhcpPayload);
    if (!outInterface.isPresent()) {
        log.warn("Failed to determine where to send {}", dhcpPayload.getPacketType());
        return;
    }

    Interface outIface = outInterface.get();
    ConnectPoint location = outIface.connectPoint();
    VlanId vlanId = getVlanIdFromRelayAgentOption(dhcpPayload);
    if (vlanId == null) {
        vlanId = outIface.vlan();
    }
    MacAddress macAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
    HostId hostId = HostId.hostId(macAddress, vlanId);
    DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);
    if (record == null) {
        record = new DhcpRecord(HostId.hostId(macAddress, vlanId));
    } else {
        record = record.clone();
    }
    record.addLocation(new HostLocation(location, System.currentTimeMillis()));
    if (dhcpPayload.getPacketType() == DHCP.MsgType.DHCPACK) {
        record.ip4Address(Ip4Address.valueOf(dhcpPayload.getYourIPAddress()));
    }
    record.ip4Status(dhcpPayload.getPacketType());
    record.setDirectlyConnected(directlyConnected(dhcpPayload));
    record.updateLastSeen();
    dhcpRelayStore.updateDhcpRecord(HostId.hostId(macAddress, vlanId), record);
}
 
Example 5
Source File: VtnManager.java    From onos with Apache License 2.0 5 votes vote down vote up
private void arprequestProcess(ARP arpPacket, DeviceId deviceId) {
    MacAddress dstMac = MacAddress
            .valueOf(arpPacket.getSenderHardwareAddress());
    IpAddress srcIp = IpAddress.valueOf(IPv4
            .toIPv4Address(arpPacket.getTargetProtocolAddress()));
    IpAddress dstIp = IpAddress.valueOf(IPv4
            .toIPv4Address(arpPacket.getSenderProtocolAddress()));
    FloatingIp floatingIp = floatingIpStore.get(srcIp);
    if (floatingIp == null) {
        return;
    }
    DeviceId deviceIdOfFloatingIp = getDeviceIdOfFloatingIP(floatingIp);
    if (!deviceId.equals(deviceIdOfFloatingIp)) {
        return;
    }
    Port exPort = exPortOfDevice.get(deviceId);
    MacAddress srcMac = MacAddress.valueOf(exPort.annotations()
            .value(AnnotationKeys.PORT_MAC));
    if (!downloadSnatRules(deviceId, srcMac, srcIp, dstMac, dstIp,
                           floatingIp)) {
        return;
    }
    Ethernet ethernet = buildArpResponse(dstIp, dstMac, srcIp, srcMac);
    if (ethernet != null) {
        sendPacketOut(deviceId, exPort.number(), ethernet);
    }
}
 
Example 6
Source File: ObstacleConstraintTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    resourceContext = createMock(ResourceContext.class);

    link1 = DefaultLink.builder()
            .providerId(PROVIDER_ID)
            .src(cp(DID1, PN1))
            .dst(cp(DID2, PN2))
            .type(DIRECT)
            .build();
    link2 = DefaultLink.builder()
            .providerId(PROVIDER_ID)
            .src(cp(DID2, PN3))
            .dst(cp(DID3, PN4))
            .type(DIRECT)
            .build();
    host1 = new DefaultHost(PROVIDER_ID, HostId.hostId("00:00:00:00:00:01/None"),
            MacAddress.valueOf(0), VlanId.vlanId(),
            new HostLocation(DID5, PN1, 1),
            ImmutableSet.of(), DefaultAnnotations.EMPTY);
    host2 = new DefaultHost(PROVIDER_ID, HostId.hostId("00:00:00:00:00:02/None"),
            MacAddress.valueOf(0), VlanId.vlanId(),
            new HostLocation(DID6, PN1, 1),
            ImmutableSet.of(), DefaultAnnotations.EMPTY);
    edgelink1 = createEdgeLink(host1, true);
    edgelink2 = createEdgeLink(host2, false);

    path = new DefaultPath(PROVIDER_ID, Arrays.asList(link1, link2), ScalarWeight.toWeight(10));
    pathWithEdgeLink = new DefaultPath(PROVIDER_ID,
            Arrays.asList(edgelink1, link1, link2, edgelink2), ScalarWeight.toWeight(10));
}
 
Example 7
Source File: Controller.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns interface MAC by index.
 *
 * @param interfaceIndex interface index
 * @return interface IP by index
 */
private MacAddress getInterfaceMac(int interfaceIndex) {
    MacAddress macAddress = null;
    try {
        NetworkInterface networkInterface = NetworkInterface.getByIndex(interfaceIndex);
        macAddress = MacAddress.valueOf(networkInterface.getHardwareAddress());
    } catch (Exception e) {
        log.debug("Error while getting Interface IP by index");
        return macAddress;
    }

    return macAddress;
}
 
Example 8
Source File: HostId.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a device id using the supplied ID string.
 *
 * @param string device URI string
 * @return host identifier
 */
public static HostId hostId(String string) {
    checkArgument(string.length() >= MIN_ID_LENGTH,
                  "Host ID must be at least %s characters", MIN_ID_LENGTH);
    MacAddress mac = MacAddress.valueOf(string.substring(0, MAC_LENGTH));
    VlanId vlanId = VlanId.vlanId(string.substring(MAC_LENGTH + 1));
    return new HostId(mac, vlanId);
}
 
Example 9
Source File: LispMacAddress.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public LispMacAddress readFrom(ByteBuf byteBuf) throws LispParseError {

    byte[] macByte = new byte[SIZE_OF_MAC_ADDRESS];
    byteBuf.readBytes(macByte);
    MacAddress macAddress = MacAddress.valueOf(macByte);

    return new LispMacAddress(macAddress);
}
 
Example 10
Source File: DecodeCriterionCodecHelper.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public Criterion decodeCriterion(ObjectNode json) {
    MacAddress mac = MacAddress.valueOf(nullIsIllegal(json.get(CriterionCodec.MAC),
            CriterionCodec.MAC + MISSING_MEMBER_MESSAGE).asText());
    return Criteria.matchIPv6NDSourceLinkLayerAddress(mac);
}
 
Example 11
Source File: BasePortManager.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a collection of basePorts from subnetNodes.
 *
 * @param vPortNodes the basePort json node
 * @return BasePort collection of vpn ports
 */
private Collection<BasePort> changeJsonToSub(JsonNode vPortNodes) {
    checkNotNull(vPortNodes, JSON_NOT_NULL);
    Set<FixedIp> fixedIps = null;
    TenantNetworkId tenantNetworkId = null;
    Map<BasePortId, BasePort> vportMap = new HashMap<>();
    Map<String, String> strMap = new HashMap<>();
    BasePortId basePortId = BasePortId.portId(vPortNodes.get("id").asText());
    String name = vPortNodes.get("name").asText();
    TenantId tenantId = TenantId
            .tenantId(vPortNodes.get("tenant_id").asText());
    Boolean adminStateUp = vPortNodes.get("admin_state_up").asBoolean();
    String state = vPortNodes.get("status").asText();
    MacAddress macAddress = MacAddress
            .valueOf(vPortNodes.get("mac_address").asText());
    DeviceId deviceId = DeviceId
            .deviceId(vPortNodes.get("device_id").asText());
    String deviceOwner = vPortNodes.get("device_owner").asText();
    BindingHostId bindingHostId = BindingHostId
            .bindingHostId(vPortNodes.get("host_id").asText());
    String bindingVnicType = vPortNodes.get("vnic_type").asText();
    String bindingVifType = vPortNodes.get("vif_type").asText();
    String bindingVifDetails = vPortNodes.get("vif_details").asText();
    strMap.put("name", name);
    strMap.put("deviceOwner", deviceOwner);
    strMap.put("bindingVnicType", bindingVnicType);
    strMap.put("bindingVifType", bindingVifType);
    strMap.put("bindingVifDetails", bindingVifDetails);
    BasePort prevBasePort = getPort(basePortId);
    if (prevBasePort != null) {
        fixedIps = prevBasePort.fixedIps();
        tenantNetworkId = prevBasePort.networkId();
    }
    BasePort vPort = new DefaultBasePort(basePortId,
                                         tenantNetworkId,
                                         adminStateUp,
                                         strMap, state,
                                         macAddress, tenantId,
                                         deviceId, fixedIps,
                                         bindingHostId,
                                         null,
                                         null);
    vportMap.put(basePortId, vPort);

    return Collections.unmodifiableCollection(vportMap.values());
}
 
Example 12
Source File: Dhcp4HandlerImpl.java    From onos with Apache License 2.0 4 votes vote down vote up
private void handleLeaseQueryUnknown(Ethernet packet, DHCP dhcpPayload) {
    log.debug("Lease Query for Client results in DHCPLEASEUNASSIGNED or " +
                      "DHCPLEASEUNKNOWN - removing route & forwarding reply to originator");
    if (learnRouteFromLeasequery) {
        MacAddress clientMacAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
        VlanId vlanId = VlanId.vlanId(packet.getVlanID());
        HostId hostId = HostId.hostId(clientMacAddress, vlanId);
        DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);

        if (record == null) {
            log.warn("Can't find record for host {} when handling LQ UNKNOWN/UNASSIGNED message", hostId);
            return;
        }

        Ip4Address clientIP = record.ip4Address().orElse(null);
        log.debug("LQ: IP of host is " + clientIP.getIp4Address());

        // find the new NH by looking at the src MAC of the dhcp request
        // from the LQ store
        MacAddress nextHopMac = record.nextHop().orElse(null);
        log.debug("LQ: MAC of resulting *Existing* NH for that route is " + nextHopMac.toString());

        // find the next hop IP from its mac
        HostId gwHostId = HostId.hostId(nextHopMac, vlanId);
        Host gwHost = hostService.getHost(gwHostId);

        if (gwHost == null) {
            log.warn("Can't find gateway for new NH host " + gwHostId);
            return;
        }

        Ip4Address nextHopIp = gwHost.ipAddresses()
                .stream()
                .filter(IpAddress::isIp4)
                .map(IpAddress::getIp4Address)
                .findFirst()
                .orElse(null);

        if (nextHopIp == null) {
            log.warn("Can't find IP address of gateway {}", gwHost);
            return;
        }

        log.debug("LQ: *Existing* NH IP for host is " + nextHopIp.getIp4Address() + " removing route for it");
        Route route = new Route(Route.Source.DHCP, clientIP.toIpPrefix(), nextHopIp);
        routeStore.removeRoute(route);

        // remove from temp store
        dhcpRelayStore.removeDhcpRecord(hostId);
    }
    // and forward to client
    InternalPacket ethernetPacket = processLeaseQueryFromServer(packet);
    if (ethernetPacket != null) {
        sendResponseToClient(ethernetPacket, dhcpPayload);
    }
}
 
Example 13
Source File: MockAttachment.java    From onos with Apache License 2.0 4 votes vote down vote up
MockAttachment(int seed) {
    this.stag = VlanId.vlanId((short) seed);
    this.ctag = VlanId.vlanId((short) seed);
    this.macAddress = MacAddress.valueOf(seed);
}
 
Example 14
Source File: ScaleTestManager.java    From onos with Apache License 2.0 4 votes vote down vote up
private MacAddress randomMac() {
    return MacAddress.valueOf(macBase++);
}
 
Example 15
Source File: DefaultHostProbeStore.java    From onos with Apache License 2.0 4 votes vote down vote up
private MacAddress generateProbeMac() {
    // Use ONLab OUI (3 bytes) + atomic counter (3 bytes) as the source MAC of the probe
    long nextIndex = hostProbeIndex.incrementAndGet();
    return MacAddress.valueOf(MacAddress.NONE.toLong() + nextIndex);
}
 
Example 16
Source File: CastorArpManager.java    From onos with Apache License 2.0 4 votes vote down vote up
public MacAddress srcMac() {
    return MacAddress.valueOf(eth.getSourceMACAddress());
}
 
Example 17
Source File: Dhcp4HandlerImpl.java    From onos with Apache License 2.0 4 votes vote down vote up
private void handleLeaseQueryActivateMsg(Ethernet packet, DHCP dhcpPayload) {
    log.debug("LQ: Got DHCPLEASEACTIVE packet!");

    if (learnRouteFromLeasequery) {
        // TODO: release the ip address from client
        MacAddress clientMacAddress = MacAddress.valueOf(dhcpPayload.getClientHardwareAddress());
        VlanId vlanId = VlanId.vlanId(packet.getVlanID());
        HostId hostId = HostId.hostId(clientMacAddress, vlanId);
        DhcpRecord record = dhcpRelayStore.getDhcpRecord(hostId).orElse(null);

        if (record == null) {
            log.warn("Can't find record for host {} when processing DHCPLEASEACTIVE", hostId);
            return;
        }

        // need to update routes
        log.debug("Lease Query for Client results in DHCPLEASEACTIVE - route needs to be modified");
        // get current route
        // find the ip of that client with the DhcpRelay store

        Ip4Address clientIP = record.ip4Address().orElse(null);
        log.debug("LQ: IP of host is " + clientIP.getIp4Address());

        MacAddress nextHopMac = record.nextHop().orElse(null);
        log.debug("LQ: MAC of resulting *OLD* NH for that host is " + nextHopMac.toString());

        // find the new NH by looking at the src MAC of the dhcp request
        // from the LQ store
        MacAddress newNextHopMac = record.nextHopTemp().orElse(null);
        log.debug("LQ: MAC of resulting *NEW* NH for that host is " + newNextHopMac.toString());

        log.debug("LQ: updating dhcp relay record with new NH");
        record.nextHop(newNextHopMac);

        // find the next hop IP from its mac
        HostId gwHostId = HostId.hostId(newNextHopMac, vlanId);
        Host gwHost = hostService.getHost(gwHostId);

        if (gwHost == null) {
            log.warn("Can't find gateway for new NH host " + gwHostId);
            return;
        }

        Ip4Address nextHopIp = gwHost.ipAddresses()
                .stream()
                .filter(IpAddress::isIp4)
                .map(IpAddress::getIp4Address)
                .findFirst()
                .orElse(null);

        if (nextHopIp == null) {
            log.warn("Can't find IP address of gateway " + gwHost);
            return;
        }

        log.debug("LQ: *NEW* NH IP for host is " + nextHopIp.getIp4Address());
        Route route = new Route(Route.Source.DHCP, clientIP.toIpPrefix(), nextHopIp);
        routeStore.updateRoute(route);
    }

    // and forward to client
    InternalPacket ethernetPacket = processLeaseQueryFromServer(packet);
    if (ethernetPacket != null) {
        sendResponseToClient(ethernetPacket, dhcpPayload);
    }
}
 
Example 18
Source File: DefaultK8sNode.java    From onos with Apache License 2.0 4 votes vote down vote up
private MacAddress macAddress(DeviceId deviceId, String portName) {
    Port port = port(deviceId, portName);
    Annotations annots = port.annotations();
    return annots != null ? MacAddress.valueOf(annots.value(PORT_MAC)) : null;
}
 
Example 19
Source File: OpenstackSwitchingArpHandler.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Processes ARP request packets.
 * It checks if the target IP is owned by a known host first and then ask to
 * OpenStack if it's not. This ARP proxy does not support overlapping IP.
 *
 * @param context   packet context
 * @param ethPacket ethernet packet
 */
private void processPacketIn(PacketContext context, Ethernet ethPacket) {

    // if the ARP mode is configured as broadcast mode, we simply ignore ARP packet_in
    if (ARP_BROADCAST_MODE.equals(getArpMode())) {
        return;
    }

    ARP arpPacket = (ARP) ethPacket.getPayload();
    if (arpPacket.getOpCode() != ARP.OP_REQUEST) {
        return;
    }

    InstancePort srcInstPort = instancePortService.instancePort(ethPacket.getSourceMAC());
    if (srcInstPort == null) {
        log.trace("Failed to find source instance port(MAC:{})",
                ethPacket.getSourceMAC());
        return;
    }

    IpAddress targetIp = Ip4Address.valueOf(arpPacket.getTargetProtocolAddress());

    MacAddress replyMac = isGatewayIp(targetIp) ? MacAddress.valueOf(gatewayMac) :
            getMacFromHostOpenstack(targetIp, srcInstPort.networkId());
    if (replyMac == MacAddress.NONE) {
        log.trace("Failed to find MAC address for {}", targetIp);
        return;
    }

    Ethernet ethReply = ARP.buildArpReply(
            targetIp.getIp4Address(),
            replyMac,
            ethPacket);

    TrafficTreatment treatment = DefaultTrafficTreatment.builder()
            .setOutput(context.inPacket().receivedFrom().port())
            .build();

    packetService.emit(new DefaultOutboundPacket(
            context.inPacket().receivedFrom().deviceId(),
            treatment,
            ByteBuffer.wrap(ethReply.serialize())));
}
 
Example 20
Source File: ReactiveRoutingConfig.java    From onos with Apache License 2.0 2 votes vote down vote up
/**
 *  Gets of the virtual gateway MAC address.
 *
 * @return virtual gateway MAC address
 */
public MacAddress virtualGatewayMacAddress() {
    return MacAddress.valueOf(
            object.get(VIRTUALGATEWAYMACADDRESS).asText());
}