/** * Checks whether the frame is destined to or from a gateway. * @param frame The ethernet frame to check. * @return True if it is to/from a gateway, false otherwise. */ protected boolean isDefaultGateway(Ethernet frame) { if (macToGateway.containsKey(frame.getSourceMACAddress())) return true; IPv4Address gwIp = macToGateway.get(frame.getDestinationMACAddress()); if (gwIp != null) { MacAddress host = frame.getSourceMACAddress(); String srcNet = macToGuid.get(host); if (srcNet != null) { IPv4Address gwIpSrcNet = guidToGateway.get(srcNet); if ((gwIpSrcNet != null) && (gwIp.equals(gwIpSrcNet))) return true; } } return false; }
@Test public void testUncastPacket() { // Generate the VerificationPacket OFPacketOut packet = pvs.generateVerificationPacket(sw1, OFPort.of(1), sw2); // Source MAC will always be that of sw1 for both Unicast and Broadcast byte[] srcMacActual = Arrays.copyOfRange(packet.getData(), 6, 12); assertArrayEquals(MacAddress.of(sw1HwAddrTarget).getBytes(), srcMacActual); // Destination MAC should be that of sw2 for Unicast Packet byte[] dstMacActual = Arrays.copyOfRange(packet.getData(), 0, 6); assertArrayEquals(MacAddress.of(sw2HwAddrTarget).getBytes(), dstMacActual); // Source and Destination IP's are the respective switch IP's byte[] srcIpActual = Arrays.copyOfRange(packet.getData(), 26, 30); assertArrayEquals(srcIpTarget.getAddress().getAddress(), srcIpActual); byte[] dstIpActual = Arrays.copyOfRange(packet.getData(), 30, 34); assertArrayEquals(dstIpTarget.getAddress().getAddress(), dstIpActual); }
/** * Verify that the given device exactly matches the given fields. E.g., * if ip is not null we expect the device to have exactly one IP address. * swId and port are the attachment point port. * Vlan and ip are optional all other fields must be specified. * @return */ private static void verifyDevice(IDevice d, MacAddress mac, VlanVid vlan, IPv4Address ipv4, IPv6Address ipv6, DatapathId swId, OFPort port) { assertNotNull(d); if (!mac.equals(MacAddress.NONE)) { assertEquals(mac, d.getMACAddress()); } if (vlan != null) { assertArrayEquals(new VlanVid[] { vlan }, d.getVlanId()); } if (!ipv4.equals(IPv4Address.NONE)) { assertArrayEquals(new IPv4Address[] { ipv4 }, d.getIPv4Addresses()); } if (!ipv6.equals(IPv6Address.NONE)) { assertArrayEquals(new IPv6Address[] { ipv6 }, d.getIPv6Addresses()); } if (!swId.equals(DatapathId.NONE) && !port.equals(OFPort.ZERO)) { SwitchPort expectedAp = new SwitchPort(swId, port); assertArrayEquals(new SwitchPort[] { expectedAp }, d.getAttachmentPoints()); } }
@Test public void testGetSwitchPortVlanId() { Entity entity1 = new Entity(MacAddress.of(1L), VlanVid.ofVlan(1), IPv4Address.NONE, IPv6Address.NONE, DatapathId.of(10L), OFPort.of(1), new Date()); Entity entity2 = new Entity(MacAddress.of(1L), VlanVid.ZERO, IPv4Address.NONE, IPv6Address.NONE, DatapathId.of(10L), OFPort.of(1), new Date()); Entity entity3 = new Entity(MacAddress.of(1L), VlanVid.ofVlan(3), IPv4Address.NONE, IPv6Address.NONE, DatapathId.of(1L), OFPort.of(1), new Date()); Entity entity4 = new Entity(MacAddress.of(1L), VlanVid.ofVlan(42), IPv4Address.NONE, IPv6Address.NONE, DatapathId.of(1L), OFPort.of(1), new Date()); Entity[] entities = new Entity[] { entity1, entity2, entity3, entity4 }; Device d = new Device(null,1L, null, null, null, Arrays.asList(entities), null); SwitchPort swp1x1 = new SwitchPort(DatapathId.of(1L), OFPort.of(1)); SwitchPort swp1x2 = new SwitchPort(DatapathId.of(1L), OFPort.of(2)); SwitchPort swp2x1 = new SwitchPort(DatapathId.of(2L), OFPort.of(1)); SwitchPort swp10x1 = new SwitchPort(DatapathId.of(10L), OFPort.of(1)); assertArrayEquals(new VlanVid[] { VlanVid.ZERO, VlanVid.ofVlan(1)}, d.getSwitchPortVlanIds(swp10x1)); assertArrayEquals(new VlanVid[] { VlanVid.ofVlan(3), VlanVid.ofVlan(42)}, d.getSwitchPortVlanIds(swp1x1)); assertArrayEquals(new VlanVid[0], d.getSwitchPortVlanIds(swp1x2)); assertArrayEquals(new VlanVid[0], d.getSwitchPortVlanIds(swp2x1)); }
/** * Construct a new device iterator over the key fields * @param subIterator an iterator over the full data structure to scan * @param entityClasses the entity classes to search for * @param macAddress The MAC address * @param vlan the VLAN * @param ipv4Address the ipv4 address * @param ipv6Address the ipv6 address * @param switchDPID the switch DPID * @param switchPort the switch port */ public DeviceIterator(Iterator<Device> subIterator, IEntityClass[] entityClasses, MacAddress macAddress, VlanVid vlan, IPv4Address ipv4Address, IPv6Address ipv6Address, DatapathId switchDPID, OFPort switchPort) { super(subIterator); this.entityClasses = entityClasses; this.subIterator = subIterator; this.macAddress = macAddress; this.vlan = vlan; this.ipv4Address = ipv4Address; this.ipv6Address = ipv6Address; this.switchDPID = switchDPID; this.switchPort = switchPort; }
@Override public void init(FloodlightModuleContext context) throws FloodlightModuleException { floodlightProviderService = context.getServiceImpl(IFloodlightProviderService.class); restApiService = context.getServiceImpl(IRestApiService.class); deviceService = context.getServiceImpl(IDeviceService.class); vNetsByGuid = new ConcurrentHashMap<String, VirtualNetwork>(); nameToGuid = new ConcurrentHashMap<String, String>(); guidToGateway = new ConcurrentHashMap<String, IPv4Address>(); gatewayToGuid = new ConcurrentHashMap<IPv4Address, Set<String>>(); macToGuid = new ConcurrentHashMap<MacAddress, String>(); portToMac = new ConcurrentHashMap<String, MacAddress>(); macToGateway = new ConcurrentHashMap<MacAddress, IPv4Address>(); deviceListener = new DeviceListenerImpl(); }
@Override public void addHost(MacAddress mac, String guid, String port) { if (guid != null) { if (log.isDebugEnabled()) { log.debug("Adding {} to network ID {} on port {}", new Object[] {mac, guid, port}); } // We ignore old mappings macToGuid.put(mac, guid); portToMac.put(port, mac); if (vNetsByGuid.get(guid) != null) vNetsByGuid.get(guid).addHost(port, mac); } else { log.warn("Could not add MAC {} to network ID {} on port {}, the network does not exist", new Object[] {mac.toString(), guid, port}); } }
protected Match createMatchFromPacket(IOFSwitch sw, OFPort inPort, FloodlightContext cntx) { // The packet in match will only contain the port number. // We need to add in specifics for the hosts we're routing between. Ethernet eth = IFloodlightProviderService.bcStore.get(cntx, IFloodlightProviderService.CONTEXT_PI_PAYLOAD); VlanVid vlan = VlanVid.ofVlan(eth.getVlanID()); MacAddress srcMac = eth.getSourceMACAddress(); MacAddress dstMac = eth.getDestinationMACAddress(); Match.Builder mb = sw.getOFFactory().buildMatch(); mb.setExact(MatchField.IN_PORT, inPort) .setExact(MatchField.ETH_SRC, srcMac) .setExact(MatchField.ETH_DST, dstMac); if (!vlan.equals(VlanVid.ZERO)) { mb.setExact(MatchField.VLAN_VID, OFVlanVidMatch.ofVlanVid(vlan)); } return mb.build(); }
@Put public String addHost(String postData) { IVirtualNetworkService vns = (IVirtualNetworkService)getContext().getAttributes(). get(IVirtualNetworkService.class.getCanonicalName()); HostDefinition host = new HostDefinition(); host.port = (String) getRequestAttributes().get("port"); host.guid = (String) getRequestAttributes().get("network"); try { jsonToHostDefinition(postData, host); } catch (IOException e) { log.error("Could not parse JSON {}", e.getMessage()); } vns.addHost(MacAddress.of(host.mac), host.guid, host.port); setStatus(Status.SUCCESS_OK); return "{\"status\":\"ok\"}"; }
@Test public void testLastSeen() throws Exception { Calendar c = Calendar.getInstance(); Date d1 = c.getTime(); Entity entity1 = new Entity(MacAddress.of(1L), null, null, null, null, d1); c.add(Calendar.SECOND, 1); Entity entity2 = new Entity(MacAddress.of(1L), null, IPv4Address.of(1), null, null, c.getTime()); IDevice d = deviceManager.learnDeviceByEntity(entity2); assertEquals(c.getTime(), d.getLastSeen()); d = deviceManager.learnDeviceByEntity(entity1); assertEquals(c.getTime(), d.getLastSeen()); deviceManager.startUp(null); d = deviceManager.learnDeviceByEntity(entity1); assertEquals(d1, d.getLastSeen()); d = deviceManager.learnDeviceByEntity(entity2); assertEquals(c.getTime(), d.getLastSeen()); }
@Override public void deleteHost(MacAddress mac, String port) { if (log.isDebugEnabled()) { log.debug("Removing host {} from port {}", mac, port); } if (mac == null && port == null) return; if (port != null) { MacAddress host = portToMac.remove(port); if (host != null && vNetsByGuid.get(macToGuid.get(host)) != null) vNetsByGuid.get(macToGuid.get(host)).removeHost(host); if (host != null) macToGuid.remove(host); } else if (mac != null) { if (!portToMac.isEmpty()) { for (Entry<String, MacAddress> entry : portToMac.entrySet()) { if (entry.getValue().equals(mac)) { if (vNetsByGuid.get(macToGuid.get(entry.getValue())) != null) vNetsByGuid.get(macToGuid.get(entry.getValue())).removeHost(entry.getValue()); portToMac.remove(entry.getKey()); macToGuid.remove(entry.getValue()); return; } } } } }
public LBVip() { this.id = String.valueOf((int) (Math.random()*10000)); this.name = null; this.tenantId = null; this.netId = null; this.address = 0; this.protocol = 0; this.lbMethod = 0; this.port = 0; this.pools = new ArrayList<String>(); this.sessionPersistence = false; this.connectionLimit = 0; this.address = 0; this.status = 0; this.proxyMac = MacAddress.of(LB_PROXY_MAC); }
/** * Parse set_dl_src actions. * The key and delimiter for the action should be omitted, and only the * data should be presented to this decoder. * * TODO should consider using MacAddress's built-in parser.... * * @param actionToDecode; The action as a string to decode * @param version; The OF version to create the action for * @param log * @return */ private static OFActionSetDlSrc decode_set_src_mac(String actionToDecode, OFVersion version, Logger log) { Matcher n = Pattern.compile("(?:(\\p{XDigit}+)\\:(\\p{XDigit}+)\\:(\\p{XDigit}+)\\:(\\p{XDigit}+)\\:(\\p{XDigit}+)\\:(\\p{XDigit}+))").matcher(actionToDecode); if (n.matches()) { MacAddress macaddr = MacAddress.of(get_mac_addr(n, actionToDecode, log)); if (macaddr != null) { OFActionSetDlSrc.Builder ab = OFFactories.getFactory(version).actions().buildSetDlSrc(); ab.setDlAddr(macaddr); log.debug("action {}", ab.build()); return ab.build(); } } else { log.debug("Invalid action: '{}'", actionToDecode); return null; } return null; }
/** * Generates a DHCP request OFPacketIn. * @param hostMac The host MAC address of for the request. * @return An OFPacketIn that contains a DHCP request packet. */ public static OFPacketIn DhcpDiscoveryRequestOFPacketIn(IOFSwitch sw, MacAddress hostMac) { byte[] serializedPacket = DhcpDiscoveryRequestEthernet(hostMac).serialize(); OFFactory factory = sw.getOFFactory(); OFPacketIn.Builder packetInBuilder = factory.buildPacketIn(); if (factory.getVersion() == OFVersion.OF_10) { packetInBuilder .setInPort(OFPort.of(1)) .setData(serializedPacket) .setReason(OFPacketInReason.NO_MATCH); } else { packetInBuilder .setMatch(factory.buildMatch().setExact(MatchField.IN_PORT, OFPort.of(1)).build()) .setData(serializedPacket) .setReason(OFPacketInReason.NO_MATCH); } return packetInBuilder.build(); }
/** * Construct a new device iterator over the key fields * @param subIterator an iterator over the full data structure to scan * @param entityClasses the entity classes to search for * @param macAddress The MAC address * @param vlan the VLAN * @param ipv4Address the ipv4 address * @param switchDPID the switch DPID * @param switchPort the switch port */ public DeviceIterator(Iterator<Device> subIterator, IEntityClass[] entityClasses, MacAddress macAddress, VlanVid vlan, IPv4Address ipv4Address, DatapathId switchDPID, OFPort switchPort) { super(subIterator); this.entityClasses = entityClasses; this.subIterator = subIterator; this.macAddress = macAddress; this.vlan = vlan; this.ipv4Address = ipv4Address; this.switchDPID = switchDPID; this.switchPort = switchPort; }
/** * Returns an available address (DHCPBinding) for lease. * If this MAC is configured for a static/fixed IP, that DHCPBinding will be returned. * If this MAC has had a lease before and that same lease is available, that DHCPBinding will be returned. * If not, then an attempt to return an address that has not been active before will be made. * If there are no addresses that have not been used, then the lowest currently inactive address will be returned. * If all addresses are being used, then null will be returned. * @param {@code byte[]): MAC address of the device requesting the lease * @return {@code DHCPBinding}: Reference to the DHCPBinding object if successful, null if unsuccessful */ public DHCPBinding getAnyAvailableLease(MacAddress mac) { if (isPoolFull()) return null; DHCPBinding usedBinding = null; usedBinding = this.getDHCPbindingFromMAC(mac); if (usedBinding != null) return usedBinding; for (DHCPBinding binding : DHCP_POOL) { if (!binding.isActiveLease() && binding.getMACAddress().equals(UNASSIGNED_MAC)) { return binding; } else if (!binding.isActiveLease() && usedBinding == null && !binding.isStaticIPLease()) { usedBinding = binding; } } return usedBinding; }
/** * Verify that the given device exactly matches the given fields. E.g., * if ip is not null we expect the device to have exactly one IP address. * swId and port are the attachment point port. * Vlan and ip are optional all other fields must be specified. * @return */ private static void verifyDevice(IDevice d, long mac, Short vlan, Integer ip, long swId, int port) { assertNotNull(d); assertEquals(MacAddress.of(mac), d.getMACAddress()); if (vlan == null) assertArrayEquals(new VlanVid[] { VlanVid.ofVlan(-1) }, d.getVlanId()); else assertArrayEquals(new VlanVid[] { VlanVid.ofVlan(vlan) }, d.getVlanId()); if (ip == null) assertArrayEquals(new IPv4Address[] { IPv4Address.of(0) }, d.getIPv4Addresses()); else assertArrayEquals(new IPv4Address[] { IPv4Address.of(ip) }, d.getIPv4Addresses()); SwitchPort expectedAp = new SwitchPort(DatapathId.of(swId), OFPort.of(port)); assertArrayEquals(new SwitchPort[] { expectedAp }, d.getAttachmentPoints()); }
/** * Adds a host to the MAC/VLAN->SwitchPort mapping * @param sw The switch to add the mapping to * @param mac The MAC address of the host to add * @param vlan The VLAN that the host is on * @param portVal The switchport that the host is on */ protected void addToPortMap(IOFSwitch sw, MacAddress mac, VlanVid vlan, OFPort portVal) { Map<MacVlanPair, OFPort> swMap = macVlanToSwitchPortMap.get(sw); if (vlan == VlanVid.FULL_MASK || vlan == null) { vlan = VlanVid.ofVlan(0); } if (swMap == null) { // May be accessed by REST API so we need to make it thread safe swMap = Collections.synchronizedMap(new LRULinkedHashMap<MacVlanPair, OFPort>(MAX_MACS_PER_SWITCH)); macVlanToSwitchPortMap.put(sw, swMap); } swMap.put(new MacVlanPair(mac, vlan), portVal); }
/** * Create a match object for the verification packets * * @param sw siwtch object * @param isBroadcast if broadcast then set a generic match; else specific to switch Id * @return {@link Match} */ private Match matchVerification(final IOFSwitch sw, final boolean isBroadcast) { MacAddress dstMac = MacAddress.of(VERIFICATION_BCAST_PACKET_DST); if (!isBroadcast) { dstMac = dpidToMac(sw); } Match.Builder mb = sw.getOFFactory().buildMatch(); mb.setExact(MatchField.ETH_DST, dstMac); return mb.build(); }
@Test public void testDeviceSyncRepresentationBasics() { DeviceSyncRepresentation dsr = new DeviceSyncRepresentation(); assertNull(dsr.getKey()); assertNull(dsr.getEntities()); dsr.setKey("MyKey"); assertEquals("MyKey", dsr.getKey()); assertEquals("MyKey", dsr.toString()); List<SyncEntity> entities = new ArrayList<SyncEntity>(); Entity e1a = new Entity(MacAddress.of(1L), VlanVid.ofVlan(2), IPv4Address.of(3), IPv6Address.NONE, DatapathId.of(4L), OFPort.of(5), new Date(1000)); Entity e1b = new Entity(MacAddress.of(1L), VlanVid.ofVlan(2), IPv4Address.NONE, IPv6Address.NONE, DatapathId.of(4L), OFPort.of(5), new Date(1)); entities.add(new SyncEntity(e1a)); entities.add(new SyncEntity(e1b)); // e1b comes before e1 (lastSeen) but we add it after it to test // sorting dsr.setEntities(entities); assertEquals(2, dsr.getEntities().size()); // e1b has earlier time assertEquals(e1b, dsr.getEntities().get(0).asEntity()); assertEquals(e1a, dsr.getEntities().get(1).asEntity()); dsr.setKey(null); dsr.setEntities(null); assertNull(dsr.getKey()); assertNull(dsr.getEntities()); }
private IDevice getSingleDeviceFromDeviceManager(long mac) { Iterator<? extends IDevice> diter = deviceManager.queryDevices(MacAddress.of(mac), VlanVid.ZERO, IPv4Address.NONE, IPv6Address.NONE, DatapathId.NONE, OFPort.ZERO); assertTrue("Query didn't return a device", diter.hasNext()); IDevice d = diter.next(); assertFalse("Query returned more than one device", diter.hasNext()); return d; }
@Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("["); builder.append("MAC: "); builder.append(MacAddress.of(mac).toString()); builder.append("]"); return builder.toString(); }
/** * Returns a specific available IP address binding for lease. The MAC and IP will be queried * against the DHCP pool. (1) If the MAC is found in an available, fixed binding, and that binding * is not for the provided IP, the fixed binding associated with the MAC will be returned. (2) If the * IP is found in an available, fixed binding, and that binding also contains the MAC address provided, * then the binding will be returned -- this is true only if the IP and MAC result in the same available, * fixed binding. (3) If the IP is found in the pool and it is available and not fixed, then its * binding will be returned. (4) If the IP provided does not match any available entries or is invalid, * null will be returned. If this is the case, run getAnyAvailableLease(mac) to resolve. * @param {@code byte[]}: The IP address on which to try and obtain a lease * @param {@code byte[]}: The MAC address on which to try and obtain a lease. * @return {@code DHCPBinding}: Reference to the DHCPBinding object if successful, null if unsuccessful. */ public DHCPBinding getSpecificAvailableLease(IPv4Address ip, MacAddress mac) { if (ip == null || mac == null || isPoolFull()) return null; DHCPBinding binding = this.getDHCPbindingFromIPv4(ip); DHCPBinding binding2 = this.getDHCPbindingFromMAC(mac); // For all of the following, the binding is also determined to be inactive: // If configured, we must return a fixed binding for a MAC address even if it's requesting another IP if (binding2 != null && !binding2.isActiveLease() && binding2.isStaticIPLease() && binding != binding2) { if (log != null) log.info("Fixed DHCP entry for MAC trumps requested IP. Returning binding for MAC"); return binding2; // If configured, we must return a fixed binding for an IP if the binding is fixed to the provided MAC (ideal static request case) } else if (binding != null && !binding.isActiveLease() && binding.isStaticIPLease() && mac.equals(binding.getMACAddress())) { if (log != null) log.info("Found matching fixed DHCP entry for IP with MAC. Returning binding for IP with MAC"); return binding; // The IP and MAC are not a part of a fixed binding, so return the binding of the requested IP } else if (binding != null && !binding.isActiveLease() && !binding.isStaticIPLease()) { if (log != null) log.info("No fixed DHCP entry for IP or MAC found. Returning dynamic binding for IP."); return binding; // Otherwise, the binding is fixed for both MAC and IP and this MAC does not match either, so we can't return it as available } else { if (log != null) log.debug("Invalid IP address request or IP is actively leased...check for any available lease to resolve"); return null; } }
@Test public void testFlood() throws Exception { // build our expected flooded packetOut OFPacketOut po = factory.buildPacketOut() .setInPort(OFPort.of(1)) .setActions(Arrays.asList((OFAction)factory.actions().output(OFPort.FLOOD, 0xffFFffFF))) .setBufferId(OFBufferId.NO_BUFFER) .setData(this.testPacketSerialized) .build(); Capture<OFMessage> wc1 = new Capture<OFMessage>(CaptureType.ALL); // Mock up our expected behavior IOFSwitch mockSwitch = createMock(IOFSwitch.class); expect(mockSwitch.getId()).andReturn(DatapathId.of("00:11:22:33:44:55:66:77")).anyTimes(); expect(mockSwitch.getOFFactory()).andReturn(factory).anyTimes(); expect(mockSwitch.write(EasyMock.capture(wc1))).andReturn(true).once(); // expect po // Start recording the replay on the mocks replay(mockSwitch); // Get the listener and trigger the packet in IOFMessageListener listener = mockFloodlightProvider.getListeners().get(OFType.PACKET_IN).get(0); // Make sure it's the right listener listener.receive(mockSwitch, this.packetIn, parseAndAnnotate(this.packetIn)); // Verify the replay matched our expectations OFPort result = learningSwitch.getFromPortMap(mockSwitch, MacAddress.of("00:44:33:22:11:00"), VlanVid.ofVlan(42)); verify(mockSwitch); assertTrue(wc1.hasCaptured()); assertTrue(OFMessageUtils.equalsIgnoreXid(wc1.getValue(), po)); // Verify the MAC table inside the switch assertEquals(OFPort.of(1), result); }
@Override public long parseMAC(String mac){ MacAddress macAddr = MacAddress.of(mac); if (macAddr != null){ return macAddr.getLong(); } else{ return -1; } }
private void doTestEntityOrdering(boolean computeInsertionPoint) throws Exception { Entity e = new Entity(MacAddress.of(10L), VlanVid.ZERO, IPv4Address.NONE, IPv6Address.NONE, DatapathId.NONE, OFPort.ZERO, Entity.NO_DATE); IEntityClass ec = createNiceMock(IEntityClass.class); Device d = new Device(deviceManager, 1L, e, ec); int expectedLength = 1; Long[] macs = new Long[] { 5L, // new first element 15L, // new last element 7L, // insert in middle 12L, // insert in middle 6L, // insert at idx 1 14L, // insert at idx length-2 1L, 20L }; for (Long mac: macs) { e = new Entity(MacAddress.of(mac), VlanVid.ZERO, IPv4Address.NONE, IPv6Address.NONE, DatapathId.NONE, OFPort.ZERO, Entity.NO_DATE); int insertionPoint; if (computeInsertionPoint) { insertionPoint = -(Arrays.binarySearch(d.entities, e)+1); } else { insertionPoint = -1; } d = deviceManager.allocateDevice(d, e, insertionPoint); expectedLength++; assertEquals(expectedLength, d.entities.length); for (int i = 0; i < d.entities.length-1; i++) assertEquals(-1, d.entities[i].compareTo(d.entities[i+1])); } }
public static OFPortDesc createOFPortDesc(IOFSwitch sw, String name, int number) { OFPortDesc portDesc = sw.getOFFactory().buildPortDesc() .setHwAddr(MacAddress.NONE) .setPortNo(OFPort.of(number)) .setName(name) .build(); return portDesc; }
/** * Removes a host from this network record * @param host: MAC address as MACAddress * @return boolean: true: removed, false: host not found */ public boolean removeHost(MacAddress host){ for (Entry<String, MacAddress> entry : this.portToMac.entrySet()) { if (entry.getValue().equals(host)){ this.portToMac.remove(entry.getKey()); return true; } } return false; }
@Override public IDevice findDevice(@Nonnull MacAddress macAddress, VlanVid vlan, @Nonnull IPv4Address ipv4Address, @Nonnull IPv6Address ipv6Address, @Nonnull DatapathId switchDPID, @Nonnull OFPort switchPort) throws IllegalArgumentException { if (macAddress == null) { throw new IllegalArgumentException("MAC address cannot be null. Try MacAddress.NONE if intention is 'no MAC'"); } if (ipv4Address == null) { throw new IllegalArgumentException("IPv4 address cannot be null. Try IPv4Address.NONE if intention is 'no IPv4'"); } if (ipv6Address == null) { throw new IllegalArgumentException("IPv6 address cannot be null. Try IPv6Address.NONE if intention is 'no IPv6'"); } if (vlan == null) { throw new IllegalArgumentException("VLAN cannot be null. Try VlanVid.ZERO if intention is 'no VLAN / untagged'"); } if (switchDPID == null) { throw new IllegalArgumentException("Switch DPID cannot be null. Try DatapathId.NONE if intention is 'no DPID'"); } if (switchPort == null) { throw new IllegalArgumentException("Switch port cannot be null. Try OFPort.ZERO if intention is 'no port'"); } Entity e = new Entity(macAddress, vlan, ipv4Address, ipv6Address, switchDPID, switchPort, Entity.NO_DATE); /* * allKeyFieldsPresent() will check if the entity key fields (e.g. MAC and VLAN) * have non-"zero" values i.e. are not set to e.g. MacAddress.NONE and VlanVid.ZERO */ if (!allKeyFieldsPresent(e, entityClassifier.getKeyFields())) { throw new IllegalArgumentException("Not all key fields specified." + " Required fields: " + entityClassifier.getKeyFields()); } return findDeviceByEntity(e); }
@Test public void testSyncEntity() { Date d1 = new Date(); Date d2 = new Date(0); Entity e1 = new Entity(MacAddress.of(1L), VlanVid.ofVlan(2), IPv4Address.of(3), DatapathId.of(4L), OFPort.of(5), d1); e1.setActiveSince(d2); SyncEntity se1 = new SyncEntity(e1); assertEntityEquals(e1, se1); assertEquals(1L, se1.macAddress); assertEquals(2, se1.vlan); assertEquals(3, se1.ipv4Address); assertEquals(4L, se1.switchDPID); assertEquals(5, se1.switchPort); assertEquals(d1, se1.lastSeenTimestamp); assertEquals(d2, se1.activeSince); assertNotSame(d1, se1.lastSeenTimestamp); assertNotSame(d2, se1.activeSince); Entity e2 = new Entity(MacAddress.of(42L), null, null, null, null, null); SyncEntity se2 = new SyncEntity(e2); assertEntityEquals(e2, se2); SyncEntity se3 = new SyncEntity(); SyncEntity se4 = new SyncEntity(); se3.lastSeenTimestamp = new Date(1000); se4.lastSeenTimestamp = new Date(2000); assertTrue("", se3.compareTo(se4) < 0); assertTrue("", se4.compareTo(se3) > 0); se4.lastSeenTimestamp = new Date(1000); assertTrue("", se3.compareTo(se4) == 0); assertTrue("", se4.compareTo(se3) == 0); se4.lastSeenTimestamp = new Date(500); assertTrue("", se3.compareTo(se4) > 0); assertTrue("", se4.compareTo(se3) < 0); }
@Test public void testDeviceSyncRepresentationBasics() { DeviceSyncRepresentation dsr = new DeviceSyncRepresentation(); assertNull(dsr.getKey()); assertNull(dsr.getEntities()); dsr.setKey("MyKey"); assertEquals("MyKey", dsr.getKey()); assertEquals("MyKey", dsr.toString()); List<SyncEntity> entities = new ArrayList<SyncEntity>(); Entity e1a = new Entity(MacAddress.of(1L), VlanVid.ofVlan(2), IPv4Address.of(3), DatapathId.of(4L), OFPort.of(5), new Date(1000)); Entity e1b = new Entity(MacAddress.of(1L), VlanVid.ofVlan(2), null, DatapathId.of(4L), OFPort.of(5), new Date(0)); entities.add(new SyncEntity(e1a)); entities.add(new SyncEntity(e1b)); // e1b comes before e1 (lastSeen) but we add it after it to test // sorting dsr.setEntities(entities); assertEquals(2, dsr.getEntities().size()); // e1b has earlier time assertEquals(e1b, dsr.getEntities().get(0).asEntity()); assertEquals(e1a, dsr.getEntities().get(1).asEntity()); dsr.setKey(null); dsr.setEntities(null); assertNull(dsr.getKey()); assertNull(dsr.getEntities()); }
/** * Get a (partial) entity for the destination from the packet. * @param eth * @return */ protected Entity getDestEntityFromPacket(Ethernet eth) { MacAddress dlAddr = eth.getDestinationMACAddress(); VlanVid vlan = VlanVid.ofVlan(eth.getVlanID()); IPv4Address ipv4Dst = IPv4Address.NONE; IPv6Address ipv6Dst = IPv6Address.NONE; // Ignore broadcast/multicast destination if (dlAddr.isBroadcast() || dlAddr.isMulticast()) return null; // Ignore zero dest mac if (dlAddr.equals(MacAddress.of(0))) return null; if (eth.getPayload() instanceof IPv4) { IPv4 ipv4 = (IPv4) eth.getPayload(); ipv4Dst = ipv4.getDestinationAddress(); } else if (eth.getPayload() instanceof IPv6) { IPv6 ipv6 = (IPv6) eth.getPayload(); ipv6Dst = ipv6.getDestinationAddress(); } return new Entity(dlAddr, vlan, ipv4Dst, ipv6Dst, DatapathId.NONE, OFPort.ZERO, Entity.NO_DATE); }
public int querySourceId(MacAddress mac, IPv4Address ip, IpProtocol protocol, TransportPort port) { if (!oPolicy.doRewrite(ObfuscationPolicy.Field.MAC_SRC)) mac = MacAddress.of(1); if (!oPolicy.doRewrite(ObfuscationPolicy.Field.IP_SRC)) ip = IPv4Address.of(1); if (!(oPolicy.doRewrite(ObfuscationPolicy.Field.TP_SRC) && oPolicy.doRewrite(port.getPort()))) port = TransportPort.of(0); return queryHostId(0, mac, ip, protocol, port); }
public DeviceEvent(MacAddress macAddress, List<IPv4Address> ipv4Addresses, List<IPv6Address> ipv6Addresses, List<SwitchPort> oldAttachmentPoints, List<SwitchPort> currentAttachmentPoints, List<VlanVid> vlanIds, String reason) { super(); this.macAddress = macAddress; this.ipv4Addresses = ipv4Addresses; this.ipv6Addresses = ipv6Addresses; this.oldAttachmentPoints = oldAttachmentPoints; this.currentAttachmentPoints = currentAttachmentPoints; this.vlanIds = vlanIds; this.reason = reason; }
/** * Create a new entity * * @param macAddress * @param vlan * @param ipv4Address * @param ipv6Address * @param switchDPID * @param switchPort * @param lastSeenTimestamp */ public Entity(@Nonnull MacAddress macAddress, VlanVid vlan, @Nonnull IPv4Address ipv4Address, @Nonnull IPv6Address ipv6Address, @Nonnull DatapathId switchDPID, @Nonnull OFPort switchPort, @Nonnull Date lastSeenTimestamp) { if (macAddress == null) { throw new IllegalArgumentException("MAC address cannot be null. Try MacAddress.NONE if intention is 'no MAC'"); } if (ipv4Address == null) { throw new IllegalArgumentException("IPv4 address cannot be null. Try IPv4Address.NONE if intention is 'no IPv4'"); } if (ipv6Address == null) { throw new IllegalArgumentException("IPv6 address cannot be null. Try IPv6Address.NONE if intention is 'no IPv6'"); } /* VLAN can be null for 'don't care' in query searches */ if (switchDPID == null) { throw new IllegalArgumentException("Switch DPID cannot be null. Try DatapathId.NONE if intention is 'no DPID'"); } if (switchPort == null) { throw new IllegalArgumentException("Switch port cannot be null. Try OFPort.ZERO if intention is 'no port'"); } if (lastSeenTimestamp == null) { throw new IllegalArgumentException("Last seen time stamp cannot be null. Try Entity.NO_DATE if intention is 'no time'"); } this.macAddress = macAddress; this.ipv4Address = ipv4Address; this.ipv6Address = ipv6Address; this.vlan = vlan; this.switchDPID = switchDPID; this.switchPort = switchPort; this.lastSeenTimestamp = lastSeenTimestamp; this.activeSince = lastSeenTimestamp; }
/** * Get sender IP address from packet if the packet is an ARP * packet and if the source MAC address matches the ARP packets * sender MAC address. * @param eth * @param dlAddr * @return */ private IPv4Address getSrcNwAddr(Ethernet eth, MacAddress dlAddr) { if (eth.getPayload() instanceof ARP) { ARP arp = (ARP) eth.getPayload(); if ((arp.getProtocolType() == ARP.PROTO_TYPE_IP) && (MacAddress.of(arp.getSenderHardwareAddress()).equals(dlAddr))) { return IPv4Address.of(arp.getSenderProtocolAddress()); } } return IPv4Address.NONE; }
@Override public void deviceAdded(IDevice device) { if (device.getIPv4Addresses() == null) return; for (IPv4Address i : device.getIPv4Addresses()) { if (gatewayToGuid.containsKey(i)) { MacAddress mac = device.getMACAddress(); if (log.isDebugEnabled()) log.debug("Adding MAC {} with IP {} a a gateway", mac.toString(), i.toString()); macToGateway.put(mac, i); } } }