method2testcases
stringlengths
118
6.63k
### Question: FermaTransitVlanRepository extends FermaGenericRepository<TransitVlan, TransitVlanData, TransitVlanFrame> implements TransitVlanRepository { @Override public Optional<TransitVlan> findByVlan(int vlan) { List<? extends TransitVlanFrame> transitVlanFrames = framedGraph().traverse(g -> g.V() .hasLabel(TransitVlanFrame.FRAME_LABEL) .has(TransitVlanFrame.VLAN_PROPERTY, vlan)) .toListExplicit(TransitVlanFrame.class); return transitVlanFrames.isEmpty() ? Optional.empty() : Optional.of(transitVlanFrames.get(0)) .map(TransitVlan::new); } FermaTransitVlanRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<TransitVlan> findAll(); @Override Collection<TransitVlan> findByPathId(PathId pathId, PathId oppositePathId); @Override Optional<TransitVlan> findByPathId(PathId pathId); @Override boolean exists(int vlan); @Override Optional<TransitVlan> findByVlan(int vlan); @Override Optional<Integer> findFirstUnassignedVlan(int lowestTransitVlan, int highestTransitVlan); }### Answer: @Test public void shouldFindTransitVlan() { TransitVlan vlan = createTransitVlan(); vlan.setVlan(VLAN); Optional<TransitVlan> foundVlan = transitVlanRepository.findByVlan(VLAN); assertTrue(foundVlan.isPresent()); assertEquals(vlan.getVlan(), foundVlan.get().getVlan()); assertEquals(vlan.getFlowId(), foundVlan.get().getFlowId()); assertEquals(vlan.getPathId(), foundVlan.get().getPathId()); } @Test public void shouldSelectNextInOrderResourceWhenFindUnassignedTransitVlan() { int first = findUnassignedTransitVlanAndCreate("flow_1"); assertEquals(5, first); int second = findUnassignedTransitVlanAndCreate("flow_2"); assertEquals(6, second); int third = findUnassignedTransitVlanAndCreate("flow_3"); assertEquals(7, third); transactionManager.doInTransaction(() -> transitVlanRepository.findByVlan(second).ifPresent(transitVlanRepository::remove)); int fourth = findUnassignedTransitVlanAndCreate("flow_4"); assertEquals(6, fourth); int fifth = findUnassignedTransitVlanAndCreate("flow_5"); assertEquals(8, fifth); }
### Question: FermaVxlanRepository extends FermaGenericRepository<Vxlan, VxlanData, VxlanFrame> implements VxlanRepository { @Override public Collection<Vxlan> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(VxlanFrame.FRAME_LABEL)) .toListExplicit(VxlanFrame.class).stream() .map(Vxlan::new) .collect(Collectors.toList()); } FermaVxlanRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<Vxlan> findAll(); @Override Collection<Vxlan> findByPathId(PathId pathId, PathId oppositePathId); @Override boolean exists(int vxlan); @Override Optional<Integer> findFirstUnassignedVxlan(int lowestVxlan, int highestVxlan); }### Answer: @Test public void shouldCreateVxlan() { Vxlan vxlan = createVxlan(); Collection<Vxlan> allVxlans = vxlanRepository.findAll(); Vxlan foundVxlan = allVxlans.iterator().next(); assertEquals(vxlan.getVni(), foundVxlan.getVni()); assertEquals(TEST_FLOW_ID, foundVxlan.getFlowId()); } @Test public void shouldDeleteVxlan() { Vxlan vxlan = createVxlan(); transactionManager.doInTransaction(() -> vxlanRepository.remove(vxlan)); assertEquals(0, vxlanRepository.findAll().size()); } @Test public void shouldDeleteFoundVxlan() { createVxlan(); transactionManager.doInTransaction(() -> { Collection<Vxlan> allVxlans = vxlanRepository.findAll(); Vxlan foundVxlan = allVxlans.iterator().next(); vxlanRepository.remove(foundVxlan); }); assertEquals(0, vxlanRepository.findAll().size()); } @Test public void shouldSelectNextInOrderResourceWhenFindUnassignedVxlan() { int first = findUnassignedVxlanAndCreate("flow_1"); assertEquals(5, first); int second = findUnassignedVxlanAndCreate("flow_2"); assertEquals(6, second); int third = findUnassignedVxlanAndCreate("flow_3"); assertEquals(7, third); transactionManager.doInTransaction(() -> { vxlanRepository.findAll().stream() .filter(vxlan -> vxlan.getVni() == second) .forEach(vxlanRepository::remove); }); int fourth = findUnassignedVxlanAndCreate("flow_4"); assertEquals(6, fourth); int fifth = findUnassignedVxlanAndCreate("flow_5"); assertEquals(8, fifth); }
### Question: FermaFlowMeterRepository extends FermaGenericRepository<FlowMeter, FlowMeterData, FlowMeterFrame> implements FlowMeterRepository { @Override public Collection<FlowMeter> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(FlowMeterFrame.FRAME_LABEL)) .toListExplicit(FlowMeterFrame.class).stream() .map(FlowMeter::new) .collect(Collectors.toList()); } FermaFlowMeterRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowMeter> findAll(); @Override Optional<FlowMeter> findByPathId(PathId pathId); @Override boolean exists(SwitchId switchId, MeterId meterId); @Override Optional<MeterId> findFirstUnassignedMeter(SwitchId switchId, MeterId lowestMeterId, MeterId highestMeterId); }### Answer: @Test public void shouldCreateFlowMeter() { createFlowMeter(); Collection<FlowMeter> allMeters = flowMeterRepository.findAll(); FlowMeter foundMeter = allMeters.iterator().next(); assertEquals(theSwitch.getSwitchId(), foundMeter.getSwitchId()); assertEquals(TEST_FLOW_ID, foundMeter.getFlowId()); } @Test public void shouldDeleteFlowMeter() { FlowMeter meter = createFlowMeter(); transactionManager.doInTransaction(() -> flowMeterRepository.remove(meter)); assertEquals(0, flowMeterRepository.findAll().size()); } @Test public void shouldDeleteFoundFlowMeter() { createFlowMeter(); transactionManager.doInTransaction(() -> { Collection<FlowMeter> allMeters = flowMeterRepository.findAll(); FlowMeter foundMeter = allMeters.iterator().next(); flowMeterRepository.remove(foundMeter); }); assertEquals(0, flowMeterRepository.findAll().size()); } @Test public void shouldSelectNextInOrderResourceWhenFindUnassignedMeter() { long first = findUnassignedMeterAndCreate("flow_1"); assertEquals(5, first); long second = findUnassignedMeterAndCreate("flow_2"); assertEquals(6, second); long third = findUnassignedMeterAndCreate("flow_3"); assertEquals(7, third); transactionManager.doInTransaction(() -> { flowMeterRepository.findAll().stream() .filter(flowMeter -> flowMeter.getMeterId().getValue() == second) .forEach(flowMeterRepository::remove); }); long fourth = findUnassignedMeterAndCreate("flow_4"); assertEquals(6, fourth); long fifth = findUnassignedMeterAndCreate("flow_5"); assertEquals(8, fifth); }
### Question: FermaFlowMeterRepository extends FermaGenericRepository<FlowMeter, FlowMeterData, FlowMeterFrame> implements FlowMeterRepository { @Override public Optional<FlowMeter> findByPathId(PathId pathId) { List<? extends FlowMeterFrame> flowMeterFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowMeterFrame.FRAME_LABEL) .has(FlowMeterFrame.PATH_ID_PROPERTY, PathIdConverter.INSTANCE.toGraphProperty(pathId))) .toListExplicit(FlowMeterFrame.class); return flowMeterFrames.isEmpty() ? Optional.empty() : Optional.of(flowMeterFrames.get(0)) .map(FlowMeter::new); } FermaFlowMeterRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowMeter> findAll(); @Override Optional<FlowMeter> findByPathId(PathId pathId); @Override boolean exists(SwitchId switchId, MeterId meterId); @Override Optional<MeterId> findFirstUnassignedMeter(SwitchId switchId, MeterId lowestMeterId, MeterId highestMeterId); }### Answer: @Ignore("InMemoryGraph doesn't enforce constraint") @Test(expected = PersistenceException.class) public void shouldNotGetMoreThanOneMetersForPath() { createFlowMeter(1, new PathId(TEST_PATH_ID)); createFlowMeter(2, new PathId(TEST_PATH_ID)); flowMeterRepository.findByPathId(new PathId(TEST_PATH_ID)); } @Test public void shouldGetZeroMetersForPath() { Optional<FlowMeter> meters = flowMeterRepository.findByPathId(new PathId(TEST_PATH_ID)); assertFalse(meters.isPresent()); }
### Question: FermaSwitchConnectedDevicesRepository extends FermaGenericRepository<SwitchConnectedDevice, SwitchConnectedDeviceData, SwitchConnectedDeviceFrame> implements SwitchConnectedDeviceRepository { @Override public Collection<SwitchConnectedDevice> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(SwitchConnectedDeviceFrame.FRAME_LABEL)) .toListExplicit(SwitchConnectedDeviceFrame.class).stream() .map(SwitchConnectedDevice::new) .collect(Collectors.toList()); } FermaSwitchConnectedDevicesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<SwitchConnectedDevice> findAll(); @Override Collection<SwitchConnectedDevice> findBySwitchId(SwitchId switchId); @Override Collection<SwitchConnectedDevice> findByFlowId(String flowId); @Override Optional<SwitchConnectedDevice> findLldpByUniqueFieldCombination( SwitchId switchId, int portNumber, int vlan, String macAddress, String chassisId, String portId); @Override Optional<SwitchConnectedDevice> findArpByUniqueFieldCombination( SwitchId switchId, int portNumber, int vlan, String macAddress, String ipAddress); }### Answer: @Test public void createConnectedDeviceTest() { connectedDeviceRepository.add(lldpConnectedDeviceA); Collection<SwitchConnectedDevice> devices = connectedDeviceRepository.findAll(); assertEquals(lldpConnectedDeviceA, devices.iterator().next()); assertNotNull(devices.iterator().next().getSwitchObj()); } @Test public void deleteConnectedDeviceTest() { transactionManager.doInTransaction(() -> { connectedDeviceRepository.add(lldpConnectedDeviceA); connectedDeviceRepository.add(lldpConnectedDeviceB); assertEquals(2, connectedDeviceRepository.findAll().size()); connectedDeviceRepository.remove(lldpConnectedDeviceA); assertEquals(1, connectedDeviceRepository.findAll().size()); assertEquals(lldpConnectedDeviceB, connectedDeviceRepository.findAll().iterator().next()); connectedDeviceRepository.remove(lldpConnectedDeviceB); assertEquals(0, connectedDeviceRepository.findAll().size()); }); }
### Question: FermaSwitchConnectedDevicesRepository extends FermaGenericRepository<SwitchConnectedDevice, SwitchConnectedDeviceData, SwitchConnectedDeviceFrame> implements SwitchConnectedDeviceRepository { @Override public Collection<SwitchConnectedDevice> findBySwitchId(SwitchId switchId) { return framedGraph().traverse(g -> g.V() .hasLabel(SwitchConnectedDeviceFrame.FRAME_LABEL) .has(SwitchConnectedDeviceFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .toListExplicit(SwitchConnectedDeviceFrame.class).stream() .map(SwitchConnectedDevice::new) .collect(Collectors.toList()); } FermaSwitchConnectedDevicesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<SwitchConnectedDevice> findAll(); @Override Collection<SwitchConnectedDevice> findBySwitchId(SwitchId switchId); @Override Collection<SwitchConnectedDevice> findByFlowId(String flowId); @Override Optional<SwitchConnectedDevice> findLldpByUniqueFieldCombination( SwitchId switchId, int portNumber, int vlan, String macAddress, String chassisId, String portId); @Override Optional<SwitchConnectedDevice> findArpByUniqueFieldCombination( SwitchId switchId, int portNumber, int vlan, String macAddress, String ipAddress); }### Answer: @Test public void findBySwitchIdTest() { connectedDeviceRepository.add(lldpConnectedDeviceA); connectedDeviceRepository.add(lldpConnectedDeviceB); connectedDeviceRepository.add(arpConnectedDeviceC); connectedDeviceRepository.add(arpConnectedDeviceD); Collection<SwitchConnectedDevice> firstSwitchDevices = connectedDeviceRepository .findBySwitchId(FIRST_SWITCH_ID); assertEquals(1, firstSwitchDevices.size()); assertEquals(lldpConnectedDeviceA, firstSwitchDevices.iterator().next()); Collection<SwitchConnectedDevice> secondFlowDevices = connectedDeviceRepository .findBySwitchId(SECOND_SWITCH_ID); assertEquals(3, secondFlowDevices.size()); assertEquals(newHashSet(lldpConnectedDeviceB, arpConnectedDeviceC, arpConnectedDeviceD), newHashSet(secondFlowDevices)); }
### Question: FermaSwitchConnectedDevicesRepository extends FermaGenericRepository<SwitchConnectedDevice, SwitchConnectedDeviceData, SwitchConnectedDeviceFrame> implements SwitchConnectedDeviceRepository { @Override public Collection<SwitchConnectedDevice> findByFlowId(String flowId) { return framedGraph().traverse(g -> g.V() .hasLabel(SwitchConnectedDeviceFrame.FRAME_LABEL) .has(SwitchConnectedDeviceFrame.FLOW_ID_PROPERTY, flowId)) .toListExplicit(SwitchConnectedDeviceFrame.class).stream() .map(SwitchConnectedDevice::new) .collect(Collectors.toList()); } FermaSwitchConnectedDevicesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<SwitchConnectedDevice> findAll(); @Override Collection<SwitchConnectedDevice> findBySwitchId(SwitchId switchId); @Override Collection<SwitchConnectedDevice> findByFlowId(String flowId); @Override Optional<SwitchConnectedDevice> findLldpByUniqueFieldCombination( SwitchId switchId, int portNumber, int vlan, String macAddress, String chassisId, String portId); @Override Optional<SwitchConnectedDevice> findArpByUniqueFieldCombination( SwitchId switchId, int portNumber, int vlan, String macAddress, String ipAddress); }### Answer: @Test public void findByFlowIdTest() { connectedDeviceRepository.add(lldpConnectedDeviceA); connectedDeviceRepository.add(lldpConnectedDeviceB); connectedDeviceRepository.add(arpConnectedDeviceC); connectedDeviceRepository.add(arpConnectedDeviceD); Collection<SwitchConnectedDevice> firstDevice = connectedDeviceRepository.findByFlowId(FIRST_FLOW_ID); assertEquals(1, firstDevice.size()); assertEquals(lldpConnectedDeviceA, firstDevice.iterator().next()); Collection<SwitchConnectedDevice> secondDevices = connectedDeviceRepository.findByFlowId(SECOND_FLOW_ID); assertEquals(2, secondDevices.size()); assertEquals(newHashSet(lldpConnectedDeviceB, arpConnectedDeviceD), newHashSet(secondDevices)); }
### Question: FermaSwitchConnectedDevicesRepository extends FermaGenericRepository<SwitchConnectedDevice, SwitchConnectedDeviceData, SwitchConnectedDeviceFrame> implements SwitchConnectedDeviceRepository { @Override public Optional<SwitchConnectedDevice> findLldpByUniqueFieldCombination( SwitchId switchId, int portNumber, int vlan, String macAddress, String chassisId, String portId) { Collection<? extends SwitchConnectedDeviceFrame> devices = framedGraph().traverse(g -> g.V() .hasLabel(SwitchConnectedDeviceFrame.FRAME_LABEL) .has(SwitchConnectedDeviceFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(SwitchConnectedDeviceFrame.PORT_NUMBER_PROPERTY, portNumber) .has(SwitchConnectedDeviceFrame.VLAN_PROPERTY, vlan) .has(SwitchConnectedDeviceFrame.MAC_ADDRESS_PROPERTY, macAddress) .has(SwitchConnectedDeviceFrame.TYPE_PROPERTY, ConnectedDeviceTypeConverter.INSTANCE.toGraphProperty(ConnectedDeviceType.LLDP)) .has(SwitchConnectedDeviceFrame.CHASSIS_ID_PROPERTY, chassisId) .has(SwitchConnectedDeviceFrame.PORT_ID_PROPERTY, portId)) .toListExplicit(SwitchConnectedDeviceFrame.class); if (devices.size() > 1) { throw new PersistenceException(format("Found more that 1 LLDP Connected Device by switch ID '%s', " + "port number '%d', vlan '%d', mac address '%s', chassis ID '%s' and port ID '%s'", switchId, portNumber, vlan, macAddress, chassisId, portId)); } return devices.isEmpty() ? Optional.empty() : Optional.of(devices.iterator().next()).map(SwitchConnectedDevice::new); } FermaSwitchConnectedDevicesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<SwitchConnectedDevice> findAll(); @Override Collection<SwitchConnectedDevice> findBySwitchId(SwitchId switchId); @Override Collection<SwitchConnectedDevice> findByFlowId(String flowId); @Override Optional<SwitchConnectedDevice> findLldpByUniqueFieldCombination( SwitchId switchId, int portNumber, int vlan, String macAddress, String chassisId, String portId); @Override Optional<SwitchConnectedDevice> findArpByUniqueFieldCombination( SwitchId switchId, int portNumber, int vlan, String macAddress, String ipAddress); }### Answer: @Test public void findByLldpUniqueFields() { connectedDeviceRepository.add(lldpConnectedDeviceA); connectedDeviceRepository.add(lldpConnectedDeviceB); connectedDeviceRepository.add(arpConnectedDeviceC); runFindByLldpUniqueFields(lldpConnectedDeviceA); runFindByLldpUniqueFields(lldpConnectedDeviceB); runFindByLldpUniqueFields(arpConnectedDeviceC); assertFalse(connectedDeviceRepository.findLldpByUniqueFieldCombination( firstSwitch.getSwitchId(), 999, 999, "fake", CHASSIS_ID, PORT_ID).isPresent()); } @Test public void findByArpUniqueFields() { connectedDeviceRepository.add(lldpConnectedDeviceA); connectedDeviceRepository.add(arpConnectedDeviceC); connectedDeviceRepository.add(arpConnectedDeviceD); runFindByArpUniqueFields(lldpConnectedDeviceA); runFindByArpUniqueFields(arpConnectedDeviceC); runFindByArpUniqueFields(arpConnectedDeviceD); assertFalse(connectedDeviceRepository.findLldpByUniqueFieldCombination( firstSwitch.getSwitchId(), 999, 999, "fake", CHASSIS_ID, PORT_ID).isPresent()); }
### Question: FermaPortHistoryRepository extends FermaGenericRepository<PortHistory, PortHistoryData, PortHistoryFrame> implements PortHistoryRepository { @Override public List<PortHistory> findBySwitchIdAndPortNumber(SwitchId switchId, int portNumber, Instant timeFrom, Instant timeTo) { return framedGraph().traverse(g -> { GraphTraversal<Vertex, Vertex> traversal = g.V() .hasLabel(PortHistoryFrame.FRAME_LABEL) .has(PortHistoryFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(PortHistoryFrame.PORT_NUMBER_PROPERTY, portNumber); if (timeFrom != null) { traversal = traversal.has(PortHistoryFrame.TIME_PROPERTY, P.gte(InstantLongConverter.INSTANCE.toGraphProperty(timeFrom))); } if (timeTo != null) { traversal = traversal.has(PortHistoryFrame.TIME_PROPERTY, P.lte(InstantLongConverter.INSTANCE.toGraphProperty(timeTo))); } return traversal .order().by(PortHistoryFrame.TIME_PROPERTY, Order.incr); }).toListExplicit(PortHistoryFrame.class).stream() .map(PortHistory::new) .collect(Collectors.toList()); } FermaPortHistoryRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override List<PortHistory> findBySwitchIdAndPortNumber(SwitchId switchId, int portNumber, Instant timeFrom, Instant timeTo); }### Answer: @Test public void shouldFindHistoryRecordsBySwitchByIdAndPortNumber() { Instant start = new Date().toInstant(); Instant end = new Date().toInstant().plus(1, ChronoUnit.DAYS); PortHistory portUp = createPortHistory(SWITCH_ID, PORT_NUMBER, "PORT_UP", start.plus(1, ChronoUnit.HOURS)); PortHistory portDown = createPortHistory(SWITCH_ID, PORT_NUMBER, "PORT_DOWN", end); createPortHistory(new SwitchId(2L), PORT_NUMBER, "TEST1", end); createPortHistory(SWITCH_ID, 3, "TEST2", end); createPortHistory(SWITCH_ID, PORT_NUMBER, "TEST3", start.minus(1, ChronoUnit.SECONDS)); createPortHistory(SWITCH_ID, PORT_NUMBER, "TEST4", end.plus(1, ChronoUnit.HOURS)); Collection<PortHistory> portHistory = repository.findBySwitchIdAndPortNumber(SWITCH_ID, PORT_NUMBER, start, end); assertEquals(2, portHistory.size()); assertTrue(portHistory.contains(portUp)); assertTrue(portHistory.contains(portDown)); }
### Question: FermaFeatureTogglesRepository extends FermaGenericRepository<FeatureToggles, FeatureTogglesData, FeatureTogglesFrame> implements FeatureTogglesRepository { @Override public Optional<FeatureToggles> find() { List<? extends FeatureTogglesFrame> featureTogglesFrames = framedGraph().traverse(g -> g.V() .hasLabel(FeatureTogglesFrame.FRAME_LABEL)) .toListExplicit(FeatureTogglesFrame.class); return featureTogglesFrames.isEmpty() ? Optional.empty() : Optional.of(featureTogglesFrames.get(0)) .map(FeatureToggles::new); } FermaFeatureTogglesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Optional<FeatureToggles> find(); @Override FeatureToggles getOrDefault(); }### Answer: @Test public void shouldCreateAndUpdateFeatureToggles() { FeatureToggles featureTogglesA = FeatureToggles.builder() .flowsRerouteOnIslDiscoveryEnabled(false) .createFlowEnabled(false) .updateFlowEnabled(false) .deleteFlowEnabled(false) .useBfdForIslIntegrityCheck(false) .floodlightRoutePeriodicSync(false) .flowsRerouteUsingDefaultEncapType(false) .build(); featureTogglesRepository.add(featureTogglesA); FeatureToggles foundFeatureToggles = featureTogglesRepository.find().get(); assertEquals(featureTogglesA, foundFeatureToggles); foundFeatureToggles.setUpdateFlowEnabled(true); FeatureToggles updatedFeatureToggles = featureTogglesRepository.find().get(); assertTrue(updatedFeatureToggles.getUpdateFlowEnabled()); }
### Question: FermaBfdSessionRepository extends FermaGenericRepository<BfdSession, BfdSessionData, BfdSessionFrame> implements BfdSessionRepository { @Override public Collection<BfdSession> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(BfdSessionFrame.FRAME_LABEL)) .toListExplicit(BfdSessionFrame.class).stream() .map(BfdSession::new) .collect(Collectors.toList()); } FermaBfdSessionRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<BfdSession> findAll(); @Override boolean exists(SwitchId switchId, Integer port); @Override Optional<BfdSession> findBySwitchIdAndPort(SwitchId switchId, Integer port); }### Answer: @Test public void shouldCreateBfdPort() { createBfdSession(); assertEquals(1, repository.findAll().size()); } @Test public void shouldDeleteBfdPort() { BfdSession bfdSession = createBfdSession(); assertEquals(1, repository.findAll().size()); transactionManager.doInTransaction(() -> repository.remove(bfdSession)); assertEquals(0, repository.findAll().size()); } @Ignore("Need to fix: in-memory persistence doesn't impose constraints") @Test(expected = ConstraintViolationException.class) public void createUseCaseTest() { assertEquals(TEST_DISCRIMINATOR, getDiscriminator(TEST_SWITCH_ID, TEST_PORT, TEST_DISCRIMINATOR)); assertEquals(TEST_DISCRIMINATOR, getDiscriminator(TEST_SWITCH_ID, TEST_PORT, TEST_DISCRIMINATOR)); assertEquals(1, repository.findAll().size()); assertEquals(TEST_DISCRIMINATOR, getDiscriminator(TEST_SWITCH_ID, TEST_PORT + 1, TEST_DISCRIMINATOR)); } @Test public void deleteUseCaseTest() { getDiscriminator(TEST_SWITCH_ID, TEST_PORT, TEST_DISCRIMINATOR); assertEquals(1, repository.findAll().size()); freeDiscriminator(TEST_SWITCH_ID, TEST_PORT); assertEquals(0, repository.findAll().size()); }
### Question: FermaBfdSessionRepository extends FermaGenericRepository<BfdSession, BfdSessionData, BfdSessionFrame> implements BfdSessionRepository { @Override public Optional<BfdSession> findBySwitchIdAndPort(SwitchId switchId, Integer port) { List<? extends BfdSessionFrame> bfdSessionFrames = framedGraph().traverse(g -> g.V() .hasLabel(BfdSessionFrame.FRAME_LABEL) .has(BfdSessionFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(BfdSessionFrame.PORT_PROPERTY, port)) .toListExplicit(BfdSessionFrame.class); return bfdSessionFrames.isEmpty() ? Optional.empty() : Optional.of(bfdSessionFrames.get(0)) .map(BfdSession::new); } FermaBfdSessionRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<BfdSession> findAll(); @Override boolean exists(SwitchId switchId, Integer port); @Override Optional<BfdSession> findBySwitchIdAndPort(SwitchId switchId, Integer port); }### Answer: @Test public void shouldFindBySwitchIdAndPort() { BfdSession bfdSession = createBfdSession(); BfdSession foundPort = repository.findBySwitchIdAndPort(TEST_SWITCH_ID, TEST_PORT).get(); assertEquals(bfdSession.getDiscriminator(), foundPort.getDiscriminator()); }
### Question: FermaSwitchPropertiesRepository extends FermaGenericRepository<SwitchProperties, SwitchPropertiesData, SwitchPropertiesFrame> implements SwitchPropertiesRepository { @Override public Collection<SwitchProperties> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(SwitchPropertiesFrame.FRAME_LABEL)) .toListExplicit(SwitchPropertiesFrame.class).stream() .map(SwitchProperties::new) .collect(Collectors.toList()); } FermaSwitchPropertiesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<SwitchProperties> findAll(); @Override Optional<SwitchProperties> findBySwitchId(SwitchId switchId); }### Answer: @Test public void shouldCreateSwitchPropertiesWithRelation() { Switch origSwitch = Switch.builder() .switchId(TEST_SWITCH_ID) .description("Some description") .build(); switchRepository.add(origSwitch); SwitchProperties switchProperties = SwitchProperties.builder() .switchObj(origSwitch) .supportedTransitEncapsulation(SwitchProperties.DEFAULT_FLOW_ENCAPSULATION_TYPES) .build(); switchPropertiesRepository.add(switchProperties); List<SwitchProperties> switchPropertiesResult = new ArrayList<>(switchPropertiesRepository.findAll()); assertEquals(1, switchPropertiesResult.size()); assertNotNull(switchPropertiesResult.get(0).getSwitchObj()); }
### Question: FermaSwitchPropertiesRepository extends FermaGenericRepository<SwitchProperties, SwitchPropertiesData, SwitchPropertiesFrame> implements SwitchPropertiesRepository { @Override public Optional<SwitchProperties> findBySwitchId(SwitchId switchId) { List<? extends SwitchPropertiesFrame> switchPropertiesFrames = framedGraph().traverse(g -> g.V() .hasLabel(SwitchPropertiesFrame.FRAME_LABEL) .has(SwitchPropertiesFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .toListExplicit(SwitchPropertiesFrame.class); return switchPropertiesFrames.isEmpty() ? Optional.empty() : Optional.of(switchPropertiesFrames.get(0)) .map(SwitchProperties::new); } FermaSwitchPropertiesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<SwitchProperties> findAll(); @Override Optional<SwitchProperties> findBySwitchId(SwitchId switchId); }### Answer: @Test public void shouldFindSwitchPropertiesBySwitchId() { Switch origSwitch = Switch.builder() .switchId(TEST_SWITCH_ID) .description("Some description") .build(); switchRepository.add(origSwitch); SwitchProperties switchProperties = SwitchProperties.builder() .switchObj(origSwitch) .supportedTransitEncapsulation(SwitchProperties.DEFAULT_FLOW_ENCAPSULATION_TYPES) .build(); switchPropertiesRepository.add(switchProperties); Optional<SwitchProperties> switchPropertiesOptional = switchPropertiesRepository.findBySwitchId(TEST_SWITCH_ID); assertTrue(switchPropertiesOptional.isPresent()); } @Test public void shouldCreatePropertiesWithServer42Props() { Switch origSwitch = Switch.builder().switchId(TEST_SWITCH_ID) .description("Some description").build(); switchRepository.add(origSwitch); SwitchProperties switchProperties = SwitchProperties.builder() .switchObj(origSwitch) .server42FlowRtt(true) .server42Port(SERVER_42_PORT) .server42Vlan(SERVER_42_VLAN) .server42MacAddress(SERVER_42_MAC_ADDRESS) .supportedTransitEncapsulation(SwitchProperties.DEFAULT_FLOW_ENCAPSULATION_TYPES) .build(); switchPropertiesRepository.add(switchProperties); Optional<SwitchProperties> switchPropertiesOptional = switchPropertiesRepository.findBySwitchId(TEST_SWITCH_ID); assertTrue(switchPropertiesOptional.isPresent()); assertTrue(switchPropertiesOptional.get().isServer42FlowRtt()); assertEquals(SERVER_42_PORT, switchPropertiesOptional.get().getServer42Port()); assertEquals(SERVER_42_VLAN, switchPropertiesOptional.get().getServer42Vlan()); assertEquals(SERVER_42_MAC_ADDRESS, switchPropertiesOptional.get().getServer42MacAddress()); } @Test public void shouldCreatePropertiesWithNullServer42Props() { Switch origSwitch = Switch.builder().switchId(TEST_SWITCH_ID) .description("Some description").build(); switchRepository.add(origSwitch); SwitchProperties switchProperties = SwitchProperties.builder() .switchObj(origSwitch) .server42Port(null) .server42Vlan(null) .server42MacAddress(null) .supportedTransitEncapsulation(SwitchProperties.DEFAULT_FLOW_ENCAPSULATION_TYPES).build(); switchPropertiesRepository.add(switchProperties); Optional<SwitchProperties> switchPropertiesOptional = switchPropertiesRepository.findBySwitchId(TEST_SWITCH_ID); assertTrue(switchPropertiesOptional.isPresent()); assertFalse(switchPropertiesOptional.get().isServer42FlowRtt()); assertNull(switchPropertiesOptional.get().getServer42Port()); assertNull(switchPropertiesOptional.get().getServer42MacAddress()); }
### Question: FermaLinkPropsRepository extends FermaGenericRepository<LinkProps, LinkPropsData, LinkPropsFrame> implements LinkPropsRepository { @Override public Collection<LinkProps> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(LinkPropsFrame.FRAME_LABEL)) .toListExplicit(LinkPropsFrame.class).stream() .map(LinkProps::new) .collect(Collectors.toList()); } FermaLinkPropsRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<LinkProps> findAll(); @Override Collection<LinkProps> findByEndpoints(SwitchId srcSwitch, Integer srcPort, SwitchId dstSwitch, Integer dstPort); }### Answer: @Test public void shouldCreateLinkProps() { createLinkProps(1); assertEquals(1, linkPropsRepository.findAll().size()); } @Test public void shouldDeleteLinkProps() { LinkProps linkProps = createLinkProps(1); transactionManager.doInTransaction(() -> { linkPropsRepository.remove(linkProps); }); assertEquals(0, linkPropsRepository.findAll().size()); }
### Question: FermaLinkPropsRepository extends FermaGenericRepository<LinkProps, LinkPropsData, LinkPropsFrame> implements LinkPropsRepository { @Override public Collection<LinkProps> findByEndpoints(SwitchId srcSwitch, Integer srcPort, SwitchId dstSwitch, Integer dstPort) { return framedGraph().traverse(g -> { GraphTraversal<Vertex, Vertex> traversal = g.V() .hasLabel(LinkPropsFrame.FRAME_LABEL); if (srcSwitch != null) { traversal = traversal.has(LinkPropsFrame.SRC_SWITCH_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(srcSwitch)); } if (srcPort != null) { traversal = traversal.has(LinkPropsFrame.SRC_PORT_PROPERTY, srcPort); } if (dstSwitch != null) { traversal = traversal.has(LinkPropsFrame.DST_SWITCH_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(dstSwitch)); } if (dstPort != null) { traversal = traversal.has(LinkPropsFrame.DST_PORT_PROPERTY, dstPort); } return traversal; }).toListExplicit(LinkPropsFrame.class).stream() .map(LinkProps::new) .collect(Collectors.toList()); } FermaLinkPropsRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<LinkProps> findAll(); @Override Collection<LinkProps> findByEndpoints(SwitchId srcSwitch, Integer srcPort, SwitchId dstSwitch, Integer dstPort); }### Answer: @Test public void shouldFindLinkPropsByEndpoints() { createLinkProps(2); List<LinkProps> foundLinkProps = Lists.newArrayList( linkPropsRepository.findByEndpoints(TEST_SWITCH_A_ID, 1, TEST_SWITCH_B_ID, 2)); assertThat(foundLinkProps, Matchers.hasSize(1)); } @Test public void shouldFindLinkPropsBySrcEndpoint() { createLinkProps(2); List<LinkProps> foundLinkProps = Lists.newArrayList( linkPropsRepository.findByEndpoints(TEST_SWITCH_A_ID, 1, null, null)); assertThat(foundLinkProps, Matchers.hasSize(1)); } @Test public void shouldFindLinkPropsByDestEndpoint() { createLinkProps(2); List<LinkProps> foundLinkProps = Lists.newArrayList( linkPropsRepository.findByEndpoints(null, null, TEST_SWITCH_B_ID, 2)); assertThat(foundLinkProps, Matchers.hasSize(1)); } @Test public void shouldFindLinkPropsBySrcAndDestSwitches() { createLinkProps(1); List<LinkProps> foundLinkProps = Lists.newArrayList( linkPropsRepository.findByEndpoints(TEST_SWITCH_A_ID, null, TEST_SWITCH_B_ID, null)); assertThat(foundLinkProps, Matchers.hasSize(1)); }
### Question: FlowValidationService { public List<SwitchId> getSwitchIdListByFlowId(String flowId) { return switchRepository.findSwitchesInFlowPathByFlowId(flowId).stream() .map(Switch::getSwitchId) .collect(Collectors.toList()); } FlowValidationService(PersistenceManager persistenceManager, FlowResourcesConfig flowResourcesConfig, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient); void checkFlowStatus(String flowId); List<SwitchId> getSwitchIdListByFlowId(String flowId); List<FlowValidationResponse> validateFlow(String flowId, List<SwitchFlowEntries> switchFlowEntries, List<SwitchMeterEntries> switchMeterEntries); }### Answer: @Test public void shouldGetSwitchIdListByFlowId() { buildTransitVlanFlow(""); List<SwitchId> switchIds = service.getSwitchIdListByFlowId(TEST_FLOW_ID_A); assertEquals(4, switchIds.size()); buildOneSwitchPortFlow(); switchIds = service.getSwitchIdListByFlowId(TEST_FLOW_ID_B); assertEquals(1, switchIds.size()); }
### Question: OneToOneMapping implements MappingApproach { public void remove(SwitchId switchId, String region) { remove(switchId); } OneToOneMapping(Clock clock, Duration staleWipeDelay); Optional<String> lookup(SwitchId switchId); @Override void set(SwitchId switchId, String region); void add(SwitchId switchId, String region); void remove(SwitchId switchId, String region); void remove(SwitchId switchId); Map<String, Set<SwitchId>> makeReversedMapping(); }### Answer: @Test public void testRemove() { OneToOneMapping subject = makeSubject(); subject.add(SWITCH_ALPHA, REGION_A); subject.add(SWITCH_BETA, REGION_A); subject.remove(SWITCH_ALPHA); Optional<String> result = subject.lookup(SWITCH_ALPHA); Assert.assertTrue(result.isPresent()); Assert.assertEquals(REGION_A, result.get()); Assert.assertTrue(subject.lookup(SWITCH_ALPHA).isPresent()); clock.adjust(staleDelay.plus(Duration.ofSeconds(1))); Assert.assertFalse(subject.lookup(SWITCH_ALPHA).isPresent()); Assert.assertTrue(subject.lookup(SWITCH_BETA).isPresent()); }
### Question: SwitchReadWriteConnectMonitor extends SwitchConnectMonitor { @Override protected boolean isReadWriteMode() { return true; } SwitchReadWriteConnectMonitor(SwitchMonitorCarrier carrier, Clock clock, SwitchId switchId); }### Answer: @Test public void multipleConnections() { SwitchReadWriteConnectMonitor subject = makeSubject(SWITCH_ALPHA); SwitchInfoData connectEvent = makeConnectNotification(SWITCH_ALPHA); subject.handleSwitchStatusNotification(connectEvent, REGION_A); verify(carrier, times(1)) .switchStatusUpdateNotification(eq(connectEvent.getSwitchId()), eq(connectEvent)); verify(carrier).regionUpdateNotification( eq(new RegionMappingSet(connectEvent.getSwitchId(), REGION_A, subject.isReadWriteMode()))); subject.handleSwitchStatusNotification(connectEvent, REGION_B); verify(carrier, times(1)) .switchStatusUpdateNotification(eq(connectEvent.getSwitchId()), eq(connectEvent)); verify(carrier, never()).regionUpdateNotification( eq(new RegionMappingSet(connectEvent.getSwitchId(), REGION_B, subject.isReadWriteMode()))); } @Test public void disconnectOneOfOneConnections() { SwitchReadWriteConnectMonitor subject = makeSubject(SWITCH_ALPHA); SwitchInfoData connectEvent = makeConnectNotification(SWITCH_ALPHA); subject.handleSwitchStatusNotification(connectEvent, REGION_A); verify(carrier).switchStatusUpdateNotification(eq(connectEvent.getSwitchId()), eq(connectEvent)); verify(carrier).regionUpdateNotification( eq(new RegionMappingSet(connectEvent.getSwitchId(), REGION_A, subject.isReadWriteMode()))); Instant now = clock.adjust(Duration.ofSeconds(1)); Assert.assertTrue(subject.isAvailable()); SwitchInfoData disconnectEvent = makeDisconnectNotification(connectEvent.getSwitchId()); subject.handleSwitchStatusNotification(disconnectEvent, REGION_A); verify(carrier).switchStatusUpdateNotification( eq(disconnectEvent.getSwitchId()), ArgumentMatchers.eq(disconnectEvent)); Assert.assertFalse(subject.isAvailable()); Assert.assertEquals(now, subject.getBecomeUnavailableAt()); } @Test public void disconnectTwoOfTwoConnections() { SwitchReadWriteConnectMonitor subject = makeSubject(SWITCH_ALPHA); SwitchInfoData connectEvent = makeConnectNotification(SWITCH_ALPHA); subject.handleSwitchStatusNotification(connectEvent, REGION_A); subject.handleSwitchStatusNotification(connectEvent, REGION_B); Assert.assertTrue(subject.isAvailable()); SwitchInfoData disconnectEvent = makeDisconnectNotification(connectEvent.getSwitchId()); clock.adjust(Duration.ofSeconds(1)); subject.handleSwitchStatusNotification(disconnectEvent, REGION_A); verify(carrier).regionUpdateNotification( eq(new RegionMappingSet(disconnectEvent.getSwitchId(), REGION_B, subject.isReadWriteMode()))); reset(carrier); Instant failedAt = clock.adjust(Duration.ofSeconds(1)); subject.handleSwitchStatusNotification(disconnectEvent, REGION_B); Assert.assertFalse(subject.isAvailable()); Assert.assertEquals(failedAt, subject.getBecomeUnavailableAt()); verify(carrier).switchStatusUpdateNotification(eq(disconnectEvent.getSwitchId()), eq(disconnectEvent)); verify(carrier).regionUpdateNotification( eq(new RegionMappingRemove(disconnectEvent.getSwitchId(), null, subject.isReadWriteMode()))); verifyNoMoreInteractions(carrier); }
### Question: SwitchMonitorService { public void handleStatusUpdateNotification(SwitchInfoData notification, String region) { SwitchMonitorEntry entry = lookupOrCreateSwitchMonitor(notification.getSwitchId()); entry.handleStatusUpdateNotification(notification, region); } SwitchMonitorService(Clock clock, SwitchMonitorCarrier carrier); void handleTimerTick(); void handleRegionOfflineNotification(String region); void handleStatusUpdateNotification(SwitchInfoData notification, String region); void handleNetworkDumpResponse(NetworkDumpSwitchData response, String region); }### Answer: @Test public void regularSwitchConnectSequence() { SwitchMonitorService subject = makeSubject(); SwitchInfoData swAdd = new SwitchInfoData(SWITCH_ALPHA, SwitchChangeType.ADDED); subject.handleStatusUpdateNotification(swAdd, REGION_ALPHA); verify(carrier).regionUpdateNotification( eq(new RegionMappingAdd(swAdd.getSwitchId(), REGION_ALPHA, false))); verifyNoMoreInteractions(carrier); SwitchInfoData swActivate = makeSwitchActivateNotification(swAdd.getSwitchId()); subject.handleStatusUpdateNotification(swActivate, REGION_ALPHA); verify(carrier).switchStatusUpdateNotification(eq(swActivate.getSwitchId()), eq(swActivate)); verify(carrier).regionUpdateNotification( eq(new RegionMappingSet(swActivate.getSwitchId(), REGION_ALPHA, true))); verifyNoMoreInteractions(carrier); }
### Question: PacketService { public void handleLldpData(LldpInfoData data) { transactionManager.doInTransaction(() -> { FlowRelatedData flowRelatedData = findFlowRelatedData(data); if (flowRelatedData == null) { return; } SwitchConnectedDevice device = getOrCreateLldpDevice(data, flowRelatedData.originalVlan); if (device == null) { return; } device.setTtl(data.getTtl()); device.setPortDescription(data.getPortDescription()); device.setSystemName(data.getSystemName()); device.setSystemDescription(data.getSystemDescription()); device.setSystemCapabilities(data.getSystemCapabilities()); device.setManagementAddress(data.getManagementAddress()); device.setTimeLastSeen(Instant.ofEpochMilli(data.getTimestamp())); device.setFlowId(flowRelatedData.flowId); device.setSource(flowRelatedData.source); }); } PacketService(PersistenceManager persistenceManager); void handleLldpData(LldpInfoData data); void handleArpData(ArpInfoData data); static final int FULL_PORT_VLAN; }### Answer: @Test public void testHandleLldpDataSameTimeOnCreate() { LldpInfoData data = createLldpInfoDataData(); packetService.handleLldpData(data); Collection<SwitchConnectedDevice> devices = switchConnectedDeviceRepository.findAll(); assertEquals(1, devices.size()); assertEquals(devices.iterator().next().getTimeFirstSeen(), devices.iterator().next().getTimeLastSeen()); } @Test public void testHandleLldpDataDifferentTimeOnUpdate() throws InterruptedException { packetService.handleLldpData(createLldpInfoDataData()); Thread.sleep(10); packetService.handleLldpData(createLldpInfoDataData()); Collection<SwitchConnectedDevice> devices = switchConnectedDeviceRepository.findAll(); assertEquals(1, devices.size()); assertNotEquals(devices.iterator().next().getTimeFirstSeen(), devices.iterator().next().getTimeLastSeen()); } @Test public void testHandleLldpDataNonExistentSwitch() { LldpInfoData data = createLldpInfoDataData(); data.setSwitchId(new SwitchId("12345")); packetService.handleLldpData(data); assertTrue(switchConnectedDeviceRepository.findAll().isEmpty()); }
### Question: PacketService { public void handleArpData(ArpInfoData data) { transactionManager.doInTransaction(() -> { FlowRelatedData flowRelatedData = findFlowRelatedData(data); if (flowRelatedData == null) { return; } SwitchConnectedDevice device = getOrCreateArpDevice(data, flowRelatedData.originalVlan); if (device == null) { return; } device.setTimeLastSeen(Instant.ofEpochMilli(data.getTimestamp())); device.setFlowId(flowRelatedData.flowId); device.setSource(flowRelatedData.source); }); } PacketService(PersistenceManager persistenceManager); void handleLldpData(LldpInfoData data); void handleArpData(ArpInfoData data); static final int FULL_PORT_VLAN; }### Answer: @Test public void testHandleArpDataSameTimeOnCreate() { packetService.handleArpData(createArpInfoData()); Collection<SwitchConnectedDevice> devices = switchConnectedDeviceRepository.findAll(); assertEquals(1, devices.size()); assertEquals(devices.iterator().next().getTimeFirstSeen(), devices.iterator().next().getTimeLastSeen()); } @Test public void testHandleArpDataDifferentTimeOnUpdate() throws InterruptedException { packetService.handleArpData(createArpInfoData()); Thread.sleep(10); packetService.handleArpData(createArpInfoData()); Collection<SwitchConnectedDevice> devices = switchConnectedDeviceRepository.findAll(); assertEquals(1, devices.size()); assertNotEquals(devices.iterator().next().getTimeFirstSeen(), devices.iterator().next().getTimeLastSeen()); } @Test public void testHandleArpDataNonExistentSwitch() { ArpInfoData data = createArpInfoData(); data.setSwitchId(new SwitchId("12345")); packetService.handleArpData(data); assertTrue(switchConnectedDeviceRepository.findAll().isEmpty()); }
### Question: PacketService { @VisibleForTesting FlowRelatedData findFlowRelatedDataForOneSwitchFlow(ConnectedDevicePacketBase data) { int outputVlan = data.getVlans().isEmpty() ? 0 : data.getVlans().get(0); int customerVlan = data.getVlans().size() > 1 ? data.getVlans().get(1) : 0; Flow flow = getFlowBySwitchIdInPortAndOutVlan( data.getSwitchId(), data.getPortNumber(), outputVlan, getPacketName(data)); if (flow == null) { return null; } if (!flow.isOneSwitchFlow()) { log.warn("Found NOT one switch flow {} by SwitchId {}, port number {}, vlan {} from {} packet", flow.getFlowId(), data.getSwitchId(), data.getPortNumber(), outputVlan, getPacketName(data)); return null; } if (flow.getSrcPort() == flow.getDestPort()) { return getOneSwitchOnePortFlowRelatedData(flow, outputVlan, customerVlan, data); } if (data.getPortNumber() == flow.getSrcPort()) { if (flow.getSrcVlan() == FULL_PORT_VLAN) { if (flow.getDestVlan() == FULL_PORT_VLAN) { return new FlowRelatedData(outputVlan, flow.getFlowId(), true); } else { return new FlowRelatedData(customerVlan, flow.getFlowId(), true); } } else { return new FlowRelatedData(flow.getSrcVlan(), flow.getFlowId(), true); } } else if (data.getPortNumber() == flow.getDestPort()) { if (flow.getDestVlan() == FULL_PORT_VLAN) { if (flow.getSrcVlan() == FULL_PORT_VLAN) { return new FlowRelatedData(outputVlan, flow.getFlowId(), false); } else { return new FlowRelatedData(customerVlan, flow.getFlowId(), false); } } else { return new FlowRelatedData(flow.getDestVlan(), flow.getFlowId(), false); } } log.warn("Got LLDP packet from one switch flow {} with non-src/non-dst vlan {}. SwitchId {}, " + "port number {}", flow.getFlowId(), outputVlan, data.getSwitchId(), data.getPortNumber()); return null; } PacketService(PersistenceManager persistenceManager); void handleLldpData(LldpInfoData data); void handleArpData(ArpInfoData data); static final int FULL_PORT_VLAN; }### Answer: @Test @Parameters(method = "getOneSwitchOnePortFlowParameters") public void findFlowRelatedDataForOneSwitchOnePortFlowTest( int inVlan, int srcVlan, int dstVlan, List<Integer> vlansInPacket, boolean source) { createFlow(FLOW_ID, srcVlan, dstVlan, null, true, true); LldpInfoData data = createLldpInfoDataData(SWITCH_ID_1, vlansInPacket, PORT_NUMBER_1); FlowRelatedData flowRelatedData = packetService.findFlowRelatedDataForOneSwitchFlow(data); assertEquals(FLOW_ID, flowRelatedData.getFlowId()); assertEquals(inVlan, flowRelatedData.getOriginalVlan()); assertEquals(source, flowRelatedData.getSource()); } @Test @Parameters(method = "getOneSwitchFlowParameters") public void findFlowRelatedDataForOneSwitchFlowTest( int inVlan, int srcVlan, int dstVlan, List<Integer> vlansInPacket, boolean source) { createFlow(FLOW_ID, srcVlan, dstVlan, null, true, false); LldpInfoData data = createLldpInfoDataData( SWITCH_ID_1, vlansInPacket, source ? PORT_NUMBER_1 : PORT_NUMBER_2); FlowRelatedData flowRelatedData = packetService.findFlowRelatedDataForOneSwitchFlow(data); assertEquals(FLOW_ID, flowRelatedData.getFlowId()); assertEquals(inVlan, flowRelatedData.getOriginalVlan()); assertEquals(source, flowRelatedData.getSource()); }
### Question: PacketService { @VisibleForTesting FlowRelatedData findFlowRelatedDataForVlanFlow(ConnectedDevicePacketBase data) { if (data.getVlans().isEmpty()) { log.warn("Got {} packet without transit VLAN: {}", getPacketName(data), data); return null; } int transitVlan = data.getVlans().get(0); Flow flow = findFlowByTransitVlan(transitVlan); if (flow == null) { return null; } int customerVlan = data.getVlans().size() > 1 ? data.getVlans().get(1) : 0; if (data.getSwitchId().equals(flow.getSrcSwitchId())) { if (flow.getSrcVlan() == FULL_PORT_VLAN) { return new FlowRelatedData(customerVlan, flow.getFlowId(), true); } else { return new FlowRelatedData(flow.getSrcVlan(), flow.getFlowId(), true); } } else if (data.getSwitchId().equals(flow.getDestSwitchId())) { if (flow.getDestVlan() == FULL_PORT_VLAN) { return new FlowRelatedData(customerVlan, flow.getFlowId(), false); } else { return new FlowRelatedData(flow.getDestVlan(), flow.getFlowId(), false); } } else { log.warn("Got {} packet from Flow {} on non-src/non-dst switch {}. Transit vlan: {}", getPacketName(data), flow.getFlowId(), data.getSwitchId(), transitVlan); return null; } } PacketService(PersistenceManager persistenceManager); void handleLldpData(LldpInfoData data); void handleArpData(ArpInfoData data); static final int FULL_PORT_VLAN; }### Answer: @Test @Parameters(method = "getVlanFlowParameters") public void findFlowRelatedDataForVlanFlowTest( int inVlan, int srcVlan, int dstVlan, int transitVlan, List<Integer> vlansInPacket, boolean source) { createFlow(FLOW_ID, srcVlan, dstVlan, transitVlan, false, false); LldpInfoData data = createLldpInfoDataData( source ? SWITCH_ID_1 : SWITCH_ID_2, vlansInPacket, source ? PORT_NUMBER_1 : PORT_NUMBER_2); FlowRelatedData flowRelatedData = packetService.findFlowRelatedDataForVlanFlow(data); assertEquals(FLOW_ID, flowRelatedData.getFlowId()); assertEquals(inVlan, flowRelatedData.getOriginalVlan()); assertEquals(source, flowRelatedData.getSource()); }
### Question: PacketService { @VisibleForTesting FlowRelatedData findFlowRelatedDataForVxlanFlow(ConnectedDevicePacketBase data) { int inputVlan = data.getVlans().isEmpty() ? 0 : data.getVlans().get(0); Flow flow = getFlowBySwitchIdPortAndVlan( data.getSwitchId(), data.getPortNumber(), inputVlan, getPacketName(data)); if (flow == null) { return null; } if (data.getSwitchId().equals(flow.getSrcSwitchId())) { return new FlowRelatedData(inputVlan, flow.getFlowId(), true); } else if (data.getSwitchId().equals(flow.getDestSwitchId())) { return new FlowRelatedData(inputVlan, flow.getFlowId(), false); } else { log.warn("Got {} packet from Flow {} on non-src/non-dst switch {}. Port number {}, input vlan {}", getPacketName(data), flow.getFlowId(), data.getSwitchId(), data.getPortNumber(), inputVlan); return null; } } PacketService(PersistenceManager persistenceManager); void handleLldpData(LldpInfoData data); void handleArpData(ArpInfoData data); static final int FULL_PORT_VLAN; }### Answer: @Test @Parameters(method = "getInOutVlanCombinationForVxlanParameters") public void findFlowRelatedDataForVxlanFlowTest( int inVlan, int srcVlan, int dstVlan, List<Integer> vlansInPacket, boolean source) { createFlow(FLOW_ID, srcVlan, dstVlan, null, false, false); LldpInfoData data = createLldpInfoDataData( source ? SWITCH_ID_1 : SWITCH_ID_2, vlansInPacket, source ? PORT_NUMBER_1 : PORT_NUMBER_2); FlowRelatedData flowRelatedData = packetService.findFlowRelatedDataForVxlanFlow(data); assertEquals(FLOW_ID, flowRelatedData.getFlowId()); assertEquals(inVlan, flowRelatedData.getOriginalVlan()); assertEquals(source, flowRelatedData.getSource()); }
### Question: RerouteService { public void processSingleSwitchFlowStatusUpdate(SwitchStateChanged request) { transactionManager.doInTransaction(() -> { Collection<Flow> affectedFlows = flowRepository.findOneSwitchFlows(request.getSwitchId()); FlowStatus newFlowStatus = request.getStatus() == SwitchStatus.ACTIVE ? FlowStatus.UP : FlowStatus.DOWN; String newFlowStatusInfo = request.getStatus() == SwitchStatus.ACTIVE ? null : format("Switch %s is inactive", request.getSwitchId()); FlowPathStatus newFlowPathStatus = request.getStatus() == SwitchStatus.ACTIVE ? FlowPathStatus.ACTIVE : FlowPathStatus.INACTIVE; for (Flow flow : affectedFlows) { log.info("Updating flow and path statuses for flow {} to {}, {}", flow.getFlowId(), newFlowStatus, newFlowPathStatus); flowDashboardLogger.onFlowStatusUpdate(flow.getFlowId(), newFlowStatus); flow.setStatus(newFlowStatus); flow.setStatusInfo(newFlowStatusInfo); flow.getForwardPath().setStatus(newFlowPathStatus); flow.getReversePath().setStatus(newFlowPathStatus); } }); } RerouteService(PersistenceManager persistenceManager); void rerouteAffectedFlows(MessageSender sender, String correlationId, RerouteAffectedFlows command); void rerouteInactiveAffectedFlows(MessageSender sender, String correlationId, SwitchId switchId); void rerouteInactiveFlows(MessageSender sender, String correlationId, RerouteInactiveFlows command); Collection<FlowPath> getAffectedFlowPaths(SwitchId switchId, int port); List<FlowPath> getPathsForSwapping(Collection<FlowPath> paths); List<FlowWithAffectedPaths> groupPathsForRerouting(Collection<FlowPath> paths); Set<Flow> groupAffectedPinnedFlows(Collection<FlowPath> paths); Map<Flow, Set<PathId>> getInactiveFlowsForRerouting(); Set<Flow> getAffectedInactiveFlowsForRerouting(SwitchId switchId); void processManualRerouteRequest(MessageSender sender, String correlationId, FlowRerouteRequest request); void processSingleSwitchFlowStatusUpdate(SwitchStateChanged request); }### Answer: @Test public void handleUpdateSingleSwitchFlows() { FlowRepository flowRepository = mock(FlowRepository.class); when(flowRepository.findOneSwitchFlows(oneSwitchFlow.getSrcSwitch().getSwitchId())) .thenReturn(Arrays.asList(oneSwitchFlow)); FlowPathRepository flowPathRepository = mock(FlowPathRepository.class); RepositoryFactory repositoryFactory = mock(RepositoryFactory.class); when(repositoryFactory.createFlowRepository()) .thenReturn(flowRepository); when(repositoryFactory.createFlowPathRepository()) .thenReturn(flowPathRepository); PersistenceManager persistenceManager = mock(PersistenceManager.class); when(persistenceManager.getRepositoryFactory()).thenReturn(repositoryFactory); when(persistenceManager.getTransactionManager()).thenReturn(transactionManager); RerouteService rerouteService = new RerouteService(persistenceManager); rerouteService.processSingleSwitchFlowStatusUpdate( new SwitchStateChanged(oneSwitchFlow.getSrcSwitchId(), SwitchStatus.INACTIVE)); assertEquals(format("Switch %s is inactive", oneSwitchFlow.getSrcSwitchId()), FlowStatus.DOWN, oneSwitchFlow.getStatus()); }
### Question: RerouteService { public void rerouteInactiveAffectedFlows(MessageSender sender, String correlationId, SwitchId switchId) { Set<Flow> flowsForRerouting = getAffectedInactiveFlowsForRerouting(switchId); for (Flow flow : flowsForRerouting) { if (flow.isPinned()) { log.info("Skipping reroute command for pinned flow {}", flow.getFlowId()); } else { log.info("Produce reroute (attempt to restore inactive flow) request for {} (switch online {})", flow.getFlowId(), switchId); FlowThrottlingData flowThrottlingData = getFlowThrottlingDataBuilder(flow) .correlationId(correlationId) .affectedIsl(Collections.emptySet()) .force(false) .effectivelyDown(true) .reason(format("Switch '%s' online", switchId)) .build(); sender.emitRerouteCommand(flow.getFlowId(), flowThrottlingData); } } } RerouteService(PersistenceManager persistenceManager); void rerouteAffectedFlows(MessageSender sender, String correlationId, RerouteAffectedFlows command); void rerouteInactiveAffectedFlows(MessageSender sender, String correlationId, SwitchId switchId); void rerouteInactiveFlows(MessageSender sender, String correlationId, RerouteInactiveFlows command); Collection<FlowPath> getAffectedFlowPaths(SwitchId switchId, int port); List<FlowPath> getPathsForSwapping(Collection<FlowPath> paths); List<FlowWithAffectedPaths> groupPathsForRerouting(Collection<FlowPath> paths); Set<Flow> groupAffectedPinnedFlows(Collection<FlowPath> paths); Map<Flow, Set<PathId>> getInactiveFlowsForRerouting(); Set<Flow> getAffectedInactiveFlowsForRerouting(SwitchId switchId); void processManualRerouteRequest(MessageSender sender, String correlationId, FlowRerouteRequest request); void processSingleSwitchFlowStatusUpdate(SwitchStateChanged request); }### Answer: @Test public void handleRerouteInactiveAffectedFlows() { FlowPathRepository pathRepository = mock(FlowPathRepository.class); when(pathRepository.findInactiveBySegmentSwitch(regularFlow.getSrcSwitchId())) .thenReturn(Arrays.asList(regularFlow.getForwardPath(), regularFlow.getReversePath())); RepositoryFactory repositoryFactory = mock(RepositoryFactory.class); when(repositoryFactory.createFlowPathRepository()) .thenReturn(pathRepository); PersistenceManager persistenceManager = mock(PersistenceManager.class); when(persistenceManager.getRepositoryFactory()).thenReturn(repositoryFactory); when(persistenceManager.getTransactionManager()).thenReturn(transactionManager); RerouteService rerouteService = new RerouteService(persistenceManager); regularFlow.setStatus(FlowStatus.DOWN); rerouteService.rerouteInactiveAffectedFlows(carrier, CORRELATION_ID, regularFlow.getSrcSwitchId()); FlowThrottlingData expected = FlowThrottlingData.builder() .correlationId(CORRELATION_ID) .priority(regularFlow.getPriority()) .timeCreate(regularFlow.getTimeCreate()) .affectedIsl(Collections.emptySet()) .force(false) .effectivelyDown(true) .reason(format("Switch '%s' online", regularFlow.getSrcSwitchId())) .build(); verify(carrier).emitRerouteCommand(eq(regularFlow.getFlowId()), eq(expected)); regularFlow.setStatus(FlowStatus.UP); }
### Question: RerouteService { public void processManualRerouteRequest(MessageSender sender, String correlationId, FlowRerouteRequest request) { Optional<Flow> flow = flowRepository.findById(request.getFlowId()); FlowThrottlingData flowThrottlingData = getFlowThrottlingDataBuilder(flow.orElse(null)) .correlationId(correlationId) .affectedIsl(request.getAffectedIsl()) .force(request.isForce()) .effectivelyDown(request.isEffectivelyDown()) .reason(request.getReason()) .build(); sender.emitManualRerouteCommand(request.getFlowId(), flowThrottlingData); } RerouteService(PersistenceManager persistenceManager); void rerouteAffectedFlows(MessageSender sender, String correlationId, RerouteAffectedFlows command); void rerouteInactiveAffectedFlows(MessageSender sender, String correlationId, SwitchId switchId); void rerouteInactiveFlows(MessageSender sender, String correlationId, RerouteInactiveFlows command); Collection<FlowPath> getAffectedFlowPaths(SwitchId switchId, int port); List<FlowPath> getPathsForSwapping(Collection<FlowPath> paths); List<FlowWithAffectedPaths> groupPathsForRerouting(Collection<FlowPath> paths); Set<Flow> groupAffectedPinnedFlows(Collection<FlowPath> paths); Map<Flow, Set<PathId>> getInactiveFlowsForRerouting(); Set<Flow> getAffectedInactiveFlowsForRerouting(SwitchId switchId); void processManualRerouteRequest(MessageSender sender, String correlationId, FlowRerouteRequest request); void processSingleSwitchFlowStatusUpdate(SwitchStateChanged request); }### Answer: @Test public void processManualRerouteRequest() { FlowRepository flowRepository = mock(FlowRepository.class); when(flowRepository.findById(regularFlow.getFlowId())) .thenReturn(Optional.of(regularFlow)); RepositoryFactory repositoryFactory = mock(RepositoryFactory.class); when(repositoryFactory.createFlowRepository()) .thenReturn(flowRepository); PersistenceManager persistenceManager = mock(PersistenceManager.class); when(persistenceManager.getRepositoryFactory()).thenReturn(repositoryFactory); when(persistenceManager.getTransactionManager()).thenReturn(transactionManager); RerouteService rerouteService = new RerouteService(persistenceManager); FlowRerouteRequest request = new FlowRerouteRequest(regularFlow.getFlowId(), true, true, false, Collections.emptySet(), "reason"); rerouteService.processManualRerouteRequest(carrier, CORRELATION_ID, request); FlowThrottlingData expected = FlowThrottlingData.builder() .correlationId(CORRELATION_ID) .priority(regularFlow.getPriority()) .timeCreate(regularFlow.getTimeCreate()) .affectedIsl(Collections.emptySet()) .force(true) .effectivelyDown(true) .reason("reason") .build(); verify(carrier).emitManualRerouteCommand(eq(regularFlow.getFlowId()), eq(expected)); }
### Question: ExtendableTimeWindow { public boolean flushIfReady() { if (firstEventTime == null) { return false; } LocalDateTime now = LocalDateTime.now(clock); boolean isTimeToFlush = lastEventTime.plus(minDelay, ChronoUnit.SECONDS).isBefore(now) || firstEventTime.plus(maxDelay, ChronoUnit.SECONDS).isBefore(now); if (isTimeToFlush) { firstEventTime = null; lastEventTime = null; } return isTimeToFlush; } ExtendableTimeWindow(long minDelay, long maxDelay); ExtendableTimeWindow(long minDelay, long maxDelay, Clock clock); void registerEvent(); boolean flushIfReady(); }### Answer: @Test public void noFlushEmptyWindow() { assertFalse(extendableTimeWindow.flushIfReady()); } @Test public void noFlushEmptyWindow2() { when(clock.instant()).thenReturn(Instant.now()); assertFalse(extendableTimeWindow.flushIfReady()); }
### Question: NetworkUniIslService { public void uniIslSetup(Endpoint endpoint, Isl history) { log.info("Uni-ISL service receive SETUP request for {}", endpoint); IslReference reference; if (history != null) { reference = IslReference.of(history); carrier.setupIslFromHistory(endpoint, reference, history); } else { reference = IslReference.of(endpoint); } endpointData.put(endpoint, reference); } NetworkUniIslService(IUniIslCarrier carrier); void uniIslSetup(Endpoint endpoint, Isl history); void uniIslDiscovery(Endpoint endpoint, IslInfoData speakerDiscoveryEvent); void uniIslFail(Endpoint endpoint); void uniIslPhysicalDown(Endpoint endpoint); void roundTripStatusNotification(RoundTripStatus status); void uniIslBfdStatusUpdate(Endpoint endpoint, BfdStatusUpdate status); void uniIslRemove(Endpoint endpoint); void islRemovedNotification(Endpoint endpoint, IslReference removedIsl); }### Answer: @Test public void newIslWithHistory() { NetworkUniIslService service = new NetworkUniIslService(carrier); Endpoint endpoint1 = Endpoint.of(alphaDatapath, 1); Endpoint endpoint2 = Endpoint.of(alphaDatapath, 2); Switch alphaSwitch = Switch.builder().switchId(alphaDatapath).build(); Switch betaSwitch = Switch.builder().switchId(betaDatapath).build(); Isl islAtoB = Isl.builder() .srcSwitch(alphaSwitch) .srcPort(1) .destSwitch(betaSwitch) .destPort(1).build(); Isl islAtoB2 = Isl.builder() .srcSwitch(alphaSwitch) .srcPort(2) .destSwitch(betaSwitch) .destPort(2).build(); service.uniIslSetup(endpoint1, islAtoB); service.uniIslSetup(endpoint2, islAtoB2); verify(carrier).setupIslFromHistory(endpoint1, IslReference.of(islAtoB), islAtoB); verify(carrier).setupIslFromHistory(endpoint2, IslReference.of(islAtoB2), islAtoB2); }
### Question: NetworkSwitchService { public void switchAddWithHistory(HistoryFacts history) { log.info("Switch service receive switch ADD from history request for {}", history.getSwitchId()); SwitchFsm switchFsm = controllerFactory.produce(persistenceManager, history.getSwitchId(), options); SwitchFsmContext fsmContext = SwitchFsmContext.builder(carrier) .history(history) .build(); controller.put(history.getSwitchId(), switchFsm); controllerExecutor.fire(switchFsm, SwitchFsmEvent.HISTORY, fsmContext); } NetworkSwitchService(ISwitchCarrier carrier, PersistenceManager persistenceManager, NetworkOptions options); void switchAddWithHistory(HistoryFacts history); void switchEvent(SwitchInfoData payload); void switchManagerResponse(SwitchSyncResponse payload, String key); void switchManagerErrorResponse(SwitchSyncErrorData payload, String key); void switchManagerTimeout(SwitchId switchId, String key); void switchBecomeUnmanaged(SwitchId datapath); void switchBecomeManaged(SpeakerSwitchView switchView); void switchPortEvent(PortInfoData payload); void remove(SwitchId datapath); }### Answer: @Test public void switchFromHistoryToOffline() { when(switchRepository.findById(alphaDatapath)).thenReturn( Optional.of(Switch.builder().switchId(alphaDatapath) .build())); HistoryFacts history = new HistoryFacts(alphaDatapath); Switch alphaSwitch = Switch.builder().switchId(alphaDatapath).build(); Switch betaSwitch = Switch.builder().switchId(betaDatapath).build(); Isl islAtoB = Isl.builder() .srcSwitch(alphaSwitch) .srcPort(1) .destSwitch(betaSwitch) .destPort(1).build(); Isl islAtoB2 = Isl.builder() .srcSwitch(alphaSwitch) .srcPort(2) .destSwitch(betaSwitch) .destPort(2).build(); history.addLink(islAtoB); history.addLink(islAtoB2); NetworkSwitchService service = new NetworkSwitchService(carrier, persistenceManager, options); service.switchAddWithHistory(history); verify(carrier).setupPortHandler(Endpoint.of(alphaDatapath, 1), islAtoB); verify(carrier).setupPortHandler(Endpoint.of(alphaDatapath, 2), islAtoB2); verify(carrier).setOnlineMode(Endpoint.of(alphaDatapath, 1), OnlineStatus.OFFLINE); verify(carrier).setOnlineMode(Endpoint.of(alphaDatapath, 2), OnlineStatus.OFFLINE); }
### Question: NetworkIslService { public void islMove(Endpoint endpoint, IslReference reference) { log.debug("ISL service receive MOVED(FAIL) notification for {} (on {})", reference, endpoint); IslFsm islFsm = locateController(reference).fsm; IslFsmContext context = IslFsmContext.builder(carrier, endpoint).build(); controllerExecutor.fire(islFsm, IslFsmEvent.ISL_MOVE, context); } NetworkIslService(IIslCarrier carrier, PersistenceManager persistenceManager, NetworkOptions options); @VisibleForTesting NetworkIslService(IIslCarrier carrier, PersistenceManager persistenceManager, NetworkOptions options, NetworkTopologyDashboardLogger.Builder dashboardLoggerBuilder, Clock clock); void islSetupFromHistory(Endpoint endpoint, IslReference reference, Isl history); void islUp(Endpoint endpoint, IslReference reference, IslDataHolder islData); void islDown(Endpoint endpoint, IslReference reference, IslDownReason reason); void islMove(Endpoint endpoint, IslReference reference); void roundTripStatusNotification(IslReference reference, RoundTripStatus status); void bfdStatusUpdate(Endpoint endpoint, IslReference reference, BfdStatusUpdate status); void bfdEnableDisable(IslReference reference, IslBfdFlagUpdated payload); void islDefaultRuleInstalled(IslReference reference, InstallIslDefaultRulesResult payload); void islDefaultRuleDeleted(IslReference reference, RemoveIslDefaultRulesResult payload); void islDefaultTimeout(IslReference reference, Endpoint endpoint); void remove(IslReference reference); }### Answer: @Test @Ignore("become invalid due to change initialisation logic") public void initialMoveEvent() { emulateEmptyPersistentDb(); IslReference ref = new IslReference(endpointAlpha1, endpointBeta2); service.islMove(ref.getSource(), ref); verify(carrier, times(2)).triggerReroute(any(RerouteAffectedFlows.class)); verify(islRepository).add(argThat( link -> link.getSrcSwitchId().equals(endpointAlpha1.getDatapath()) && link.getSrcPort() == endpointAlpha1.getPortNumber() && link.getDestSwitchId().equals(endpointBeta2.getDatapath()) && link.getDestPort() == endpointBeta2.getPortNumber() && link.getActualStatus() == IslStatus.INACTIVE && link.getStatus() == IslStatus.INACTIVE)); verify(islRepository).add(argThat( link -> link.getSrcSwitchId().equals(endpointBeta2.getDatapath()) && link.getSrcPort() == endpointBeta2.getPortNumber() && link.getDestSwitchId().equals(endpointAlpha1.getDatapath()) && link.getDestPort() == endpointAlpha1.getPortNumber() && link.getActualStatus() == IslStatus.INACTIVE && link.getStatus() == IslStatus.INACTIVE)); verifyNoMoreInteractions(carrier); }
### Question: NetworkIslService { public void islDown(Endpoint endpoint, IslReference reference, IslDownReason reason) { log.debug("ISL service receive FAIL notification for {} (on {})", reference, endpoint); IslFsm islFsm = locateController(reference).fsm; IslFsmContext context = IslFsmContext.builder(carrier, endpoint) .downReason(reason) .build(); controllerExecutor.fire(islFsm, IslFsmEvent.ISL_DOWN, context); } NetworkIslService(IIslCarrier carrier, PersistenceManager persistenceManager, NetworkOptions options); @VisibleForTesting NetworkIslService(IIslCarrier carrier, PersistenceManager persistenceManager, NetworkOptions options, NetworkTopologyDashboardLogger.Builder dashboardLoggerBuilder, Clock clock); void islSetupFromHistory(Endpoint endpoint, IslReference reference, Isl history); void islUp(Endpoint endpoint, IslReference reference, IslDataHolder islData); void islDown(Endpoint endpoint, IslReference reference, IslDownReason reason); void islMove(Endpoint endpoint, IslReference reference); void roundTripStatusNotification(IslReference reference, RoundTripStatus status); void bfdStatusUpdate(Endpoint endpoint, IslReference reference, BfdStatusUpdate status); void bfdEnableDisable(IslReference reference, IslBfdFlagUpdated payload); void islDefaultRuleInstalled(IslReference reference, InstallIslDefaultRulesResult payload); void islDefaultRuleDeleted(IslReference reference, RemoveIslDefaultRulesResult payload); void islDefaultTimeout(IslReference reference, Endpoint endpoint); void remove(IslReference reference); }### Answer: @Test public void setIslUnstableTimeOnPortDown() { setupIslStorageStub(); IslReference reference = prepareActiveIsl(); Instant updateTime = clock.adjust(Duration.ofSeconds(1)); service.islDown(endpointAlpha1, reference, IslDownReason.PORT_DOWN); Isl forward = lookupIsl(reference.getSource(), reference.getDest()); Assert.assertEquals(updateTime, forward.getTimeUnstable()); Isl reverse = lookupIsl(reference.getDest(), reference.getSource()); Assert.assertEquals(updateTime, reverse.getTimeUnstable()); } @Test public void portDownOverriderBfdUp() { setupIslStorageStub(); IslReference reference = prepareBfdEnabledIsl(); reset(dashboardLogger); service.islDown(reference.getSource(), reference, IslDownReason.PORT_DOWN); verify(dashboardLogger).onIslDown(reference); }
### Question: NetworkBfdPortService { public void updateLinkStatus(Endpoint logicalEndpoint, LinkStatus linkStatus) { log.debug("BFD-port service receive logical port status update for {} (logical) status:{}", logicalEndpoint, linkStatus); BfdPortFsm controller = lookupControllerByLogicalEndpoint(logicalEndpoint); controller.updateLinkStatus(carrier, linkStatus); } NetworkBfdPortService(IBfdPortCarrier carrier, PersistenceManager persistenceManager); void setup(Endpoint endpoint, int physicalPortNumber); Endpoint remove(Endpoint logicalEndpoint); void updateLinkStatus(Endpoint logicalEndpoint, LinkStatus linkStatus); void updateOnlineMode(Endpoint endpoint, boolean mode); void enable(Endpoint physicalEndpoint, IslReference reference); void disable(Endpoint physicalEndpoint); void speakerResponse(String key, Endpoint logicalEndpoint, BfdSessionResponse response); void speakerTimeout(String key, Endpoint logicalEndpoint); }### Answer: @Test public void upDownUp() { setupAndEnable(); service.updateLinkStatus(alphaLogicalEndpoint, LinkStatus.DOWN); verify(carrier).bfdDownNotification(alphaEndpoint); verifyNoMoreInteractions(carrier); reset(carrier); service.updateLinkStatus(alphaLogicalEndpoint, LinkStatus.UP); verify(carrier).bfdUpNotification(alphaEndpoint); verifyNoMoreInteractions(carrier); }
### Question: NetworkBfdPortService { public Endpoint remove(Endpoint logicalEndpoint) { log.info("BFD-port service receive REMOVE request for {} (logical)", logicalEndpoint); BfdPortFsm controller = controllerByLogicalPort.remove(logicalEndpoint); if (controller == null) { throw BfdPortControllerNotFoundException.ofLogical(logicalEndpoint); } controllerByPhysicalPort.remove(controller.getPhysicalEndpoint()); remove(controller); return controller.getPhysicalEndpoint(); } NetworkBfdPortService(IBfdPortCarrier carrier, PersistenceManager persistenceManager); void setup(Endpoint endpoint, int physicalPortNumber); Endpoint remove(Endpoint logicalEndpoint); void updateLinkStatus(Endpoint logicalEndpoint, LinkStatus linkStatus); void updateOnlineMode(Endpoint endpoint, boolean mode); void enable(Endpoint physicalEndpoint, IslReference reference); void disable(Endpoint physicalEndpoint); void speakerResponse(String key, Endpoint logicalEndpoint, BfdSessionResponse response); void speakerTimeout(String key, Endpoint logicalEndpoint); }### Answer: @Test public void killDuringInstalling() { setupController(); doAnswer(invocation -> invocation.getArgument(0)) .when(bfdSessionRepository).add(any()); NoviBfdSession session = doEnable(); when(carrier.removeBfdSession(any(NoviBfdSession.class))).thenReturn(removeRequestKey); service.remove(alphaLogicalEndpoint); verifyTerminateSequence(session); } @Test public void killDuringActiveUp() { NoviBfdSession session = setupAndEnable(); when(carrier.removeBfdSession(any(NoviBfdSession.class))).thenReturn(removeRequestKey); service.remove(alphaLogicalEndpoint); verify(carrier).bfdKillNotification(alphaEndpoint); verifyTerminateSequence(session); }
### Question: NetworkBfdPortService { public void setup(Endpoint endpoint, int physicalPortNumber) { log.info("BFD-port service receive SETUP request for {} (physical-port:{})", endpoint, physicalPortNumber); BfdPortFsm controller = controllerFactory.produce(persistenceManager, endpoint, physicalPortNumber); BfdPortFsmContext context = BfdPortFsmContext.builder(carrier).build(); handle(controller, BfdPortFsmEvent.HISTORY, context); controllerByLogicalPort.put(controller.getLogicalEndpoint(), controller); controllerByPhysicalPort.put(controller.getPhysicalEndpoint(), controller); IslReference autostartData = autostart.remove(controller.getPhysicalEndpoint()); if (autostartData != null) { context = BfdPortFsmContext.builder(carrier) .islReference(autostartData) .build(); handle(controller, BfdPortFsmEvent.ENABLE, context); } } NetworkBfdPortService(IBfdPortCarrier carrier, PersistenceManager persistenceManager); void setup(Endpoint endpoint, int physicalPortNumber); Endpoint remove(Endpoint logicalEndpoint); void updateLinkStatus(Endpoint logicalEndpoint, LinkStatus linkStatus); void updateOnlineMode(Endpoint endpoint, boolean mode); void enable(Endpoint physicalEndpoint, IslReference reference); void disable(Endpoint physicalEndpoint); void speakerResponse(String key, Endpoint logicalEndpoint, BfdSessionResponse response); void speakerTimeout(String key, Endpoint logicalEndpoint); }### Answer: @Test public void enableBeforeSetup() { IslReference reference = new IslReference(alphaEndpoint, betaEndpoint); doEnableBeforeSetup(reference); doAnswer(invocation -> invocation.getArgument(0)) .when(bfdSessionRepository).add(any()); mockSwitchLookup(alphaSwitch); mockSwitchLookup(betaSwitch); mockMissingBfdSession(alphaLogicalEndpoint); when(carrier.setupBfdSession(any(NoviBfdSession.class))).thenReturn(setupRequestKey); service.setup(alphaLogicalEndpoint, alphaEndpoint.getPortNumber()); verify(bfdSessionRepository).add(any(BfdSession.class)); verify(carrier).setupBfdSession(argThat( arg -> arg.getTarget().getDatapath().equals(alphaEndpoint.getDatapath()) && arg.getPhysicalPortNumber() == alphaEndpoint.getPortNumber() && arg.getLogicalPortNumber() == alphaLogicalEndpoint.getPortNumber() && arg.getRemote().getDatapath().equals(betaEndpoint.getDatapath()))); verifyNoMoreInteractions(carrier); }
### Question: NetworkWatcherService { public void addWatch(Endpoint endpoint) { addWatch(endpoint, now()); } NetworkWatcherService( IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); @VisibleForTesting NetworkWatcherService( Clock clock, IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); void addWatch(Endpoint endpoint); void removeWatch(Endpoint endpoint); void tick(); void confirmation(Endpoint endpoint, long packetNo); void discovery(IslInfoData discoveryEvent); void roundTripDiscovery(Endpoint endpoint, long packetId); }### Answer: @Test public void addWatch() { NetworkWatcherService w = makeService(); w.addWatch(Endpoint.of(new SwitchId(1), 1), 1); w.addWatch(Endpoint.of(new SwitchId(1), 2), 1); w.addWatch(Endpoint.of(new SwitchId(2), 1), 2); w.addWatch(Endpoint.of(new SwitchId(2), 1), 2); w.addWatch(Endpoint.of(new SwitchId(2), 2), 3); assertThat(w.getConfirmedPackets().size(), is(0)); assertThat(w.getTimeouts().size(), is(3)); verify(carrier, times(5)).sendDiscovery(any(DiscoverIslCommandData.class)); }
### Question: NetworkWatcherService { public void removeWatch(Endpoint endpoint) { log.debug("Watcher service receive REMOVE-watch request for {}", endpoint); carrier.clearDiscovery(endpoint); discoveryPackets.removeIf(packet -> packet.endpoint.equals(endpoint)); roundTripPackets.removeIf(packet -> packet.endpoint.equals(endpoint)); confirmedPackets.removeIf(packet -> packet.endpoint.equals(endpoint)); lastSeenRoundTrip.remove(endpoint); } NetworkWatcherService( IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); @VisibleForTesting NetworkWatcherService( Clock clock, IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); void addWatch(Endpoint endpoint); void removeWatch(Endpoint endpoint); void tick(); void confirmation(Endpoint endpoint, long packetNo); void discovery(IslInfoData discoveryEvent); void roundTripDiscovery(Endpoint endpoint, long packetId); }### Answer: @Test public void removeWatch() { NetworkWatcherService w = makeService(); w.addWatch(Endpoint.of(new SwitchId(1), 1), 1); w.addWatch(Endpoint.of(new SwitchId(1), 2), 2); w.addWatch(Endpoint.of(new SwitchId(2), 1), 3); w.addWatch(Endpoint.of(new SwitchId(2), 2), 4); w.addWatch(Endpoint.of(new SwitchId(3), 1), 5); verify(carrier, times(5)).sendDiscovery(any(DiscoverIslCommandData.class)); w.confirmation(Endpoint.of(new SwitchId(1), 2), 1); w.confirmation(Endpoint.of(new SwitchId(2), 1), 2); assertThat(w.getConfirmedPackets().size(), is(2)); assertThat(w.getTimeouts().size(), is(5)); assertThat(w.getDiscoveryPackets().size(), is(3)); w.removeWatch(Endpoint.of(new SwitchId(1), 2)); w.removeWatch(Endpoint.of(new SwitchId(2), 2)); verify(carrier).clearDiscovery(Endpoint.of(new SwitchId(1), 2)); verify(carrier).clearDiscovery(Endpoint.of(new SwitchId(2), 2)); assertThat(w.getConfirmedPackets().size(), is(1)); assertThat(w.getDiscoveryPackets().size(), is(2)); w.tick(100); assertThat(w.getTimeouts().size(), is(0)); }
### Question: NetworkWatcherService { public void tick() { tick(now()); } NetworkWatcherService( IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); @VisibleForTesting NetworkWatcherService( Clock clock, IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); void addWatch(Endpoint endpoint); void removeWatch(Endpoint endpoint); void tick(); void confirmation(Endpoint endpoint, long packetNo); void discovery(IslInfoData discoveryEvent); void roundTripDiscovery(Endpoint endpoint, long packetId); }### Answer: @Test public void tick() { NetworkWatcherService w = makeService(); w.addWatch(Endpoint.of(new SwitchId(1), 1), 1); w.addWatch(Endpoint.of(new SwitchId(1), 2), 1); w.addWatch(Endpoint.of(new SwitchId(2), 1), 2); w.addWatch(Endpoint.of(new SwitchId(2), 1), 2); w.addWatch(Endpoint.of(new SwitchId(2), 2), 3); assertThat(w.getConfirmedPackets().size(), is(0)); assertThat(w.getTimeouts().size(), is(3)); verify(carrier, times(5)).sendDiscovery(any(DiscoverIslCommandData.class)); w.confirmation(Endpoint.of(new SwitchId(1), 1), 0); w.confirmation(Endpoint.of(new SwitchId(2), 1), 2); assertThat(w.getConfirmedPackets().size(), is(2)); w.tick(100); assertThat(w.getConfirmedPackets().size(), is(0)); verify(carrier).discoveryFailed(eq(Endpoint.of(new SwitchId(1), 1)), eq(0L), anyLong()); verify(carrier).discoveryFailed(eq(Endpoint.of(new SwitchId(2), 1)), eq(2L), anyLong()); verify(carrier, times(2)).discoveryFailed(any(Endpoint.class), anyLong(), anyLong()); assertThat(w.getTimeouts().size(), is(0)); }
### Question: NetworkWatcherService { public void discovery(IslInfoData discoveryEvent) { Endpoint source = new Endpoint(discoveryEvent.getSource()); Long packetId = discoveryEvent.getPacketId(); if (packetId == null) { log.error("Got corrupted discovery packet into {} - packetId field is empty", source); } else { discovery(discoveryEvent, Packet.of(source, packetId)); } } NetworkWatcherService( IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); @VisibleForTesting NetworkWatcherService( Clock clock, IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); void addWatch(Endpoint endpoint); void removeWatch(Endpoint endpoint); void tick(); void confirmation(Endpoint endpoint, long packetNo); void discovery(IslInfoData discoveryEvent); void roundTripDiscovery(Endpoint endpoint, long packetId); }### Answer: @Test public void discovery() { NetworkWatcherService w = makeService(); w.addWatch(Endpoint.of(new SwitchId(1), 1), 1); w.addWatch(Endpoint.of(new SwitchId(1), 2), 1); w.addWatch(Endpoint.of(new SwitchId(2), 1), 2); w.addWatch(Endpoint.of(new SwitchId(2), 1), 2); w.addWatch(Endpoint.of(new SwitchId(2), 2), 3); assertThat(w.getConfirmedPackets().size(), is(0)); assertThat(w.getTimeouts().size(), is(3)); verify(carrier, times(5)).sendDiscovery(any(DiscoverIslCommandData.class)); w.confirmation(Endpoint.of(new SwitchId(1), 1), 0); w.confirmation(Endpoint.of(new SwitchId(2), 1), 2); assertThat(w.getConfirmedPackets().size(), is(2)); PathNode source = new PathNode(new SwitchId(1), 1, 0); PathNode destination = new PathNode(new SwitchId(2), 1, 0); IslInfoData islAlphaBeta = IslInfoData.builder().source(source).destination(destination).packetId(0L).build(); IslInfoData islBetaAlpha = IslInfoData.builder().source(destination).destination(source).packetId(2L).build(); w.discovery(islAlphaBeta); w.discovery(islBetaAlpha); w.tick(100); assertThat(w.getConfirmedPackets().size(), is(0)); verify(carrier).discoveryReceived(eq(new Endpoint(islAlphaBeta.getSource())), eq(0L), eq(islAlphaBeta), anyLong()); verify(carrier).discoveryReceived(eq(new Endpoint(islBetaAlpha.getSource())), eq(2L), eq(islBetaAlpha), anyLong()); verify(carrier, times(2)).discoveryReceived(any(Endpoint.class), anyLong(), any(IslInfoData.class), anyLong()); assertThat(w.getTimeouts().size(), is(0)); }
### Question: NetworkDecisionMakerService { public void discovered(Endpoint endpoint, long packetId, IslInfoData discoveryEvent) { discovered(endpoint, packetId, discoveryEvent, now()); } NetworkDecisionMakerService(IDecisionMakerCarrier carrier, long failTimeout, long awaitTime); void discovered(Endpoint endpoint, long packetId, IslInfoData discoveryEvent); void failed(Endpoint endpoint, long packetId); void tick(); void clear(Endpoint endpoint); }### Answer: @Test public void discovered() { NetworkDecisionMakerService w = new NetworkDecisionMakerService(carrier, 10, 5); w.discovered(endpointBeta, 1L, islAlphaBeta, 1L); w.discovered(endpointAlpha, 2L, islBetaAlpha, 2L); verify(carrier).linkDiscovered(eq(islAlphaBeta)); verify(carrier).linkDiscovered(eq(islBetaAlpha)); }
### Question: NetworkDecisionMakerService { public void failed(Endpoint endpoint, long packetId) { failed(endpoint, packetId, now()); } NetworkDecisionMakerService(IDecisionMakerCarrier carrier, long failTimeout, long awaitTime); void discovered(Endpoint endpoint, long packetId, IslInfoData discoveryEvent); void failed(Endpoint endpoint, long packetId); void tick(); void clear(Endpoint endpoint); }### Answer: @Test public void failed() { NetworkDecisionMakerService w = new NetworkDecisionMakerService(carrier, 10, 5); w.failed(endpointAlpha, 0L, 0); w.failed(endpointAlpha, 1L, 1); w.failed(endpointAlpha, 2L, 4); verify(carrier, never()).linkDestroyed(any(Endpoint.class)); w.failed(endpointAlpha, 3L, 5); verify(carrier).linkDestroyed(eq(endpointAlpha)); w.discovered(endpointAlpha, 4L, islBetaAlpha, 20); verify(carrier).linkDiscovered(islBetaAlpha); reset(carrier); w.failed(endpointAlpha, 5L, 21); w.failed(endpointAlpha, 6L, 23); w.failed(endpointAlpha, 7L, 24); verify(carrier, never()).linkDestroyed(any(Endpoint.class)); w.failed(endpointAlpha, 8L, 31); verify(carrier).linkDestroyed(eq(endpointAlpha)); }
### Question: SwitchId implements Comparable<SwitchId>, Serializable { @VisibleForTesting String colonSeparatedBytes(char[] hex, int offset) { if (offset < 0 || offset % 2 != 0 || offset >= hex.length) { throw new IllegalArgumentException(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", offset)); } int length = hex.length - offset; length += length / 2 - 1; char[] buffer = new char[length]; int dst = 0; for (int src = offset; src < hex.length; src++) { if (offset < src && src % 2 == 0) { buffer[dst++] = ':'; } buffer[dst++] = hex[src]; } return new String(buffer); } SwitchId(long switchId); SwitchId(String switchId); long toLong(); String toMacAddress(); @JsonValue @Override String toString(); String toOtsdFormat(); @Override int compareTo(SwitchId other); }### Answer: @Test public void colonSeparatedBytesIllegalArgumentExceptionNegativeOffset() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", -1)); new SwitchId("00").colonSeparatedBytes(new char[]{'t', 'e', 's', 't'}, -1); } @Test public void colonSeparatedBytesIllegalArgumentExceptionOddOffset() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", 3)); new SwitchId("00").colonSeparatedBytes(new char[]{'t', 'e', 's', 't'}, 3); } @Test public void colonSeparatedBytesIllegalArgumentExceptionMoreThenHexLength() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", 6)); new SwitchId("00").colonSeparatedBytes(new char[]{'t', 'e', 's', 't'}, 6); }
### Question: Isl implements CompositeDataEntity<Isl.IslData> { public boolean isUnstable() { if (islConfig == null) { throw new IllegalStateException("IslConfig has not initialized."); } return getTimeUnstable() != null && getTimeUnstable().plus(islConfig.getUnstableIslTimeout()).isAfter(Instant.now()); } private Isl(); Isl(@NonNull Isl entityToClone); @Builder Isl(@NonNull Switch srcSwitch, @NonNull Switch destSwitch, int srcPort, int destPort, long latency, long speed, int cost, long maxBandwidth, long defaultMaxBandwidth, long availableBandwidth, IslStatus status, IslStatus actualStatus, IslStatus roundTripStatus, IslDownReason downReason, boolean underMaintenance, boolean enableBfd, BfdSessionStatus bfdSessionStatus, Instant timeUnstable); Isl(@NonNull IslData data); boolean isUnstable(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void shouldComputeIsUnstable() { Isl isl = Isl.builder() .srcSwitch(Switch.builder().switchId(new SwitchId(1)).build()) .destSwitch(Switch.builder().switchId(new SwitchId(2)).build()) .build(); isl.setIslConfig(islConfig); isl.setTimeUnstable(Instant.now().minus(islConfig.getUnstableIslTimeout())); assertFalse(isl.isUnstable()); isl.setTimeUnstable(Instant.now()); assertTrue(isl.isUnstable()); }
### Question: Meter implements Serializable { public static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient, String switchDescription) { return calculateBurstSize(bandwidth, flowMeterMinBurstSizeInKbits, flowMeterBurstCoefficient, switchDescription, switchDescription); } static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient, String switchDescription); static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient, String switchManufacturerDescription, String switchSoftwareDescription); static long calculateBurstSizeConsideringHardwareLimitations( long bandwidth, long requestedBurstSize, Set<SwitchFeature> features); static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes); static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes); static String[] getMeterKbpsFlags(); static String[] getMeterPktpsFlags(); static boolean equalsRate(long actual, long expected, boolean isESwitch); static boolean equalsBurstSize(long actual, long expected, boolean isESwitch); static final int MIN_RATE_IN_KBPS; }### Answer: @Test public void calculateBurstSize() { assertEquals(1024, Meter.calculateBurstSize(512L, 1024L, 1.0, "centec")); assertEquals(32000, Meter.calculateBurstSize(32333L, 1024L, 1.0, "centec")); assertEquals(10030, Meter.calculateBurstSize(10000L, 1024L, 1.003, "centec")); assertEquals(1105500, Meter.calculateBurstSize(1100000L, 1024L, 1.005, "NW000.0.0")); assertEquals(1105500, Meter.calculateBurstSize(1100000L, 1024L, 1.05, "NW000.0.0")); }
### Question: Meter implements Serializable { public static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes) { return Math.max(MIN_RATE_IN_KBPS, (rateInPackets * packetSizeInBytes * 8) / 1024L); } static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient, String switchDescription); static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient, String switchManufacturerDescription, String switchSoftwareDescription); static long calculateBurstSizeConsideringHardwareLimitations( long bandwidth, long requestedBurstSize, Set<SwitchFeature> features); static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes); static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes); static String[] getMeterKbpsFlags(); static String[] getMeterPktpsFlags(); static boolean equalsRate(long actual, long expected, boolean isESwitch); static boolean equalsBurstSize(long actual, long expected, boolean isESwitch); static final int MIN_RATE_IN_KBPS; }### Answer: @Test public void convertRateToKiloBitsTest() { assertEquals(800, Meter.convertRateToKiloBits(100, 1024)); assertEquals(64, Meter.convertRateToKiloBits(1, 1)); assertEquals(64, Meter.convertRateToKiloBits(8, 16)); }
### Question: Meter implements Serializable { public static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes) { return (burstSizeInPackets * packetSizeInBytes * 8) / 1024L; } static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient, String switchDescription); static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient, String switchManufacturerDescription, String switchSoftwareDescription); static long calculateBurstSizeConsideringHardwareLimitations( long bandwidth, long requestedBurstSize, Set<SwitchFeature> features); static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes); static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes); static String[] getMeterKbpsFlags(); static String[] getMeterPktpsFlags(); static boolean equalsRate(long actual, long expected, boolean isESwitch); static boolean equalsBurstSize(long actual, long expected, boolean isESwitch); static final int MIN_RATE_IN_KBPS; }### Answer: @Test public void convertBurstSizeToKiloBitsTest() { assertEquals(800, Meter.convertBurstSizeToKiloBits(100, 1024)); assertEquals(1, Meter.convertBurstSizeToKiloBits(8, 16)); }
### Question: Meter implements Serializable { public static long calculateBurstSizeConsideringHardwareLimitations( long bandwidth, long requestedBurstSize, Set<SwitchFeature> features) { if (features.contains(SwitchFeature.MAX_BURST_COEFFICIENT_LIMITATION)) { return Math.min(requestedBurstSize, Math.round(bandwidth * MAX_NOVIFLOW_BURST_COEFFICIENT)); } return requestedBurstSize; } static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient, String switchDescription); static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient, String switchManufacturerDescription, String switchSoftwareDescription); static long calculateBurstSizeConsideringHardwareLimitations( long bandwidth, long requestedBurstSize, Set<SwitchFeature> features); static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes); static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes); static String[] getMeterKbpsFlags(); static String[] getMeterPktpsFlags(); static boolean equalsRate(long actual, long expected, boolean isESwitch); static boolean equalsBurstSize(long actual, long expected, boolean isESwitch); static final int MIN_RATE_IN_KBPS; }### Answer: @Test public void convertCalculateBurstSizeConsideringHardwareLimitations() { Set<SwitchFeature> limitationFeature = newHashSet(MAX_BURST_COEFFICIENT_LIMITATION); assertEquals(4096, Meter.calculateBurstSizeConsideringHardwareLimitations(1, 4096, newHashSet())); assertEquals(1, Meter.calculateBurstSizeConsideringHardwareLimitations(1, 4096, limitationFeature)); assertEquals(100, Meter.calculateBurstSizeConsideringHardwareLimitations(100, 100, limitationFeature)); assertEquals(10, Meter.calculateBurstSizeConsideringHardwareLimitations(100, 10, limitationFeature)); }
### Question: FlowSegmentCookie extends Cookie { @Override public FlowSegmentCookieBuilder toBuilder() { return new FlowSegmentCookieBuilder() .type(getType()) .direction(getDirection()) .flowEffectiveId(getFlowEffectiveId()); } @JsonCreator FlowSegmentCookie(long value); FlowSegmentCookie(FlowPathDirection direction, long flowEffectiveId); FlowSegmentCookie(CookieType type, long value); @Builder private FlowSegmentCookie(CookieType type, FlowPathDirection direction, long flowEffectiveId); @Override void validate(); @Override FlowSegmentCookieBuilder toBuilder(); FlowPathDirection getValidatedDirection(); FlowPathDirection getDirection(); long getFlowEffectiveId(); static FlowSegmentCookieBuilder builder(); }### Answer: @Test public void changingOfFlowSegmentCookieTypeTest() { FlowSegmentCookie flowCookie = new FlowSegmentCookie(FlowPathDirection.FORWARD, 10); Assert.assertEquals(CookieType.SERVICE_OR_FLOW_SEGMENT, flowCookie.getType()); FlowSegmentCookie server42Cookie = flowCookie.toBuilder() .type(CookieType.SERVER_42_INGRESS) .build(); Assert.assertEquals(CookieType.SERVER_42_INGRESS, server42Cookie.getType()); }
### Question: LinkOperationsService { public List<Isl> updateLinkUnderMaintenanceFlag(SwitchId srcSwitchId, Integer srcPort, SwitchId dstSwitchId, Integer dstPort, boolean underMaintenance) throws IslNotFoundException { return transactionManager.doInTransaction(() -> { Optional<Isl> foundIsl = islRepository.findByEndpoints(srcSwitchId, srcPort, dstSwitchId, dstPort); Optional<Isl> foundReverceIsl = islRepository.findByEndpoints(dstSwitchId, dstPort, srcSwitchId, srcPort); if (!(foundIsl.isPresent() && foundReverceIsl.isPresent())) { return Optional.<List<Isl>>empty(); } Isl isl = foundIsl.get(); Isl reverceIsl = foundReverceIsl.get(); if (isl.isUnderMaintenance() == underMaintenance) { return Optional.of(Arrays.asList(isl, reverceIsl)); } isl.setUnderMaintenance(underMaintenance); reverceIsl.setUnderMaintenance(underMaintenance); return Optional.of(Arrays.asList(isl, reverceIsl)); }).orElseThrow(() -> new IslNotFoundException(srcSwitchId, srcPort, dstSwitchId, dstPort)); } LinkOperationsService(ILinkOperationsServiceCarrier carrier, RepositoryFactory repositoryFactory, TransactionManager transactionManager); List<Isl> updateLinkUnderMaintenanceFlag(SwitchId srcSwitchId, Integer srcPort, SwitchId dstSwitchId, Integer dstPort, boolean underMaintenance); Collection<Isl> getAllIsls(SwitchId srcSwitch, Integer srcPort, SwitchId dstSwitch, Integer dstPort); Collection<Isl> deleteIsl(SwitchId sourceSwitch, int sourcePort, SwitchId destinationSwitch, int destinationPort, boolean force); Collection<Isl> updateEnableBfdFlag(Endpoint source, Endpoint destination, boolean flagValue); }### Answer: @Test public void shouldUpdateLinkUnderMaintenanceFlag() throws IslNotFoundException { createIsl(IslStatus.ACTIVE); for (int i = 0; i < 2; i++) { List<Isl> link = linkOperationsService .updateLinkUnderMaintenanceFlag(TEST_SWITCH_A_ID, TEST_SWITCH_A_PORT, TEST_SWITCH_B_ID, TEST_SWITCH_B_PORT, true); assertEquals(2, link.size()); assertTrue(link.get(0).isUnderMaintenance()); assertTrue(link.get(1).isUnderMaintenance()); } for (int i = 0; i < 2; i++) { List<Isl> link = linkOperationsService .updateLinkUnderMaintenanceFlag(TEST_SWITCH_A_ID, TEST_SWITCH_A_PORT, TEST_SWITCH_B_ID, TEST_SWITCH_B_PORT, false); assertEquals(2, link.size()); assertFalse(link.get(0).isUnderMaintenance()); assertFalse(link.get(1).isUnderMaintenance()); } }
### Question: PathSegment implements CompositeDataEntity<PathSegment.PathSegmentData> { public boolean containsNode(SwitchId switchId, int port) { if (switchId == null) { throw new IllegalArgumentException("Switch id must be not null"); } return (switchId.equals(getSrcSwitchId()) && port == getSrcPort()) || (switchId.equals(getDestSwitchId()) && port == getDestPort()); } private PathSegment(); PathSegment(@NonNull PathSegment entityToClone, FlowPath path); @Builder PathSegment(@NonNull Switch srcSwitch, @NonNull Switch destSwitch, int srcPort, int destPort, boolean srcWithMultiTable, boolean destWithMultiTable, int seqId, Long latency, long bandwidth, boolean ignoreBandwidth, boolean failed); PathSegment(@NonNull PathSegmentData data); boolean containsNode(SwitchId switchId, int port); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test(expected = IllegalArgumentException.class) public void testContainsNodeInvalidInput() { flow.getForwardPath().getSegments().get(0).containsNode(null, 1); } @Test public void testContainsNodeSourceMatch() { assertTrue(flow.getForwardPath().getSegments().get(0).containsNode(SWITCH_ID_A, 1)); } @Test public void testContainsNodeDestinationMatch() { assertTrue(flow.getForwardPath().getSegments().get(0).containsNode(SWITCH_ID_B, 1)); } @Test public void testContainsNodeNoSwitchMatch() { assertFalse(flow.getForwardPath().getSegments().get(0).containsNode(SWITCH_ID_C, 1)); } @Test public void testContainsNodeNoPortMatch() { assertFalse(flow.getForwardPath().getSegments().get(0).containsNode(SWITCH_ID_B, 2)); } @Test public void testContainsNodeNoSwitchPortMatch() { assertFalse(flow.getForwardPath().getSegments().get(0).containsNode(SWITCH_ID_C, 2)); }
### Question: MeterId implements Comparable<MeterId>, Serializable { public static MeterId createMeterIdForDefaultRule(long cookie) { if (!Cookie.isDefaultRule(cookie)) { throw new IllegalArgumentException(String.format("Cookie '%s' is not a cookie of default rule", cookie)); } return new MeterId((int) (cookie & METER_ID_DEFAULT_RULE_MASK)); } @JsonCreator MeterId(long value); static boolean isMeterIdOfDefaultRule(long meterId); static MeterId createMeterIdForDefaultRule(long cookie); @JsonValue long getValue(); @Override int compareTo(MeterId compareWith); static final long METER_ID_DEFAULT_RULE_MASK; static final int MIN_FLOW_METER_ID; static final int MAX_FLOW_METER_ID; static final int MIN_SYSTEM_RULE_METER_ID; static final int MAX_SYSTEM_RULE_METER_ID; }### Answer: @Test(expected = IllegalArgumentException.class) public void createMeterIdForInvalidDefaultRuleTest() { MeterId.createMeterIdForDefaultRule(0x0000000000000123L); }
### Question: SwitchProperties implements CompositeDataEntity<SwitchProperties.SwitchPropertiesData> { @VisibleForTesting public boolean validateProp(SwitchFeature feature) { if (getSwitchObj() != null && !getSwitchObj().getFeatures().contains(feature)) { String message = String.format("Switch %s doesn't support requested feature %s", getSwitchId(), feature); throw new IllegalArgumentException(message); } return true; } private SwitchProperties(); SwitchProperties(@NonNull SwitchProperties entityToClone); @Builder SwitchProperties(Switch switchObj, Set<FlowEncapsulationType> supportedTransitEncapsulation, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt, Integer server42Port, MacAddress server42MacAddress, Integer server42Vlan, Integer inboundTelescopePort, Integer outboundTelescopePort, Integer telescopeIngressVlan, Integer telescopeEgressVlan); SwitchProperties(@NonNull SwitchPropertiesData data); void setMultiTable(boolean multiTable); void setSupportedTransitEncapsulation(Set<FlowEncapsulationType> supportedTransitEncapsulation); @VisibleForTesting boolean validateProp(SwitchFeature feature); @Override boolean equals(Object o); @Override int hashCode(); static Set<FlowEncapsulationType> DEFAULT_FLOW_ENCAPSULATION_TYPES; }### Answer: @Test(expected = IllegalArgumentException.class) public void validatePropRaiseTest() { Switch sw = Switch.builder() .switchId(new SwitchId(1)) .build(); SwitchProperties sp = SwitchProperties.builder() .switchObj(sw) .build(); sp.validateProp(SwitchFeature.BFD); } @Test public void validatePropPassesTest() { Set<SwitchFeature> features = new HashSet<>(); features.add(SwitchFeature.MULTI_TABLE); Switch sw = Switch.builder() .switchId(new SwitchId(1)) .features(features) .build(); SwitchProperties sp = SwitchProperties.builder() .switchObj(sw) .build(); assertTrue(sp.validateProp(SwitchFeature.MULTI_TABLE)); }
### Question: SwitchProperties implements CompositeDataEntity<SwitchProperties.SwitchPropertiesData> { public void setMultiTable(boolean multiTable) { if (multiTable) { validateProp(SwitchFeature.MULTI_TABLE); } data.setMultiTable(multiTable); } private SwitchProperties(); SwitchProperties(@NonNull SwitchProperties entityToClone); @Builder SwitchProperties(Switch switchObj, Set<FlowEncapsulationType> supportedTransitEncapsulation, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt, Integer server42Port, MacAddress server42MacAddress, Integer server42Vlan, Integer inboundTelescopePort, Integer outboundTelescopePort, Integer telescopeIngressVlan, Integer telescopeEgressVlan); SwitchProperties(@NonNull SwitchPropertiesData data); void setMultiTable(boolean multiTable); void setSupportedTransitEncapsulation(Set<FlowEncapsulationType> supportedTransitEncapsulation); @VisibleForTesting boolean validateProp(SwitchFeature feature); @Override boolean equals(Object o); @Override int hashCode(); static Set<FlowEncapsulationType> DEFAULT_FLOW_ENCAPSULATION_TYPES; }### Answer: @Test(expected = IllegalArgumentException.class) public void setUnsupportedMultiTableFlagTest() { Switch sw = Switch.builder() .switchId(new SwitchId(1)) .build(); SwitchProperties sp = SwitchProperties.builder() .switchObj(sw) .build(); sp.setMultiTable(true); }
### Question: SwitchProperties implements CompositeDataEntity<SwitchProperties.SwitchPropertiesData> { public void setSupportedTransitEncapsulation(Set<FlowEncapsulationType> supportedTransitEncapsulation) { if (supportedTransitEncapsulation != null && supportedTransitEncapsulation.contains(FlowEncapsulationType.VXLAN)) { validateProp(SwitchFeature.NOVIFLOW_COPY_FIELD); } data.setSupportedTransitEncapsulation(supportedTransitEncapsulation); } private SwitchProperties(); SwitchProperties(@NonNull SwitchProperties entityToClone); @Builder SwitchProperties(Switch switchObj, Set<FlowEncapsulationType> supportedTransitEncapsulation, boolean multiTable, boolean switchLldp, boolean switchArp, boolean server42FlowRtt, Integer server42Port, MacAddress server42MacAddress, Integer server42Vlan, Integer inboundTelescopePort, Integer outboundTelescopePort, Integer telescopeIngressVlan, Integer telescopeEgressVlan); SwitchProperties(@NonNull SwitchPropertiesData data); void setMultiTable(boolean multiTable); void setSupportedTransitEncapsulation(Set<FlowEncapsulationType> supportedTransitEncapsulation); @VisibleForTesting boolean validateProp(SwitchFeature feature); @Override boolean equals(Object o); @Override int hashCode(); static Set<FlowEncapsulationType> DEFAULT_FLOW_ENCAPSULATION_TYPES; }### Answer: @Test(expected = IllegalArgumentException.class) public void setUnsupportedTransitEncapsulationTest() { Switch sw = Switch.builder() .switchId(new SwitchId(1)) .build(); SwitchProperties sp = SwitchProperties.builder() .switchObj(sw) .build(); Set<FlowEncapsulationType> flowEncapsulationTypes = new HashSet<>(); flowEncapsulationTypes.add(FlowEncapsulationType.VXLAN); sp.setSupportedTransitEncapsulation(flowEncapsulationTypes); }
### Question: PathWeight implements Comparable<PathWeight> { public PathWeight add(PathWeight toAdd) { List<Long> result = new ArrayList<>(); Iterator<Long> firstIterator = params.iterator(); Iterator<Long> secondIterator = toAdd.params.iterator(); while (firstIterator.hasNext() || secondIterator.hasNext()) { long first = firstIterator.hasNext() ? firstIterator.next() : 0L; long second = secondIterator.hasNext() ? secondIterator.next() : 0L; result.add(first + second); } return new PathWeight(result); } PathWeight(long... params); PathWeight(List<Long> params); PathWeight add(PathWeight toAdd); long toLong(); @Override int compareTo(PathWeight o); }### Answer: @Test public void add() { PathWeight first = new PathWeight(2, 7); PathWeight second = new PathWeight(1, 2); PathWeight actual = first.add(second); assertEquals(0, actual.compareTo(new PathWeight(3, 9))); }
### Question: PathWeight implements Comparable<PathWeight> { @Override public int compareTo(PathWeight o) { int firstSize = params.size(); int secondSize = o.params.size(); int limit = Math.min(firstSize, secondSize); int i = 0; while (i < limit) { long first = params.get(i).longValue(); long second = o.params.get(i).longValue(); if (first != second) { return first > second ? 1 : -1; } i++; } if (firstSize == secondSize) { return 0; } else { return Integer.compare(firstSize, secondSize); } } PathWeight(long... params); PathWeight(List<Long> params); PathWeight add(PathWeight toAdd); long toLong(); @Override int compareTo(PathWeight o); }### Answer: @Test public void compareTo() { final PathWeight first = new PathWeight(2, 7); final PathWeight second = new PathWeight(5, 7); final PathWeight equalToSecond = new PathWeight(5, 7); final PathWeight third = new PathWeight(7); final PathWeight fourth = new PathWeight(7, 2); assertTrue(first.compareTo(second) < 0); assertTrue(second.compareTo(first) > 0); assertTrue(second.compareTo(equalToSecond) == 0); assertTrue(second.compareTo(third) < 0); assertTrue(third.compareTo(fourth) < 0); assertTrue(fourth.compareTo(third) > 0); }
### Question: PathComputerFactory { public PathComputer getPathComputer() { return new InMemoryPathComputer(availableNetworkFactory, new BestWeightAndShortestPathFinder(config.getMaxAllowedDepth()), config); } PathComputerFactory(PathComputerConfig config, AvailableNetworkFactory availableNetworkFactory); PathComputer getPathComputer(); }### Answer: @Test public void shouldCreateAnInstance() { PathComputerFactory factory = new PathComputerFactory( mock(PathComputerConfig.class), mock(AvailableNetworkFactory.class)); PathComputer pathComputer = factory.getPathComputer(); assertTrue(pathComputer instanceof InMemoryPathComputer); }
### Question: FlowStatusResponse extends InfoData { public FlowIdStatusPayload getPayload() { return payload; } @JsonCreator FlowStatusResponse(@JsonProperty(PAYLOAD) final FlowIdStatusPayload payload); FlowIdStatusPayload getPayload(); void setPayload(final FlowIdStatusPayload payload); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object object); }### Answer: @Test public void testJsonSerialization() throws IOException { InfoMessage msg = new InfoMessage(new FlowStatusResponse( new FlowIdStatusPayload("FLOW", FlowState.UP)), 10L, "CORRELATION", Destination.NORTHBOUND, null); InfoMessage fromJson = MAPPER.readValue(json, InfoMessage.class); FlowStatusResponse fsrJson = (FlowStatusResponse) fromJson.getData(); FlowStatusResponse fsrObj = (FlowStatusResponse) msg.getData(); Assert.assertEquals(fsrJson.getPayload().getId(), fsrObj.getPayload().getId()); Assert.assertEquals(fsrJson.getPayload().getStatus(), fsrObj.getPayload().getStatus()); Assert.assertEquals(fsrJson.getPayload().getStatus(), FlowState.UP); Assert.assertEquals(fromJson.getCorrelationId(), msg.getCorrelationId()); System.out.println("JSON: " + MAPPER.writeValueAsString(msg)); }
### Question: FlowValidator { @VisibleForTesting void checkForEqualsEndpoints(RequestedFlow firstFlow, RequestedFlow secondFlow) throws InvalidFlowException { String message = "New requested endpoint for '%s' conflicts with existing endpoint for '%s'"; Set<FlowEndpoint> firstFlowEndpoints = validateFlowEqualsEndpoints(firstFlow, message); Set<FlowEndpoint> secondFlowEndpoints = validateFlowEqualsEndpoints(secondFlow, message); for (FlowEndpoint endpoint : secondFlowEndpoints) { if (firstFlowEndpoints.contains(endpoint)) { message = String.format(message, secondFlow.getFlowId(), firstFlow.getFlowId()); throw new InvalidFlowException(message, ErrorType.DATA_INVALID); } } } FlowValidator(FlowRepository flowRepository, SwitchRepository switchRepository, IslRepository islRepository, SwitchPropertiesRepository switchPropertiesRepository); void validate(RequestedFlow flow); void validate(RequestedFlow flow, Set<String> bulkUpdateFlowIds); void validateForSwapEndpoints(RequestedFlow firstFlow, RequestedFlow secondFlow); }### Answer: @Test(expected = InvalidFlowException.class) public void shouldFailOnSwapWhenEqualsEndpointsOnFirstFlow() throws InvalidFlowException { RequestedFlow firstFlow = RequestedFlow.builder() .flowId("firstFlow") .srcSwitch(SWITCH_ID_1) .srcPort(10) .srcVlan(11) .destSwitch(SWITCH_ID_2) .destPort(10) .destVlan(11) .build(); RequestedFlow secondFlow = RequestedFlow.builder() .flowId("secondFlow") .srcSwitch(SWITCH_ID_2) .destSwitch(SWITCH_ID_2) .build(); flowValidator.checkForEqualsEndpoints(firstFlow, secondFlow); } @Test(expected = InvalidFlowException.class) public void shouldFailOnSwapWhenEqualsEndpointsOnSecondFlow() throws InvalidFlowException { RequestedFlow firstFlow = RequestedFlow.builder() .flowId("firstFlow") .srcSwitch(SWITCH_ID_2) .srcPort(10) .srcVlan(11) .destSwitch(SWITCH_ID_2) .destPort(12) .build(); RequestedFlow secondFlow = RequestedFlow.builder() .flowId("secondFlow") .srcSwitch(SWITCH_ID_1) .srcPort(10) .srcVlan(11) .destSwitch(SWITCH_ID_1) .destPort(10) .destVlan(11) .build(); flowValidator.checkForEqualsEndpoints(firstFlow, secondFlow); } @Test(expected = InvalidFlowException.class) public void shouldFailOnSwapWhenEqualsEndpointsOnFirstAndSecondFlow() throws InvalidFlowException { RequestedFlow firstFlow = RequestedFlow.builder() .flowId("firstFlow") .srcSwitch(SWITCH_ID_1) .srcPort(10) .srcVlan(11) .destSwitch(SWITCH_ID_2) .destPort(12) .destVlan(13) .build(); RequestedFlow secondFlow = RequestedFlow.builder() .flowId("secondFlow") .srcSwitch(SWITCH_ID_1) .srcPort(10) .srcVlan(11) .destSwitch(SWITCH_ID_2) .destPort(12) .destVlan(13) .build(); flowValidator.checkForEqualsEndpoints(firstFlow, secondFlow); } @Test public void shouldNotFailOnSwapWhenDifferentEndpointsOnFirstAndSecondFlow() throws InvalidFlowException { RequestedFlow firstFlow = RequestedFlow.builder() .flowId("firstFlow") .srcSwitch(SWITCH_ID_1) .srcPort(10) .srcVlan(11) .destSwitch(SWITCH_ID_2) .destPort(12) .destVlan(13) .build(); RequestedFlow secondFlow = RequestedFlow.builder() .flowId("secondFlow") .srcSwitch(SWITCH_ID_1) .srcPort(14) .srcVlan(15) .destSwitch(SWITCH_ID_2) .destPort(16) .destVlan(17) .build(); flowValidator.checkForEqualsEndpoints(firstFlow, secondFlow); }
### Question: BaseResourceAllocationAction extends NbTrackableAction<T, S, E, C> { @VisibleForTesting void updateAvailableBandwidth(SwitchId srcSwitch, int srcPort, SwitchId dstSwitch, int dstPort, long allowedOverprovisionedBandwidth, boolean forceToIgnoreBandwidth) throws ResourceAllocationException { long usedBandwidth = flowPathRepository.getUsedBandwidthBetweenEndpoints(srcSwitch, srcPort, dstSwitch, dstPort); log.debug("Updating ISL {}_{}-{}_{} with used bandwidth {}", srcSwitch, srcPort, dstSwitch, dstPort, usedBandwidth); long islAvailableBandwidth = islRepository.updateAvailableBandwidth(srcSwitch, srcPort, dstSwitch, dstPort, usedBandwidth); if (!forceToIgnoreBandwidth && (islAvailableBandwidth + allowedOverprovisionedBandwidth) < 0) { throw new ResourceAllocationException(format("ISL %s_%d-%s_%d was overprovisioned", srcSwitch, srcPort, dstSwitch, dstPort)); } } BaseResourceAllocationAction(PersistenceManager persistenceManager, int pathAllocationRetriesLimit, int pathAllocationRetryDelay, PathComputer pathComputer, FlowResourcesManager resourcesManager, FlowOperationsDashboardLogger dashboardLogger); }### Answer: @Test(expected = ResourceAllocationException.class) public void updateAvailableBandwidthFailsOnOverProvisionTest() throws ResourceAllocationException { when(persistenceManager.getRepositoryFactory()).thenReturn(repositoryFactory); when(repositoryFactory.createFlowPathRepository()).thenReturn(flowPathRepository); when(repositoryFactory.createIslRepository()).thenReturn(islRepository); when(flowPathRepository.getUsedBandwidthBetweenEndpoints(any(), eq(10), any(), eq(10))) .thenReturn(100L); when(islRepository.updateAvailableBandwidth(any(), eq(10), any(), eq(10), eq(100L))) .thenReturn(-1L); BaseResourceAllocationAction action = Mockito.mock(BaseResourceAllocationAction.class, Mockito.withSettings() .useConstructor(persistenceManager, 3, 3, pathComputer, resourcesManager, dashboardLogger) .defaultAnswer(Mockito.CALLS_REAL_METHODS)); action.updateAvailableBandwidth(new SwitchId(1000), 10, new SwitchId(1000), 10, 0L, false); } @Test() public void updateAvailableBandwidthIgnorsOverProvisionTest() throws ResourceAllocationException { when(persistenceManager.getRepositoryFactory()).thenReturn(repositoryFactory); when(repositoryFactory.createFlowPathRepository()).thenReturn(flowPathRepository); when(repositoryFactory.createIslRepository()).thenReturn(islRepository); when(flowPathRepository.getUsedBandwidthBetweenEndpoints(any(), eq(10), any(), eq(10))) .thenReturn(100L); when(islRepository.updateAvailableBandwidth(any(), eq(10), any(), eq(10), eq(100L))) .thenReturn(-1L); BaseResourceAllocationAction action = Mockito.mock(BaseResourceAllocationAction.class, Mockito.withSettings() .useConstructor(persistenceManager, 3, 3, pathComputer, resourcesManager, dashboardLogger) .defaultAnswer(Mockito.CALLS_REAL_METHODS)); action.updateAvailableBandwidth(new SwitchId(1000), 10, new SwitchId(1000), 10, 0L, true); }
### Question: NoviflowResponseMapper { public Boolean toBoolean(YesNo yesNo) { if (yesNo == null) { return null; } switch (yesNo) { case YES: return true; case NO: return false; default: return null; } } @Mapping(source = "logicalportno", target = "logicalPortNumber") @Mapping(source = "portnoList", target = "portNumbers") @Mapping(source = "logicalporttype", target = "type") abstract LogicalPort map(io.grpc.noviflow.LogicalPort port); @Mapping(source = "ethLinksList", target = "ethLinks") @Mapping(source = "buildsList", target = "builds") abstract SwitchInfoStatus map(StatusSwitch statusSwitch); @Mapping(source = "ipaddr", target = "ipAddress") abstract RemoteLogServer map(io.grpc.noviflow.RemoteLogServer remoteLogServer); abstract PacketInOutStatsDto map(PacketInOutStatsResponse stats); abstract PacketInOutStatsResponse map(PacketInOutStats stats); LogicalPortType map(io.grpc.noviflow.LogicalPortType type); io.grpc.noviflow.LogicalPortType map(LogicalPortType type); Boolean toBoolean(YesNo yesNo); }### Answer: @Test public void yesNoTest() { Assert.assertTrue(mapper.toBoolean(YesNo.YES)); Assert.assertFalse(mapper.toBoolean(YesNo.NO)); assertNull(mapper.toBoolean(null)); assertNull(mapper.toBoolean(YesNo.UNRECOGNIZED)); assertNull(mapper.toBoolean(YesNo.YESNO_RESERVED)); }
### Question: NoviflowResponseMapper { @Mapping(source = "logicalportno", target = "logicalPortNumber") @Mapping(source = "portnoList", target = "portNumbers") @Mapping(source = "logicalporttype", target = "type") public abstract LogicalPort map(io.grpc.noviflow.LogicalPort port); @Mapping(source = "logicalportno", target = "logicalPortNumber") @Mapping(source = "portnoList", target = "portNumbers") @Mapping(source = "logicalporttype", target = "type") abstract LogicalPort map(io.grpc.noviflow.LogicalPort port); @Mapping(source = "ethLinksList", target = "ethLinks") @Mapping(source = "buildsList", target = "builds") abstract SwitchInfoStatus map(StatusSwitch statusSwitch); @Mapping(source = "ipaddr", target = "ipAddress") abstract RemoteLogServer map(io.grpc.noviflow.RemoteLogServer remoteLogServer); abstract PacketInOutStatsDto map(PacketInOutStatsResponse stats); abstract PacketInOutStatsResponse map(PacketInOutStats stats); LogicalPortType map(io.grpc.noviflow.LogicalPortType type); io.grpc.noviflow.LogicalPortType map(LogicalPortType type); Boolean toBoolean(YesNo yesNo); }### Answer: @Test public void packetInOutTest() { PacketInOutStats stats = PacketInOutStats.newBuilder() .setPacketInTotalPackets(PACKET_IN_TOTAL_PACKETS) .setPacketInTotalPacketsDataplane(PACKET_IN_TOTAL_PACKETS_DATAPLANE) .setPacketInNoMatchPackets(PACKET_IN_NO_MATCH_PACKETS) .setPacketInApplyActionPackets(PACKET_IN_APPLY_ACTION_PACKETS) .setPacketInInvalidTtlPackets(PACKET_IN_INVALID_TTL_PACKETS) .setPacketInActionSetPackets(PACKET_IN_ACTION_SET_PACKETS) .setPacketInGroupPackets(PACKET_IN_GROUP_PACKETS) .setPacketInPacketOutPackets(PACKET_IN_PACKET_OUT_PACKETS) .setPacketOutTotalPacketsDataplane(PACKET_OUT_TOTAL_PACKETS_DATAPLANE) .setPacketOutTotalPacketsHost(PACKET_OUT_TOTAL_PACKETS_HOST) .setPacketOutEth0InterfaceUp(YesNo.YES) .setReplyStatus(REPLY_STATUS) .build(); PacketInOutStatsResponse response = mapper.map(stats); assertEquals(PACKET_IN_TOTAL_PACKETS, response.getPacketInTotalPackets()); assertEquals(PACKET_IN_TOTAL_PACKETS_DATAPLANE, response.getPacketInTotalPacketsDataplane()); assertEquals(PACKET_IN_NO_MATCH_PACKETS, response.getPacketInNoMatchPackets()); assertEquals(PACKET_IN_APPLY_ACTION_PACKETS, response.getPacketInApplyActionPackets()); assertEquals(PACKET_IN_INVALID_TTL_PACKETS, response.getPacketInInvalidTtlPackets()); assertEquals(PACKET_IN_ACTION_SET_PACKETS, response.getPacketInActionSetPackets()); assertEquals(PACKET_IN_GROUP_PACKETS, response.getPacketInGroupPackets()); assertEquals(PACKET_IN_PACKET_OUT_PACKETS, response.getPacketInPacketOutPackets()); assertEquals(PACKET_OUT_TOTAL_PACKETS_DATAPLANE, response.getPacketOutTotalPacketsDataplane()); assertEquals(PACKET_OUT_TOTAL_PACKETS_HOST, response.getPacketOutTotalPacketsHost()); assertEquals(Boolean.TRUE, response.getPacketOutEth0InterfaceUp()); assertEquals(REPLY_STATUS, response.getReplyStatus()); }
### Question: SpeakerFlowSegmentRequestBuilder implements FlowCommandBuilder { @Override public List<FlowSegmentRequestFactory> buildAllExceptIngress(CommandContext context, @NonNull Flow flow) { return buildAllExceptIngress(context, flow, flow.getForwardPath(), flow.getReversePath()); } SpeakerFlowSegmentRequestBuilder(FlowResourcesManager resourcesManager); @Override List<FlowSegmentRequestFactory> buildAll(CommandContext context, Flow flow, FlowPath path, SpeakerRequestBuildContext speakerRequestBuildContext); @Override List<FlowSegmentRequestFactory> buildAll(CommandContext context, Flow flow, FlowPath forwardPath, FlowPath reversePath, SpeakerRequestBuildContext speakerRequestBuildContext); @Override List<FlowSegmentRequestFactory> buildAllExceptIngress(CommandContext context, @NonNull Flow flow); @Override List<FlowSegmentRequestFactory> buildAllExceptIngress(CommandContext context, Flow flow, FlowPath path); @Override List<FlowSegmentRequestFactory> buildAllExceptIngress( CommandContext context, Flow flow, FlowPath path, FlowPath oppositePath); @Override List<FlowSegmentRequestFactory> buildIngressOnly( CommandContext context, @NonNull Flow flow, SpeakerRequestBuildContext speakerRequestBuildContext); @Override List<FlowSegmentRequestFactory> buildIngressOnly( CommandContext context, Flow flow, FlowPath path, FlowPath oppositePath, SpeakerRequestBuildContext speakerRequestBuildContext); @Override List<FlowSegmentRequestFactory> buildIngressOnlyOneDirection( CommandContext context, Flow flow, FlowPath path, FlowPath oppositePath, PathContext pathContext); @Override List<FlowSegmentRequestFactory> buildEgressOnly( CommandContext context, Flow flow, FlowPath path, FlowPath oppositePath); @Override List<FlowSegmentRequestFactory> buildEgressOnlyOneDirection( CommandContext context, Flow flow, FlowPath path, FlowPath oppositePath); }### Answer: @Test public void shouldCreateNonIngressRequestsWithoutVlans() { Switch srcSwitch = Switch.builder().switchId(SWITCH_1).build(); Switch destSwitch = Switch.builder().switchId(SWITCH_2).build(); Flow flow = buildFlow(srcSwitch, 1, 0, destSwitch, 2, 0, 0); setSegmentsWithoutTransitSwitches( Objects.requireNonNull(flow.getForwardPath()), Objects.requireNonNull(flow.getReversePath())); List<FlowSegmentRequestFactory> commands = target.buildAllExceptIngress(COMMAND_CONTEXT, flow); assertEquals(2, commands.size()); verifyForwardEgressRequest(flow, commands.get(0).makeInstallRequest(commandIdGenerator.generate())); verifyReverseEgressRequest(flow, commands.get(1).makeInstallRequest(commandIdGenerator.generate())); } @Test public void shouldCreateNonIngressCommandsWithTransitSwitch() { Switch srcSwitch = Switch.builder().switchId(SWITCH_1).build(); Switch destSwitch = Switch.builder().switchId(SWITCH_3).build(); Flow flow = buildFlow(srcSwitch, 1, 101, destSwitch, 2, 102, 0); setSegmentsWithTransitSwitches( Objects.requireNonNull(flow.getForwardPath()), Objects.requireNonNull(flow.getReversePath())); List<FlowSegmentRequestFactory> commands = target.buildAllExceptIngress(COMMAND_CONTEXT, flow); assertEquals(4, commands.size()); verifyForwardTransitRequest(flow, SWITCH_2, commands.get(0).makeInstallRequest(commandIdGenerator.generate())); verifyForwardEgressRequest(flow, commands.get(1).makeInstallRequest(commandIdGenerator.generate())); verifyReverseTransitRequest(flow, SWITCH_2, commands.get(2).makeInstallRequest(commandIdGenerator.generate())); verifyReverseEgressRequest(flow, commands.get(3).makeInstallRequest(commandIdGenerator.generate())); }
### Question: SpeakerFlowSegmentRequestBuilder implements FlowCommandBuilder { @Override public List<FlowSegmentRequestFactory> buildAll(CommandContext context, Flow flow, FlowPath path, SpeakerRequestBuildContext speakerRequestBuildContext) { return makeRequests(context, flow, path, null, true, true, true, speakerRequestBuildContext); } SpeakerFlowSegmentRequestBuilder(FlowResourcesManager resourcesManager); @Override List<FlowSegmentRequestFactory> buildAll(CommandContext context, Flow flow, FlowPath path, SpeakerRequestBuildContext speakerRequestBuildContext); @Override List<FlowSegmentRequestFactory> buildAll(CommandContext context, Flow flow, FlowPath forwardPath, FlowPath reversePath, SpeakerRequestBuildContext speakerRequestBuildContext); @Override List<FlowSegmentRequestFactory> buildAllExceptIngress(CommandContext context, @NonNull Flow flow); @Override List<FlowSegmentRequestFactory> buildAllExceptIngress(CommandContext context, Flow flow, FlowPath path); @Override List<FlowSegmentRequestFactory> buildAllExceptIngress( CommandContext context, Flow flow, FlowPath path, FlowPath oppositePath); @Override List<FlowSegmentRequestFactory> buildIngressOnly( CommandContext context, @NonNull Flow flow, SpeakerRequestBuildContext speakerRequestBuildContext); @Override List<FlowSegmentRequestFactory> buildIngressOnly( CommandContext context, Flow flow, FlowPath path, FlowPath oppositePath, SpeakerRequestBuildContext speakerRequestBuildContext); @Override List<FlowSegmentRequestFactory> buildIngressOnlyOneDirection( CommandContext context, Flow flow, FlowPath path, FlowPath oppositePath, PathContext pathContext); @Override List<FlowSegmentRequestFactory> buildEgressOnly( CommandContext context, Flow flow, FlowPath path, FlowPath oppositePath); @Override List<FlowSegmentRequestFactory> buildEgressOnlyOneDirection( CommandContext context, Flow flow, FlowPath path, FlowPath oppositePath); }### Answer: @Test public void shouldCreateOneSwitchFlow() { Switch sw = Switch.builder().switchId(SWITCH_1).build(); Flow flow = buildFlow(sw, 1, 10, sw, 2, 12, 1000); List<FlowSegmentRequestFactory> commands = target.buildAll( COMMAND_CONTEXT, flow, flow.getForwardPath(), flow.getReversePath(), SpeakerRequestBuildContext.EMPTY); assertEquals(2, commands.size()); verifyForwardOneSwitchRequest(flow, commands.get(0).makeInstallRequest(commandIdGenerator.generate())); verifyReverseOneSwitchRequest(flow, commands.get(1).makeInstallRequest(commandIdGenerator.generate())); }
### Question: SpeakerFlowSegmentRequestBuilder implements FlowCommandBuilder { @Override public List<FlowSegmentRequestFactory> buildIngressOnly( CommandContext context, @NonNull Flow flow, SpeakerRequestBuildContext speakerRequestBuildContext) { return buildIngressOnly(context, flow, flow.getForwardPath(), flow.getReversePath(), speakerRequestBuildContext); } SpeakerFlowSegmentRequestBuilder(FlowResourcesManager resourcesManager); @Override List<FlowSegmentRequestFactory> buildAll(CommandContext context, Flow flow, FlowPath path, SpeakerRequestBuildContext speakerRequestBuildContext); @Override List<FlowSegmentRequestFactory> buildAll(CommandContext context, Flow flow, FlowPath forwardPath, FlowPath reversePath, SpeakerRequestBuildContext speakerRequestBuildContext); @Override List<FlowSegmentRequestFactory> buildAllExceptIngress(CommandContext context, @NonNull Flow flow); @Override List<FlowSegmentRequestFactory> buildAllExceptIngress(CommandContext context, Flow flow, FlowPath path); @Override List<FlowSegmentRequestFactory> buildAllExceptIngress( CommandContext context, Flow flow, FlowPath path, FlowPath oppositePath); @Override List<FlowSegmentRequestFactory> buildIngressOnly( CommandContext context, @NonNull Flow flow, SpeakerRequestBuildContext speakerRequestBuildContext); @Override List<FlowSegmentRequestFactory> buildIngressOnly( CommandContext context, Flow flow, FlowPath path, FlowPath oppositePath, SpeakerRequestBuildContext speakerRequestBuildContext); @Override List<FlowSegmentRequestFactory> buildIngressOnlyOneDirection( CommandContext context, Flow flow, FlowPath path, FlowPath oppositePath, PathContext pathContext); @Override List<FlowSegmentRequestFactory> buildEgressOnly( CommandContext context, Flow flow, FlowPath path, FlowPath oppositePath); @Override List<FlowSegmentRequestFactory> buildEgressOnlyOneDirection( CommandContext context, Flow flow, FlowPath path, FlowPath oppositePath); }### Answer: @Test public void useActualFlowEndpoint() { Switch srcSwitch = Switch.builder().switchId(SWITCH_1).build(); Switch destSwitch = Switch.builder().switchId(SWITCH_2).build(); Flow origin = buildFlow(srcSwitch, 1, 5, destSwitch, 2, 0, 0); setSegmentsWithoutTransitSwitches( Objects.requireNonNull(origin.getForwardPath()), Objects.requireNonNull(origin.getReversePath())); FlowPath goalForwardPath = buildFlowPath( origin, origin.getSrcSwitch(), origin.getDestSwitch(), new FlowSegmentCookie( FlowPathDirection.FORWARD, cookieFactory.next())); FlowPath goalReversePath = buildFlowPath( origin, origin.getDestSwitch(), origin.getSrcSwitch(), new FlowSegmentCookie( FlowPathDirection.REVERSE, cookieFactory.next())); setSegmentsWithTransitSwitches(goalForwardPath, goalReversePath); Flow goal = Flow.builder() .flowId(origin.getFlowId()) .srcSwitch(origin.getSrcSwitch()) .srcPort(origin.getSrcPort()) .srcVlan(origin.getSrcVlan() + 10) .destSwitch(origin.getDestSwitch()) .destPort(origin.getDestPort()) .destVlan(origin.getDestVlan()) .bandwidth(origin.getBandwidth()) .encapsulationType(origin.getEncapsulationType()) .build(); goal.setForwardPath(origin.getForwardPath()); goal.setReversePath(origin.getReversePath()); goal.addPaths(goalForwardPath, goalReversePath); List<FlowSegmentRequestFactory> commands = target.buildIngressOnly( COMMAND_CONTEXT, goal, goalForwardPath, goalReversePath, SpeakerRequestBuildContext.EMPTY); boolean haveMatch = false; for (FlowSegmentRequestFactory entry : commands) { if (SWITCH_1.equals(entry.getSwitchId())) { haveMatch = true; Assert.assertTrue(entry instanceof IngressFlowSegmentRequestFactory); IngressFlowSegmentRequestFactory segment = (IngressFlowSegmentRequestFactory) entry; IngressFlowSegmentRequest request = segment.makeInstallRequest(commandIdGenerator.generate()); Assert.assertEquals(goal.getSrcVlan(), request.getEndpoint().getOuterVlanId()); } } Assert.assertTrue(haveMatch); }
### Question: IntersectionComputer { public static boolean isProtectedPathOverlaps( List<PathSegment> primaryFlowSegments, List<PathSegment> protectedFlowSegments) { Set<Edge> primaryEdges = primaryFlowSegments.stream().map(Edge::fromPathSegment).collect(Collectors.toSet()); Set<Edge> protectedEdges = protectedFlowSegments.stream().map(Edge::fromPathSegment) .collect(Collectors.toSet()); return !Sets.intersection(primaryEdges, protectedEdges).isEmpty(); } IntersectionComputer(String targetFlowId, PathId targetForwardPathId, PathId targetReversePathId, Collection<FlowPath> paths); OverlappingSegmentsStats getOverlappingStats(); OverlappingSegmentsStats getOverlappingStats(PathId forwardPathId, PathId reversePathId); static boolean isProtectedPathOverlaps( List<PathSegment> primaryFlowSegments, List<PathSegment> protectedFlowSegments); }### Answer: @Test public void isProtectedPathOverlapsPositive() { List<FlowPath> paths = getFlowPaths(PATH_ID, PATH_ID_REVERSE, flow); List<PathSegment> primarySegments = getFlowPathSegments(paths); List<PathSegment> protectedSegmets = Collections.singletonList( buildPathSegment(SWITCH_ID_A, SWITCH_ID_B, 1, 1)); assertTrue(IntersectionComputer.isProtectedPathOverlaps(primarySegments, protectedSegmets)); } @Test public void isProtectedPathOverlapsNegative() { List<FlowPath> paths = getFlowPaths(PATH_ID, PATH_ID_REVERSE, flow); List<PathSegment> primarySegments = getFlowPathSegments(paths); List<PathSegment> protectedSegmets = Collections.singletonList( buildPathSegment(SWITCH_ID_A, SWITCH_ID_C, 3, 3)); assertFalse(IntersectionComputer.isProtectedPathOverlaps(primarySegments, protectedSegmets)); }
### Question: IslMapper { public IslInfoData map(Isl isl) { if (isl == null) { return null; } PathNode src = new PathNode(); src.setSwitchId(isl.getSrcSwitchId()); src.setPortNo(isl.getSrcPort()); src.setSegLatency(isl.getLatency()); src.setSeqId(0); PathNode dst = new PathNode(); dst.setSwitchId(isl.getDestSwitchId()); dst.setPortNo(isl.getDestPort()); dst.setSegLatency(isl.getLatency()); dst.setSeqId(1); Long timeCreateMillis = Optional.ofNullable(isl.getTimeCreate()).map(Instant::toEpochMilli).orElse(null); Long timeModifyMillis = Optional.ofNullable(isl.getTimeModify()).map(Instant::toEpochMilli).orElse(null); return new IslInfoData(isl.getLatency(), src, dst, isl.getSpeed(), isl.getAvailableBandwidth(), isl.getMaxBandwidth(), isl.getDefaultMaxBandwidth(), map(isl.getStatus()), map(isl.getActualStatus()), isl.getCost(), timeCreateMillis, timeModifyMillis, isl.isUnderMaintenance(), isl.isEnableBfd(), map(isl.getBfdSessionStatus()), null); } IslInfoData map(Isl isl); org.openkilda.model.Isl map(IslInfoData islInfoData); IslChangeType map(IslStatus status); IslStatus map(IslChangeType status); BfdSessionStatus map(String raw); String map(BfdSessionStatus status); static final IslMapper INSTANCE; }### Answer: @Test public void islMapperTest() { IslInfoData islInfoData = IslInfoData.builder() .latency(1L) .source(new PathNode(TEST_SWITCH_A_ID, 1, 0)) .destination(new PathNode(TEST_SWITCH_B_ID, 1, 1)) .speed(2L) .state(IslChangeType.DISCOVERED) .cost(700) .availableBandwidth(4L) .underMaintenance(false) .build(); Isl isl = IslMapper.INSTANCE.map(islInfoData); Assert.assertEquals(IslStatus.ACTIVE, isl.getStatus()); IslInfoData islInfoDataMapping = IslMapper.INSTANCE.map(isl); islInfoDataMapping.setState(IslChangeType.DISCOVERED); Assert.assertEquals(islInfoData, islInfoDataMapping); }
### Question: PortMapper { @Mapping(source = "state", target = "status") public abstract Port map(PortInfoData portInfoData); @Mapping(source = "state", target = "status") abstract Port map(PortInfoData portInfoData); @Mapping(target = "timestamp", ignore = true) @Mapping(target = "maxCapacity", ignore = true) @Mapping(target = "state", ignore = true) @Mapping(target = "enabled", ignore = true) abstract PortInfoData map(Port port); PortStatus map(PortChangeType portChangeType); @Mapping(source = "switchObj.switchId", target = "switchId") @Mapping(source = "port", target = "portNumber") @Mapping(target = "timestamp", ignore = true) abstract PortPropertiesPayload map(PortProperties portProperties); static final PortMapper INSTANCE; }### Answer: @Test public void portMapperTest() { PortMapper portMapper = Mappers.getMapper(PortMapper.class); PortInfoData portInfoData = new PortInfoData(TEST_SWITCH_ID, 1, PortChangeType.UP); Port port = portMapper.map(portInfoData); Assert.assertEquals(PortStatus.UP, port.getStatus()); PortInfoData portInfoDataMapping = portMapper.map(port); Assert.assertEquals(TEST_SWITCH_ID, portInfoDataMapping.getSwitchId()); Assert.assertEquals(1, portInfoDataMapping.getPortNo()); }
### Question: SimpleSwitchRuleConverter { public List<SimpleSwitchRule> convertFlowPathToSimpleSwitchRules(Flow flow, FlowPath flowPath, EncapsulationId encapsulationId, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient) { List<SimpleSwitchRule> rules = new ArrayList<>(); if (!flowPath.isProtected()) { rules.add(buildIngressSimpleSwitchRule(flow, flowPath, encapsulationId, flowMeterMinBurstSizeInKbits, flowMeterBurstCoefficient)); } if (! flow.isOneSwitchFlow()) { rules.addAll(buildTransitAndEgressSimpleSwitchRules(flow, flowPath, encapsulationId)); } return rules; } List<SimpleSwitchRule> convertFlowPathToSimpleSwitchRules(Flow flow, FlowPath flowPath, EncapsulationId encapsulationId, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient); List<SimpleSwitchRule> convertSwitchFlowEntriesToSimpleSwitchRules(SwitchFlowEntries rules, SwitchMeterEntries meters); }### Answer: @Test public void shouldConvertFlowPathWithTransitVlanEncapToSimpleSwitchRules() { Flow flow = buildFlow(FlowEncapsulationType.TRANSIT_VLAN); List<SimpleSwitchRule> expectedSwitchRules = getSimpleSwitchRuleForTransitVlan(); List<SimpleSwitchRule> switchRules = simpleSwitchRuleConverter.convertFlowPathToSimpleSwitchRules(flow, flow.getForwardPath(), TransitVlan.builder() .flowId(TEST_FLOW_ID_A) .pathId(FLOW_A_FORWARD_PATH_ID) .vlan(FLOW_A_ENCAP_ID) .build(), MIN_BURST_SIZE_IN_KBITS, BURST_COEFFICIENT); assertEquals(expectedSwitchRules, switchRules); } @Test public void convertFlowWithIngressVlanIdMatchesTransitVlanId() { Flow flow = buildFlow(FlowEncapsulationType.TRANSIT_VLAN); Assert.assertNotEquals(0, flow.getSrcVlan()); Assert.assertNotNull(flow.getForwardPath()); TransitVlan encapsulation = TransitVlan.builder() .flowId(flow.getFlowId()) .pathId(flow.getForwardPathId()) .vlan(flow.getSrcVlan()) .build(); List<SimpleSwitchRule> pathView = simpleSwitchRuleConverter.convertFlowPathToSimpleSwitchRules( flow, flow.getForwardPath(), encapsulation, MIN_BURST_SIZE_IN_KBITS, BURST_COEFFICIENT); Assert.assertFalse(pathView.isEmpty()); SimpleSwitchRule ingress = pathView.get(0); Assert.assertEquals(Collections.emptyList(), ingress.getOutVlan()); } @Test public void shouldConvertFlowPathWithVxlanEncapToSimpleSwitchRules() { Flow flow = buildFlow(FlowEncapsulationType.VXLAN); List<SimpleSwitchRule> expectedSwitchRules = getSimpleSwitchRuleForVxlan(); List<SimpleSwitchRule> switchRules = simpleSwitchRuleConverter.convertFlowPathToSimpleSwitchRules(flow, flow.getForwardPath(), Vxlan.builder() .flowId(TEST_FLOW_ID_A) .pathId(FLOW_A_FORWARD_PATH_ID) .vni(FLOW_A_ENCAP_ID) .build(), MIN_BURST_SIZE_IN_KBITS, BURST_COEFFICIENT); assertEquals(expectedSwitchRules, switchRules); } @Test public void shouldConvertFlowPathOneSwitchFlowToSimpleSwitchRules() { Flow flow = buildOneSwitchPortFlow(); List<SimpleSwitchRule> expectedSwitchRules = getSimpleSwitchRuleForOneSwitchFlow(); List<SimpleSwitchRule> switchRules = simpleSwitchRuleConverter.convertFlowPathToSimpleSwitchRules(flow, flow.getForwardPath(), null, MIN_BURST_SIZE_IN_KBITS, BURST_COEFFICIENT); assertEquals(expectedSwitchRules, switchRules); }
### Question: SimpleSwitchRuleConverter { public List<SimpleSwitchRule> convertSwitchFlowEntriesToSimpleSwitchRules(SwitchFlowEntries rules, SwitchMeterEntries meters) { if (rules == null || rules.getFlowEntries() == null) { return Collections.emptyList(); } List<SimpleSwitchRule> simpleRules = new ArrayList<>(); for (FlowEntry flowEntry : rules.getFlowEntries()) { simpleRules.add(buildSimpleSwitchRule(rules.getSwitchId(), flowEntry, meters)); } return simpleRules; } List<SimpleSwitchRule> convertFlowPathToSimpleSwitchRules(Flow flow, FlowPath flowPath, EncapsulationId encapsulationId, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient); List<SimpleSwitchRule> convertSwitchFlowEntriesToSimpleSwitchRules(SwitchFlowEntries rules, SwitchMeterEntries meters); }### Answer: @Test public void shouldConvertFlowEntriesTransitVlanFlowToSimpleSwitchRules() { List<SimpleSwitchRule> expectedSwitchRules = getSimpleSwitchRuleForTransitVlan(); List<SwitchFlowEntries> switchFlowEntries = getSwitchFlowEntriesWithTransitVlan(); List<SwitchMeterEntries> switchMeterEntries = getSwitchMeterEntries(); for (int i = 0; i < switchFlowEntries.size(); i++) { List<SimpleSwitchRule> switchRules = simpleSwitchRuleConverter.convertSwitchFlowEntriesToSimpleSwitchRules(switchFlowEntries.get(i), switchMeterEntries.get(i)); assertThat(switchRules, hasSize(1)); assertEquals(expectedSwitchRules.get(i), switchRules.get(0)); } } @Test public void shouldConvertFlowEntriesVxlanFlowToSimpleSwitchRules() { List<SimpleSwitchRule> expectedSwitchRules = getSimpleSwitchRuleForVxlan(); List<SwitchFlowEntries> switchFlowEntries = getSwitchFlowEntriesWithVxlan(); List<SwitchMeterEntries> switchMeterEntries = getSwitchMeterEntries(); for (int i = 0; i < switchFlowEntries.size(); i++) { List<SimpleSwitchRule> switchRules = simpleSwitchRuleConverter.convertSwitchFlowEntriesToSimpleSwitchRules(switchFlowEntries.get(i), switchMeterEntries.get(i)); assertThat(switchRules, hasSize(1)); assertEquals(expectedSwitchRules.get(i), switchRules.get(0)); } } @Test public void shouldConvertFlowEntriesOneSwitchFlowToSimpleSwitchRules() { List<SimpleSwitchRule> expectedSwitchRules = getSimpleSwitchRuleForOneSwitchFlow(); List<SwitchFlowEntries> switchFlowEntries = getSwitchFlowEntriesOneSwitchFlow(); List<SimpleSwitchRule> switchRules = simpleSwitchRuleConverter.convertSwitchFlowEntriesToSimpleSwitchRules(switchFlowEntries.get(0), getSwitchMeterEntriesOneSwitchFlow()); assertEquals(expectedSwitchRules, switchRules); }
### Question: CookiePool { public CookiePool(PersistenceManager persistenceManager, long minCookie, long maxCookie, int poolSize) { transactionManager = persistenceManager.getTransactionManager(); RepositoryFactory repositoryFactory = persistenceManager.getRepositoryFactory(); flowCookieRepository = repositoryFactory.createFlowCookieRepository(); this.minCookie = minCookie; this.maxCookie = maxCookie; this.poolSize = poolSize; } CookiePool(PersistenceManager persistenceManager, long minCookie, long maxCookie, int poolSize); @TransactionRequired long allocate(String flowId); void deallocate(long unmaskedCookie); }### Answer: @Test public void cookiePool() { transactionManager.doInTransaction(() -> { Set<Long> cookies = new HashSet<>(); for (long i = MIN_COOKIE; i <= MAX_COOKIE; i++) { cookies.add(cookiePool.allocate(format("flow_%d", i))); } assertEquals(MAX_COOKIE - MIN_COOKIE + 1, cookies.size()); cookies.forEach(cookie -> assertTrue(cookie >= MIN_COOKIE && cookie <= MAX_COOKIE)); }); }
### Question: CookiePool { @TransactionRequired public long allocate(String flowId) { if (nextCookie > 0) { if (nextCookie <= maxCookie && !flowCookieRepository.exists(nextCookie)) { addCookie(flowId, nextCookie); return nextCookie++; } else { nextCookie = 0; } } if (nextCookie == 0) { long numOfPools = (maxCookie - minCookie) / poolSize; if (numOfPools > 1) { long poolToTake = Math.abs(new Random().nextInt()) % numOfPools; Optional<Long> availableCookie = flowCookieRepository.findFirstUnassignedCookie( minCookie + poolToTake * poolSize, minCookie + (poolToTake + 1) * poolSize - 1); if (availableCookie.isPresent()) { nextCookie = availableCookie.get(); addCookie(flowId, nextCookie); return nextCookie++; } } nextCookie = -1; } if (nextCookie == -1) { Optional<Long> availableCookie = flowCookieRepository.findFirstUnassignedCookie(minCookie, maxCookie); if (availableCookie.isPresent()) { nextCookie = availableCookie.get(); addCookie(flowId, nextCookie); return nextCookie++; } } throw new ResourceNotAvailableException("No cookie available"); } CookiePool(PersistenceManager persistenceManager, long minCookie, long maxCookie, int poolSize); @TransactionRequired long allocate(String flowId); void deallocate(long unmaskedCookie); }### Answer: @Test(expected = ResourceNotAvailableException.class) public void cookiePoolFullTest() { transactionManager.doInTransaction(() -> { for (long i = MIN_COOKIE; i <= MAX_COOKIE + 1; i++) { assertTrue(cookiePool.allocate(format("flow_%d", i)) > 0); } }); } @Test public void cookieLldp() { transactionManager.doInTransaction(() -> { String flowId = "flow_1"; long flowCookie = cookiePool.allocate(flowId); long lldpCookie = cookiePool.allocate(flowId); assertNotEquals(flowCookie, lldpCookie); }); }
### Question: FlowResourcesManager { public FlowResources allocateFlowResources(Flow flow) throws ResourceAllocationException { log.debug("Allocate flow resources for {}.", flow); PathId forwardPathId = generatePathId(flow.getFlowId()); PathId reversePathId = generatePathId(flow.getFlowId()); try { return allocateResources(flow, forwardPathId, reversePathId); } catch (ConstraintViolationException | ResourceNotAvailableException ex) { throw new ResourceAllocationException("Unable to allocate resources", ex); } } FlowResourcesManager(PersistenceManager persistenceManager, FlowResourcesConfig config); FlowResources allocateFlowResources(Flow flow); void deallocatePathResources(PathId pathId, long unmaskedCookie, FlowEncapsulationType encapsulationType); void deallocatePathResources(FlowResources resources); Optional<EncapsulationResources> getEncapsulationResources(PathId pathId, PathId oppositePathId, FlowEncapsulationType encapsulationType); }### Answer: @Test public void shouldAllocateForFlow() throws ResourceAllocationException { transactionManager.doInTransaction(() -> { Flow flow = convertFlow(firstFlow); verifyAllocation(resourcesManager.allocateFlowResources(flow)); }); } @Test public void shouldAllocateForNoBandwidthFlow() throws ResourceAllocationException { transactionManager.doInTransaction(() -> { Flow flow = convertFlow(fourthFlow); verifyMeterLessAllocation(resourcesManager.allocateFlowResources(flow)); }); } @Test public void shouldNotConsumeVlansForSingleSwitchFlows() throws ResourceAllocationException { transactionManager.doInTransaction(() -> { final int attemps = (flowResourcesConfig.getMaxFlowTransitVlan() - flowResourcesConfig.getMinFlowTransitVlan()) / 2 + 1; for (int i = 0; i < attemps; i++) { thirdFlow.setFlowId(format("third-flow-%d", i)); Flow flow3 = convertFlow(thirdFlow); resourcesManager.allocateFlowResources(flow3); } }); } @Test public void shouldNotConsumeMetersForUnmeteredFlows() throws ResourceAllocationException { transactionManager.doInTransaction(() -> { final int attemps = (flowResourcesConfig.getMaxFlowMeterId() - flowResourcesConfig.getMinFlowMeterId()) / 2 + 1; for (int i = 0; i < attemps; i++) { fourthFlow.setFlowId(format("fourth-flow-%d", i)); Flow flow4 = convertFlow(fourthFlow); resourcesManager.allocateFlowResources(flow4); } }); }
### Question: FlowResourcesManager { public void deallocatePathResources(PathId pathId, long unmaskedCookie, FlowEncapsulationType encapsulationType) { log.debug("Deallocate flow resources for path {}, cookie: {}.", pathId, unmaskedCookie); transactionManager.doInTransaction(() -> { cookiePool.deallocate(unmaskedCookie); meterPool.deallocate(pathId); EncapsulationResourcesProvider encapsulationResourcesProvider = getEncapsulationResourcesProvider(encapsulationType); encapsulationResourcesProvider.deallocate(pathId); }); } FlowResourcesManager(PersistenceManager persistenceManager, FlowResourcesConfig config); FlowResources allocateFlowResources(Flow flow); void deallocatePathResources(PathId pathId, long unmaskedCookie, FlowEncapsulationType encapsulationType); void deallocatePathResources(FlowResources resources); Optional<EncapsulationResources> getEncapsulationResources(PathId pathId, PathId oppositePathId, FlowEncapsulationType encapsulationType); }### Answer: @Test public void deallocatePathResourcesTest() throws Exception { transactionManager.doInTransaction(() -> { Flow flow = convertFlow(firstFlow); FlowResources resources = resourcesManager.allocateFlowResources(flow); resourcesManager.deallocatePathResources(resources.getForward().getPathId(), resources.getUnmaskedCookie(), flow.getEncapsulationType()); resourcesManager.deallocatePathResources(resources.getReverse().getPathId(), resources.getUnmaskedCookie(), flow.getEncapsulationType()); verifyResourcesDeallocation(); }); }
### Question: TransitVlanPool implements EncapsulationResourcesProvider<TransitVlanEncapsulation> { @Override public TransitVlanEncapsulation allocate(Flow flow, PathId pathId, PathId oppositePathId) { return get(oppositePathId, null) .orElseGet(() -> allocate(flow, pathId)); } TransitVlanPool(PersistenceManager persistenceManager, int minTransitVlan, int maxTransitVlan, int poolSize); @Override TransitVlanEncapsulation allocate(Flow flow, PathId pathId, PathId oppositePathId); @Override void deallocate(PathId pathId); @Override Optional<TransitVlanEncapsulation> get(PathId pathId, PathId oppositePathId); }### Answer: @Test public void vlanPoolTest() { transactionManager.doInTransaction(() -> { Set<Integer> transitVlans = new HashSet<>(); for (int i = MIN_TRANSIT_VLAN; i <= MAX_TRANSIT_VLAN; i++) { Flow flow = Flow.builder() .flowId(format("flow_%d", i)).srcSwitch(SWITCH_A).destSwitch(SWITCH_B).build(); transitVlans.add(transitVlanPool.allocate( flow, new PathId(format("path_%d", i)), new PathId(format("opposite_dummy_%d", i))).getTransitVlan().getVlan()); } assertEquals(MAX_TRANSIT_VLAN - MIN_TRANSIT_VLAN + 1, transitVlans.size()); transitVlans.forEach(vlan -> assertTrue(vlan >= MIN_TRANSIT_VLAN && vlan <= MAX_TRANSIT_VLAN)); }); } @Test(expected = ResourceNotAvailableException.class) public void vlanPoolFullTest() { transactionManager.doInTransaction(() -> { for (int i = MIN_TRANSIT_VLAN; i <= MAX_TRANSIT_VLAN + 1; i++) { Flow flow = Flow.builder() .flowId(format("flow_%d", i)).srcSwitch(SWITCH_A).destSwitch(SWITCH_B).build(); assertTrue(transitVlanPool.allocate( flow, new PathId(format("path_%d", i)), new PathId(format("opposite_dummy_%d", i))).getTransitVlan().getVlan() > 0); } }); } @Test public void gotSameVlanForOppositePath() { Flow flow = Flow.builder().flowId("flow_1").srcSwitch(SWITCH_A).destSwitch(SWITCH_B).build(); final PathId forwardPathId = new PathId("forward"); final PathId reversePathId = new PathId("reverse"); transactionManager.doInTransaction(() -> { TransitVlan forward = transitVlanPool.allocate(flow, forwardPathId, reversePathId) .getTransitVlan(); TransitVlan reverse = transitVlanPool.allocate(flow, reversePathId, forwardPathId) .getTransitVlan(); Assert.assertEquals(forward, reverse); }); }
### Question: VxlanPool implements EncapsulationResourcesProvider<VxlanEncapsulation> { @Override public VxlanEncapsulation allocate(Flow flow, PathId pathId, PathId oppositePathId) { return get(oppositePathId, null) .orElseGet(() -> allocate(flow, pathId)); } VxlanPool(PersistenceManager persistenceManager, int minVxlan, int maxVxlan, int poolSize); @Override VxlanEncapsulation allocate(Flow flow, PathId pathId, PathId oppositePathId); @Override void deallocate(PathId pathId); @Override Optional<VxlanEncapsulation> get(PathId pathId, PathId oppositePathId); }### Answer: @Test public void vxlanIdPool() { transactionManager.doInTransaction(() -> { Set<Integer> vxlans = new HashSet<>(); for (int i = MIN_VXLAN; i <= MAX_VXLAN; i++) { Flow flow = Flow.builder() .flowId(format("flow_%d", i)).srcSwitch(SWITCH_A).destSwitch(SWITCH_B).build(); vxlans.add(vxlanPool.allocate( flow, new PathId(format("path_%d", i)), new PathId(format("opposite_dummy_%d", i))).getVxlan().getVni()); } assertEquals(MAX_VXLAN - MIN_VXLAN + 1, vxlans.size()); vxlans.forEach(vni -> assertTrue(vni >= MIN_VXLAN && vni <= MAX_VXLAN)); }); } @Test(expected = ResourceNotAvailableException.class) public void vxlanPoolFullTest() { transactionManager.doInTransaction(() -> { for (int i = MIN_VXLAN; i <= MAX_VXLAN + 1; i++) { Flow flow = Flow.builder() .flowId(format("flow_%d", i)).srcSwitch(SWITCH_A).destSwitch(SWITCH_B).build(); assertTrue(vxlanPool.allocate(flow, new PathId(format("path_%d", i)), new PathId(format("op_path_%d", i))).getVxlan().getVni() > 0); } }); }
### Question: MeterPool { public MeterPool(PersistenceManager persistenceManager, MeterId minMeterId, MeterId maxMeterId, int poolSize) { transactionManager = persistenceManager.getTransactionManager(); RepositoryFactory repositoryFactory = persistenceManager.getRepositoryFactory(); flowMeterRepository = repositoryFactory.createFlowMeterRepository(); this.minMeterId = minMeterId; this.maxMeterId = maxMeterId; this.poolSize = poolSize; } MeterPool(PersistenceManager persistenceManager, MeterId minMeterId, MeterId maxMeterId, int poolSize); @TransactionRequired MeterId allocate(SwitchId switchId, String flowId, PathId pathId); void deallocate(PathId... pathIds); }### Answer: @Test public void meterPoolTest() { transactionManager.doInTransaction(() -> { long minMeterId = MIN_METER_ID.getValue(); long maxMeterId = MAX_METER_ID.getValue(); Set<MeterId> meterIds = new HashSet<>(); for (long i = minMeterId; i <= maxMeterId; i++) { meterIds.add(meterPool.allocate(SWITCH_ID, format("flow_%d", i), new PathId(format("path_%d", i)))); } assertEquals(maxMeterId - minMeterId + 1, meterIds.size()); meterIds.forEach(meterId -> assertTrue(meterId.getValue() >= minMeterId && meterId.getValue() <= maxMeterId)); }); }
### Question: MeterPool { @TransactionRequired public MeterId allocate(SwitchId switchId, String flowId, PathId pathId) { MeterId nextMeter = nextMeters.get(switchId); if (nextMeter != null && nextMeter.getValue() > 0) { if (nextMeter.compareTo(maxMeterId) <= 0 && !flowMeterRepository.exists(switchId, nextMeter)) { addMeter(flowId, pathId, switchId, nextMeter); nextMeters.put(switchId, new MeterId(nextMeter.getValue() + 1)); return nextMeter; } else { nextMeters.remove(switchId); } } if (!nextMeters.containsKey(switchId)) { long numOfPools = (maxMeterId.getValue() - minMeterId.getValue()) / poolSize; if (numOfPools > 1) { long poolToTake = Math.abs(new Random().nextInt()) % numOfPools; Optional<MeterId> availableMeter = flowMeterRepository.findFirstUnassignedMeter(switchId, new MeterId(minMeterId.getValue() + poolToTake * poolSize), new MeterId(minMeterId.getValue() + (poolToTake + 1) * poolSize - 1)); if (availableMeter.isPresent()) { nextMeter = availableMeter.get(); addMeter(flowId, pathId, switchId, nextMeter); nextMeters.put(switchId, new MeterId(nextMeter.getValue() + 1)); return nextMeter; } } nextMeter = new MeterId(-1); nextMeters.put(switchId, nextMeter); } if (nextMeter != null && nextMeter.getValue() == -1) { Optional<MeterId> availableMeter = flowMeterRepository.findFirstUnassignedMeter(switchId, minMeterId, maxMeterId); if (availableMeter.isPresent()) { nextMeter = availableMeter.get(); addMeter(flowId, pathId, switchId, nextMeter); nextMeters.put(switchId, new MeterId(nextMeter.getValue() + 1)); return nextMeter; } } throw new ResourceNotAvailableException(format("No meter available for switch %s", switchId)); } MeterPool(PersistenceManager persistenceManager, MeterId minMeterId, MeterId maxMeterId, int poolSize); @TransactionRequired MeterId allocate(SwitchId switchId, String flowId, PathId pathId); void deallocate(PathId... pathIds); }### Answer: @Test(expected = ResourceNotAvailableException.class) public void meterPoolFullTest() { transactionManager.doInTransaction(() -> { for (long i = MIN_METER_ID.getValue(); i <= MAX_METER_ID.getValue() + 1; i++) { meterPool.allocate(SWITCH_ID, format("flow_%d", i), new PathId(format("path_%d", i))); } }); } @Ignore("InMemoryGraph doesn't enforce constraint") @Test(expected = ConstraintViolationException.class) public void createTwoMeterForOnePathTest() { transactionManager.doInTransaction(() -> { long first = meterPool.allocate(SWITCH_ID, FLOW_1, PATH_ID_1).getValue(); long second = meterPool.allocate(SWITCH_ID, FLOW_1, PATH_ID_1).getValue(); }); }
### Question: IslInfoData extends CacheTimeTag { @JsonIgnore public boolean isSelfLooped() { return Objects.equals(source.getSwitchId(), destination.getSwitchId()); } IslInfoData(IslInfoData that); IslInfoData(PathNode source, PathNode destination, IslChangeType state, boolean underMaintenance); @Builder(toBuilder = true) @JsonCreator IslInfoData(@JsonProperty("latency_ns") long latency, @JsonProperty("source") PathNode source, @JsonProperty("destination") PathNode destination, @JsonProperty("speed") long speed, @JsonProperty("available_bandwidth") long availableBandwidth, @JsonProperty("max_bandwidth") long maxBandwidth, @JsonProperty("default_max_bandwidth") long defaultMaxBandwidth, @JsonProperty("state") IslChangeType state, @JsonProperty("actual_state") IslChangeType actualState, @JsonProperty("cost") int cost, @JsonProperty("time_create") Long timeCreateMillis, @JsonProperty("time_modify") Long timeModifyMillis, @JsonProperty("under_maintenance") boolean underMaintenance, @JsonProperty("enable_bfd") boolean enableBfd, @JsonProperty("bfd_session_status") String bfdSessionStatus, @JsonProperty("packet_id") Long packetId); void setAvailableBandwidth(long availableBandwidth); void setState(IslChangeType state); @JsonIgnore boolean isSelfLooped(); }### Answer: @Test public void shouldReturnTrueWhenSelfLooped() { final SwitchId switchId = new SwitchId("00:00:00:00:00:00:00:01"); PathNode source = new PathNode(switchId, 1, 0); PathNode destination = new PathNode(switchId, 2, 1); IslInfoData isl = new IslInfoData(source, destination, IslChangeType.DISCOVERED, false); assertTrue(isl.isSelfLooped()); } @Test public void shouldReturnFalseWhenNotSelfLooped() { final SwitchId srcSwitch = new SwitchId("00:00:00:00:00:00:00:01"); final SwitchId dstSwitch = new SwitchId("00:00:00:00:00:00:00:02"); PathNode source = new PathNode(srcSwitch, 1, 0); PathNode destination = new PathNode(dstSwitch, 2, 1); IslInfoData isl = new IslInfoData(source, destination, IslChangeType.DISCOVERED, false); assertFalse(isl.isSelfLooped()); }
### Question: FlowRttMetricGenBolt extends MetricGenBolt { @VisibleForTesting static long noviflowTimestamp(Long v) { long seconds = (v >> 32); long nanoseconds = (v & 0xFFFFFFFFL); return seconds * TEN_TO_NINE + nanoseconds; } FlowRttMetricGenBolt(String metricPrefix); static final long TEN_TO_NINE; }### Answer: @Test public void testNoviflowTimstampToLong() { long seconds = 123456789; long nanoseconds = 987654321; long timestampNovi = (seconds << 32) + nanoseconds; assertEquals(123456789_987654321L, noviflowTimestamp(timestampNovi)); }
### Question: FlowDirectionHelper { public static Direction findDirection(long rawCookie) throws FlowCookieException { return findDirectionSafe(rawCookie) .orElseThrow(() -> new FlowCookieException(String.format( "unknown direction for %s", new Cookie(rawCookie)))); } private FlowDirectionHelper(); static Direction findDirection(long rawCookie); static Optional<Direction> findDirectionSafe(long rawCookie); }### Answer: @Test public void findDirectionTest() throws Exception { assertEquals(Direction.FORWARD, FlowDirectionHelper.findDirection(FORWARD_COOKIE)); assertEquals(Direction.REVERSE, FlowDirectionHelper.findDirection(REVERSE_COOKIE)); thrown.expect(FlowCookieException.class); FlowDirectionHelper.findDirection(BAD_COOKIE); }
### Question: OfInput { public boolean packetInCookieMismatchAll(Logger log, U64... expected) { boolean isMismatched = packetInCookieMismatchCheck(expected); if (isMismatched) { log.debug("{} - cookie mismatch (expected one of:{}, actual:{})", this, expected, packetInCookie()); } return isMismatched; } OfInput(IOFSwitch sw, OFMessage message, FloodlightContext context); U64 packetInCookie(); boolean packetInCookieMismatchAll(Logger log, U64... expected); OFType getType(); long getReceiveTime(); DatapathId getDpId(); OFMessage getMessage(); Long getLatency(); Ethernet getPacketInPayload(); OFPort getPort(); @Override String toString(); }### Answer: @Test public void isCookieMismatch0() { OfInput input = makeInput(U64.of(cookieAlpha.getValue())); Assert.assertFalse(input.packetInCookieMismatchAll(callerLogger, cookieAlpha)); } @Test public void isCookieMismatch1() { OfInput input = makeInput(U64.of(-1)); Assert.assertFalse(input.packetInCookieMismatchAll(callerLogger, cookieAlpha)); input = makeInput(U64.ZERO); Assert.assertFalse(input.packetInCookieMismatchAll(callerLogger, cookieAlpha)); } @Test public void isCookieMismatch3() { OfInput input = makeInput(cookieAlpha); Assert.assertTrue(input.packetInCookieMismatchAll(callerLogger, cookieBeta)); }
### Question: ValidatingConfigurationProvider implements ConfigurationProvider { @Override public <T> T getConfiguration(Class<T> configurationType) { requireNonNull(configurationType, "configurationType cannot be null"); T instance = factory.createConfiguration(configurationType, source); Set<ConstraintViolation<T>> errors = validator.validate(instance); if (!errors.isEmpty()) { Set<String> errorDetails = errors.stream() .map(v -> v.getPropertyPath() + " " + v.getMessage()) .collect(toSet()); throw new ConfigurationException( format("The configuration value(s) for %s violate constraint(s): %s", configurationType.getSimpleName(), String.join(";", errorDetails)), errorDetails); } return instance; } ValidatingConfigurationProvider(ConfigurationSource source, ConfigurationFactory factory); @Override T getConfiguration(Class<T> configurationType); }### Answer: @Test public void shouldPassValidationForValidConfig() { Properties source = new Properties(); source.setProperty(TEST_KEY, String.valueOf(VALID_TEST_VALUE)); ValidatingConfigurationProvider provider = new ValidatingConfigurationProvider( new PropertiesConfigurationSource(source), new JdkProxyStaticConfigurationFactory()); TestConfig config = provider.getConfiguration(TestConfig.class); assertEquals(VALID_TEST_VALUE, config.getTestProperty()); } @Test public void shouldFailValidationForInvalidConfig() { Properties source = new Properties(); source.setProperty(TEST_KEY, String.valueOf(INVALID_TEST_VALUE)); ValidatingConfigurationProvider provider = new ValidatingConfigurationProvider( new PropertiesConfigurationSource(source), new JdkProxyStaticConfigurationFactory()); expectedException.expect(ConfigurationException.class); provider.getConfiguration(TestConfig.class); }
### Question: IslStatsBolt extends AbstractBolt implements IslStatsCarrier { @VisibleForTesting List<Object> buildTsdbTuple(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort, long latency, long timestamp) throws JsonProcessingException { Map<String, String> tags = new HashMap<>(); tags.put("src_switch", srcSwitchId.toOtsdFormat()); tags.put("src_port", String.valueOf(srcPort)); tags.put("dst_switch", dstSwitchId.toOtsdFormat()); tags.put("dst_port", String.valueOf(dstPort)); return tsdbTuple(metricFormatter.format(LATENCY_METRIC_NAME), timestamp, latency, tags); } IslStatsBolt(String metricPrefix, long latencyTimeout); @Override void emitLatency(SwitchId srcSwitch, int srcPort, SwitchId dstSwitch, int dstPort, long latency, long timestamp); @Override void declareOutputFields(OutputFieldsDeclarer declarer); static final String LATENCY_METRIC_NAME; }### Answer: @Test public void buildTsdbTupleFromIslOneWayLatency() throws JsonEncodeException, IOException { List<Object> tsdbTuple = statsBolt.buildTsdbTuple( SWITCH1_ID, NODE1.getPortNo(), SWITCH2_ID, NODE2.getPortNo(), LATENCY, TIMESTAMP); assertTsdbTuple(tsdbTuple); }
### Question: IslStatsService { @VisibleForTesting boolean isRecordStillValid(LatencyRecord record) { Instant expirationTime = Instant.ofEpochMilli(record.getTimestamp()) .plusSeconds(latencyTimeout); return Instant.now().isBefore(expirationTime); } IslStatsService(IslStatsCarrier carrier, long latencyTimeout); void handleRoundTripLatencyMetric(long timestamp, IslRoundTripLatency data, Endpoint destination); void handleOneWayLatencyMetric(long timestamp, IslOneWayLatency data); void handleIstStatusUpdateNotification(IslStatusUpdateNotification notification); }### Answer: @Test public void isRecordStillValidTest() { assertFalse(islStatsService.isRecordStillValid(new LatencyRecord(1, 0))); long expiredTimestamp = Instant.now().minusSeconds(LATENCY_TIMEOUT * 2).toEpochMilli(); assertFalse(islStatsService.isRecordStillValid(new LatencyRecord(1, expiredTimestamp))); assertTrue(islStatsService.isRecordStillValid(new LatencyRecord(1, System.currentTimeMillis()))); long freshTimestamp = Instant.now().plusSeconds(LATENCY_TIMEOUT * 2).toEpochMilli(); assertTrue(islStatsService.isRecordStillValid(new LatencyRecord(1, freshTimestamp))); }
### Question: CacheService { public void handleGetDataFromCache(IslRoundTripLatency roundTripLatency) { Endpoint source = Endpoint.of(roundTripLatency.getSrcSwitchId(), roundTripLatency.getSrcPortNo()); Endpoint destination = cache.get(source); try { if (destination == null) { destination = updateCache(source); } carrier.emitCachedData(roundTripLatency, destination); } catch (IslNotFoundException e) { log.debug(String.format("Could not update ISL cache: %s", e.getMessage()), e); } catch (IllegalIslStateException e) { log.error(String.format("Could not update ISL cache: %s", e.getMessage()), e); } } CacheService(CacheCarrier carrier, RepositoryFactory repositoryFactory); void handleUpdateCache(IslStatusUpdateNotification notification); void handleGetDataFromCache(IslRoundTripLatency roundTripLatency); }### Answer: @Test() public void handleGetDataFromCacheTest() { IslRoundTripLatency forward = new IslRoundTripLatency(SWITCH_ID_1, PORT_1, 1, 0L); IslRoundTripLatency reverse = new IslRoundTripLatency(SWITCH_ID_2, PORT_2, 1, 0L); checkHandleGetDataFromCache(forward, SWITCH_ID_2, PORT_2); checkHandleGetDataFromCache(reverse, SWITCH_ID_1, PORT_1); }
### Question: CacheService { public void handleUpdateCache(IslStatusUpdateNotification notification) { if (notification.getStatus() == IslStatus.MOVED || notification.getStatus() == IslStatus.INACTIVE) { Endpoint source = Endpoint.of(notification.getSrcSwitchId(), notification.getSrcPortNo()); Endpoint destination = Endpoint.of(notification.getDstSwitchId(), notification.getDstPortNo()); cache.remove(source); cache.remove(destination); log.info("Remove ISL {}_{} ===> {}_{} from isl latency cache", notification.getSrcSwitchId(), notification.getSrcPortNo(), notification.getDstSwitchId(), notification.getDstPortNo()); } } CacheService(CacheCarrier carrier, RepositoryFactory repositoryFactory); void handleUpdateCache(IslStatusUpdateNotification notification); void handleGetDataFromCache(IslRoundTripLatency roundTripLatency); }### Answer: @Test() public void handleUpdateCacheInactiveTest() { IslStatusUpdateNotification notification = new IslStatusUpdateNotification(SWITCH_ID_1, PORT_1, SWITCH_ID_2, PORT_2, INACTIVE); updateIslStatus(SWITCH_ID_1, PORT_1, SWITCH_ID_2, PORT_2, INACTIVE); updateIslStatus(SWITCH_ID_2, PORT_2, SWITCH_ID_1, PORT_1, INACTIVE); cacheService.handleUpdateCache(notification); IslRoundTripLatency forward = new IslRoundTripLatency(SWITCH_ID_1, PORT_1, 1, 0L); checkHandleGetDataFromCache(forward, SWITCH_ID_2, PORT_2); IslRoundTripLatency reverse = new IslRoundTripLatency(SWITCH_ID_2, PORT_2, 1, 0L); checkHandleGetDataFromCache(reverse, SWITCH_ID_1, PORT_1); }
### Question: IslLatencyService { @VisibleForTesting void updateIslLatency( SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort, long latency) throws SwitchNotFoundException, IslNotFoundException { transactionManager.doInTransaction(() -> { Isl isl = islRepository.findByEndpoints(srcSwitchId, srcPort, dstSwitchId, dstPort) .orElseThrow(() -> new IslNotFoundException(srcSwitchId, srcPort, dstSwitchId, dstPort)); isl.setLatency(latency); }); } IslLatencyService(TransactionManager transactionManager, RepositoryFactory repositoryFactory, long latencyUpdateInterval, long latencyUpdateTimeRange); void handleRoundTripIslLatency(IslRoundTripLatency data, Endpoint destination, long timestamp); void handleOneWayIslLatency(IslOneWayLatency data, long timestamp); static final String ONE_WAY_LATENCY; static final String ROUND_TRIP_LATENCY; }### Answer: @Test(expected = IslNotFoundException.class) public void updateIslLatencyNonExistentSrcEndpointTest() throws IslNotFoundException, SwitchNotFoundException { islLatencyService.updateIslLatency(NON_EXISTENT_SWITCH_ID, PORT_1, SWITCH_ID_2, PORT_2, 0); } @Test(expected = IslNotFoundException.class) public void updateIslLatencyNonExistentDstEndpointTest() throws IslNotFoundException, SwitchNotFoundException { islLatencyService.updateIslLatency(SWITCH_ID_1, PORT_1, NON_EXISTENT_SWITCH_ID, PORT_2, 0); } @Test(expected = IslNotFoundException.class) public void updateIslLatencyNonExistentIslTest() throws IslNotFoundException, SwitchNotFoundException { islLatencyService.updateIslLatency(SWITCH_ID_1, NON_EXISTENT_PORT, SWITCH_ID_2, NON_EXISTENT_PORT, 0); } @Test public void updateIslLatencyTest() throws IslNotFoundException, SwitchNotFoundException { islLatencyService.updateIslLatency(SWITCH_ID_1, PORT_1, SWITCH_ID_2, PORT_2, 1000); assertForwardLatency(1000); }
### Question: IslLatencyService { public void handleOneWayIslLatency(IslOneWayLatency data, long timestamp) { log.debug("Received one way latency {} for ISL {}_{} ===> {}_{}, Packet Id: {}", data.getLatency(), data.getSrcSwitchId(), data.getSrcPortNo(), data.getDstSwitchId(), data.getDstPortNo(), data.getPacketId()); IslKey islKey = new IslKey(data); oneWayLatencyStorage.putIfAbsent(islKey, new LinkedList<>()); oneWayLatencyStorage.get(islKey).add(new LatencyRecord(data.getLatency(), timestamp)); if (isUpdateRequired(islKey)) { updateOneWayLatencyIfNeeded(data, islKey); } } IslLatencyService(TransactionManager transactionManager, RepositoryFactory repositoryFactory, long latencyUpdateInterval, long latencyUpdateTimeRange); void handleRoundTripIslLatency(IslRoundTripLatency data, Endpoint destination, long timestamp); void handleOneWayIslLatency(IslOneWayLatency data, long timestamp); static final String ONE_WAY_LATENCY; static final String ROUND_TRIP_LATENCY; }### Answer: @Test public void handleOneWayIslLatencyTest() { assertTrue(islLatencyService.isUpdateRequired(FORWARD_ISL_KEY)); islLatencyService.handleOneWayIslLatency(createForwardOneWayLatency(1), System.currentTimeMillis()); assertForwardLatency(1); assertFalse(islLatencyService.isUpdateRequired(FORWARD_ISL_KEY)); islLatencyService.handleOneWayIslLatency(createForwardOneWayLatency(10000), System.currentTimeMillis()); assertForwardLatency(1); assertFalse(islLatencyService.isUpdateRequired(FORWARD_ISL_KEY)); }
### Question: IslLatencyService { public void handleRoundTripIslLatency(IslRoundTripLatency data, Endpoint destination, long timestamp) { if (data.getLatency() < 0) { log.warn("Received invalid round trip latency {} for ISL {}_{} ===> {}_{}. Packet Id: {}", data.getLatency(), data.getSrcSwitchId(), data.getSrcPortNo(), destination.getDatapath(), destination.getPortNumber(), data.getPacketId()); return; } log.debug("Received round trip latency {} for ISL {}_{} ===> {}_{}. Packet Id: {}", data.getLatency(), data.getSrcSwitchId(), data.getSrcPortNo(), destination.getDatapath(), destination.getPortNumber(), data.getPacketId()); IslKey islKey = new IslKey(data, destination); roundTripLatencyStorage.putIfAbsent(islKey, new LinkedList<>()); roundTripLatencyStorage.get(islKey).add(new LatencyRecord(data.getLatency(), timestamp)); if (isUpdateRequired(islKey) || !roundTripLatencyIsSet.contains(islKey)) { updateRoundTripLatency(data, destination, islKey); } } IslLatencyService(TransactionManager transactionManager, RepositoryFactory repositoryFactory, long latencyUpdateInterval, long latencyUpdateTimeRange); void handleRoundTripIslLatency(IslRoundTripLatency data, Endpoint destination, long timestamp); void handleOneWayIslLatency(IslOneWayLatency data, long timestamp); static final String ONE_WAY_LATENCY; static final String ROUND_TRIP_LATENCY; }### Answer: @Test public void handleRoundTripIslLatencyTest() { assertTrue(islLatencyService.isUpdateRequired(FORWARD_ISL_KEY)); islLatencyService.handleRoundTripIslLatency( createForwardRoundTripLatency(5), FORWARD_DESTINATION, System.currentTimeMillis()); assertForwardLatency(5); assertFalse(islLatencyService.isUpdateRequired(FORWARD_ISL_KEY)); islLatencyService.handleRoundTripIslLatency( createForwardRoundTripLatency(50000), FORWARD_DESTINATION, System.currentTimeMillis()); assertForwardLatency(5); assertFalse(islLatencyService.isUpdateRequired(FORWARD_ISL_KEY)); }
### Question: IslLatencyService { @VisibleForTesting boolean isUpdateRequired(IslKey islKey) { return Instant.now().isAfter(nextUpdateTimeMap.getOrDefault(islKey, Instant.MIN)); } IslLatencyService(TransactionManager transactionManager, RepositoryFactory repositoryFactory, long latencyUpdateInterval, long latencyUpdateTimeRange); void handleRoundTripIslLatency(IslRoundTripLatency data, Endpoint destination, long timestamp); void handleOneWayIslLatency(IslOneWayLatency data, long timestamp); static final String ONE_WAY_LATENCY; static final String ROUND_TRIP_LATENCY; }### Answer: @Test public void isUpdateRequiredTest() { assertTrue(islLatencyService.isUpdateRequired(FORWARD_ISL_KEY)); IslRoundTripLatency data = new IslRoundTripLatency(SWITCH_ID_1, PORT_1, 1L, 0L); Endpoint destination = Endpoint.of(SWITCH_ID_2, PORT_2); islLatencyService.handleRoundTripIslLatency(data, destination, System.currentTimeMillis()); assertFalse(islLatencyService.isUpdateRequired(FORWARD_ISL_KEY)); }
### Question: IslLatencyService { @VisibleForTesting Instant getNextUpdateTime() { return Instant.now().plusSeconds(latencyUpdateInterval); } IslLatencyService(TransactionManager transactionManager, RepositoryFactory repositoryFactory, long latencyUpdateInterval, long latencyUpdateTimeRange); void handleRoundTripIslLatency(IslRoundTripLatency data, Endpoint destination, long timestamp); void handleOneWayIslLatency(IslOneWayLatency data, long timestamp); static final String ONE_WAY_LATENCY; static final String ROUND_TRIP_LATENCY; }### Answer: @Test public void getNextUpdateTimeTest() { Instant actualTime = islLatencyService.getNextUpdateTime(); long expectedTime = System.currentTimeMillis() + LATENCY_UPDATE_INTERVAL * 1000; assertEquals(expectedTime, actualTime.toEpochMilli(), 50); }
### Question: IslLatencyService { @VisibleForTesting long calculateAverageLatency(Queue<LatencyRecord> recordsQueue) { if (recordsQueue.isEmpty()) { log.error("Couldn't calculate average latency. Records queue is empty"); return -1; } long sum = 0; for (LatencyRecord record : recordsQueue) { sum += record.getLatency(); } return sum / recordsQueue.size(); } IslLatencyService(TransactionManager transactionManager, RepositoryFactory repositoryFactory, long latencyUpdateInterval, long latencyUpdateTimeRange); void handleRoundTripIslLatency(IslRoundTripLatency data, Endpoint destination, long timestamp); void handleOneWayIslLatency(IslOneWayLatency data, long timestamp); static final String ONE_WAY_LATENCY; static final String ROUND_TRIP_LATENCY; }### Answer: @Test public void calculateAverageLatencyTest() { Queue<LatencyRecord> latencyRecords = new LinkedList<>(); for (int i = 1; i <= 5; i++) { latencyRecords.add(new LatencyRecord(i, 1)); } assertEquals(3, islLatencyService.calculateAverageLatency(latencyRecords)); } @Test public void calculateAverageLatencyEmptyTest() { assertEquals(-1, islLatencyService.calculateAverageLatency(new LinkedList<>())); }
### Question: IslLatencyService { @VisibleForTesting void pollExpiredRecords(Queue<LatencyRecord> recordsQueue) { if (recordsQueue == null) { return; } Instant oldestTimeInRange = Instant.now().minusSeconds(latencyUpdateTimeRange); while (!recordsQueue.isEmpty() && Instant.ofEpochMilli(recordsQueue.peek().getTimestamp()).isBefore(oldestTimeInRange)) { recordsQueue.poll(); } } IslLatencyService(TransactionManager transactionManager, RepositoryFactory repositoryFactory, long latencyUpdateInterval, long latencyUpdateTimeRange); void handleRoundTripIslLatency(IslRoundTripLatency data, Endpoint destination, long timestamp); void handleOneWayIslLatency(IslOneWayLatency data, long timestamp); static final String ONE_WAY_LATENCY; static final String ROUND_TRIP_LATENCY; }### Answer: @Test public void pollExpiredRecordsTest() { Instant time = Instant.now().minusSeconds(LATENCY_UPDATE_TIME_RANGE * 2); Queue<LatencyRecord> latencyRecords = new LinkedList<>(); for (int i = 0; i < 5; i++) { latencyRecords.add(new LatencyRecord(i, time.toEpochMilli())); time = time.plusSeconds(1); } time = Instant.now().minusSeconds(LATENCY_UPDATE_TIME_RANGE - 7); for (int i = 5; i < 10; i++) { latencyRecords.add(new LatencyRecord(i, time.toEpochMilli())); time = time.plusSeconds(1); } assertEquals(10, latencyRecords.size()); islLatencyService.pollExpiredRecords(latencyRecords); assertEquals(5, latencyRecords.size()); for (int i = 5; i < 10; i++) { assertEquals(i, latencyRecords.poll().getLatency()); } }
### Question: KafkaProducerService implements IKafkaProducerService { public void sendMessageAndTrack(String topic, Message message) { produce(encode(topic, message), new SendStatusCallback(this, topic, message)); } @Override void setup(FloodlightModuleContext moduleContext); void sendMessageAndTrack(String topic, Message message); void sendMessageAndTrack(String topic, String key, Message message); @Override void sendMessageAndTrack(String topic, String key, AbstractMessage message); SendStatus sendMessage(String topic, Message message); int getFailedSendMessageCounter(); }### Answer: @Test public void errorReporting() throws Exception { final ExecutionException error = new ExecutionException("Emulate kafka send error", new IOException()); Future promise = mock(Future.class); expect(promise.get()).andThrow(error).anyTimes(); replay(promise); expect(kafkaProducer.send(anyObject(), anyObject(Callback.class))) .andAnswer(new IAnswer<Future<RecordMetadata>>() { @Override public Future<RecordMetadata> answer() { Callback callback = (Callback) getCurrentArguments()[1]; callback.onCompletion(null, error); return promise; } }); replay(kafkaProducer); subject.sendMessageAndTrack(TOPIC, makePayload()); verify(kafkaProducer); }
### Question: KafkaProducerService implements IKafkaProducerService { public SendStatus sendMessage(String topic, Message message) { SendStatus sendStatus = produce(encode(topic, message), null); return sendStatus; } @Override void setup(FloodlightModuleContext moduleContext); void sendMessageAndTrack(String topic, Message message); void sendMessageAndTrack(String topic, String key, Message message); @Override void sendMessageAndTrack(String topic, String key, AbstractMessage message); SendStatus sendMessage(String topic, Message message); int getFailedSendMessageCounter(); }### Answer: @Test public void errorDetection() throws Exception { Future promise = mock(Future.class); final ExecutionException error = new ExecutionException("Emulate kafka send error", new IOException()); expect(promise.get()).andThrow(error).anyTimes(); replay(promise); expect(kafkaProducer.send(anyObject(), anyObject(Callback.class))).andReturn(promise); replay(kafkaProducer); SendStatus status = subject.sendMessage(TOPIC, makePayload()); verify(kafkaProducer); Boolean isThrown; try { status.waitTillComplete(); isThrown = false; } catch (ExecutionException e) { isThrown = true; } Assert.assertTrue(String.format( "Exception was not thrown by %s object", status.getClass().getCanonicalName()), isThrown); }
### Question: WatcherService { public void addWatch(SwitchId switchId, int portNo, long currentTime) { Packet packet = Packet.of(switchId, portNo, packetNo); timeouts.computeIfAbsent(currentTime + awaitTime, mappingFunction -> new HashSet<>()) .add(packet); carrier.sendDiscovery(switchId, portNo, packetNo, currentTime); packetNo += 1; } WatcherService(IWatcherServiceCarrier carrier, long awaitTime); void addWatch(SwitchId switchId, int portNo, long currentTime); void removeWatch(SwitchId switchId, int portNo); void tick(long tickTime); void confirmation(SwitchId switchId, int portNo, long packetNo); void discovery(SwitchId switchId, int portNo, SwitchId endSwitchId, int endPortNo, long packetNo, long currentTime); Set<Packet> getConfirmations(); SortedMap<Long, Set<Packet>> getTimeouts(); }### Answer: @Test public void addWatch() { WatcherService w = new WatcherService(carrier, 10); w.addWatch(new SwitchId(1), 1, 1); w.addWatch(new SwitchId(1), 2, 1); w.addWatch(new SwitchId(2), 1, 2); w.addWatch(new SwitchId(2), 1, 2); w.addWatch(new SwitchId(2), 2, 3); assertThat(w.getConfirmations().size(), is(0)); assertThat(w.getTimeouts().size(), is(3)); verify(carrier, times(5)).sendDiscovery(any(SwitchId.class), anyInt(), anyLong(), anyLong()); }
### Question: WatcherService { public void removeWatch(SwitchId switchId, int portNo) { } WatcherService(IWatcherServiceCarrier carrier, long awaitTime); void addWatch(SwitchId switchId, int portNo, long currentTime); void removeWatch(SwitchId switchId, int portNo); void tick(long tickTime); void confirmation(SwitchId switchId, int portNo, long packetNo); void discovery(SwitchId switchId, int portNo, SwitchId endSwitchId, int endPortNo, long packetNo, long currentTime); Set<Packet> getConfirmations(); SortedMap<Long, Set<Packet>> getTimeouts(); }### Answer: @Test public void removeWatch() { }
### Question: WatcherService { public void tick(long tickTime) { SortedMap<Long, Set<Packet>> range = timeouts.subMap(0L, tickTime + 1); if (!range.isEmpty()) { for (Set<Packet> e : range.values()) { for (Packet ee : e) { if (confirmations.remove(ee)) { carrier.failed(ee.switchId, ee.port, tickTime); } } } range.clear(); } } WatcherService(IWatcherServiceCarrier carrier, long awaitTime); void addWatch(SwitchId switchId, int portNo, long currentTime); void removeWatch(SwitchId switchId, int portNo); void tick(long tickTime); void confirmation(SwitchId switchId, int portNo, long packetNo); void discovery(SwitchId switchId, int portNo, SwitchId endSwitchId, int endPortNo, long packetNo, long currentTime); Set<Packet> getConfirmations(); SortedMap<Long, Set<Packet>> getTimeouts(); }### Answer: @Test public void tick() { WatcherService w = new WatcherService(carrier, 10); w.addWatch(new SwitchId(1), 1, 1); w.addWatch(new SwitchId(1), 2, 1); w.addWatch(new SwitchId(2), 1, 2); w.addWatch(new SwitchId(2), 1, 2); w.addWatch(new SwitchId(2), 2, 3); assertThat(w.getConfirmations().size(), is(0)); assertThat(w.getTimeouts().size(), is(3)); verify(carrier, times(5)).sendDiscovery(any(SwitchId.class), anyInt(), anyLong(), anyLong()); w.confirmation(new SwitchId(1), 1, 0); w.confirmation(new SwitchId(2), 1, 2); assertThat(w.getConfirmations().size(), is(2)); w.tick(100); assertThat(w.getConfirmations().size(), is(0)); verify(carrier).failed(eq(new SwitchId(1)), eq(1), anyLong()); verify(carrier).failed(eq(new SwitchId(2)), eq(1), anyLong()); verify(carrier, times(2)).failed(any(SwitchId.class), anyInt(), anyLong()); assertThat(w.getTimeouts().size(), is(0)); }