src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
|---|---|
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); }
|
@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()); } }
|
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(); }
|
@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)); }
|
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; }
|
@Test(expected = IllegalArgumentException.class) public void createMeterIdForInvalidDefaultRuleTest() { MeterId.createMeterIdForDefaultRule(0x0000000000000123L); }
|
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; }
|
@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)); }
|
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; }
|
@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); }
|
LinkOperationsService { public Collection<Isl> deleteIsl(SwitchId sourceSwitch, int sourcePort, SwitchId destinationSwitch, int destinationPort, boolean force) throws IllegalIslStateException, IslNotFoundException { log.info("Delete ISL with following parameters: " + "source switch '{}', source port '{}', destination switch '{}', destination port '{}', " + "force '{}'", sourceSwitch, sourcePort, destinationSwitch, destinationPort, force); return transactionManager.doInTransaction(() -> { List<Isl> isls = new ArrayList<>(); islRepository.findByEndpoints(sourceSwitch, sourcePort, destinationSwitch, destinationPort).ifPresent(isls::add); islRepository.findByEndpoints(destinationSwitch, destinationPort, sourceSwitch, sourcePort).ifPresent(isls::add); if (isls.isEmpty()) { throw new IslNotFoundException(sourceSwitch, sourcePort, destinationSwitch, destinationPort); } if (!force) { if (isls.stream().anyMatch(x -> x.getStatus() == IslStatus.ACTIVE)) { throw new IllegalIslStateException(sourceSwitch, sourcePort, destinationSwitch, destinationPort, "ISL must NOT be in active state."); } Collection<FlowPath> flowPaths = flowPathRepository.findWithPathSegment(sourceSwitch, sourcePort, destinationSwitch, destinationPort); if (!flowPaths.isEmpty()) { throw new IllegalIslStateException(sourceSwitch, sourcePort, destinationSwitch, destinationPort, "This ISL is busy by flow paths."); } } isls.forEach(islRepository::remove); log.info("ISLs {} have been removed from the database", isls); return isls; }); } 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); }
|
@Test public void shouldDeleteInactiveIsl() throws IslNotFoundException, IllegalIslStateException { createIsl(IslStatus.INACTIVE); linkOperationsService .deleteIsl(TEST_SWITCH_A_ID, TEST_SWITCH_A_PORT, TEST_SWITCH_B_ID, TEST_SWITCH_B_PORT, false); assertTrue(islRepository.findAll().isEmpty()); }
@Test(expected = IllegalIslStateException.class) public void shouldNotDeleteActiveIsl() throws IslNotFoundException, IllegalIslStateException { createIsl(IslStatus.ACTIVE); linkOperationsService .deleteIsl(TEST_SWITCH_A_ID, TEST_SWITCH_A_PORT, TEST_SWITCH_B_ID, TEST_SWITCH_B_PORT, false); }
@Test(expected = IllegalIslStateException.class) public void shouldNotDeleteBusyIsl() throws IslNotFoundException, IllegalIslStateException { createIsl(IslStatus.INACTIVE); createFlow("test_flow_id", TEST_SWITCH_A_ID, TEST_SWITCH_A_PORT, TEST_SWITCH_B_ID, TEST_SWITCH_B_PORT); linkOperationsService .deleteIsl(TEST_SWITCH_A_ID, TEST_SWITCH_A_PORT, TEST_SWITCH_B_ID, TEST_SWITCH_B_PORT, false); }
@Test public void shouldForceDeleteActiveIsl() throws IslNotFoundException, IllegalIslStateException { createIsl(IslStatus.ACTIVE); linkOperationsService .deleteIsl(TEST_SWITCH_A_ID, TEST_SWITCH_A_PORT, TEST_SWITCH_B_ID, TEST_SWITCH_B_PORT, true); assertTrue(islRepository.findAll().isEmpty()); }
@Test public void shouldForceDeleteBusyIsl() throws IslNotFoundException, IllegalIslStateException { createIsl(IslStatus.INACTIVE); createFlow("test_flow_id", TEST_SWITCH_A_ID, TEST_SWITCH_A_PORT, TEST_SWITCH_B_ID, TEST_SWITCH_B_PORT); linkOperationsService .deleteIsl(TEST_SWITCH_A_ID, TEST_SWITCH_A_PORT, TEST_SWITCH_B_ID, TEST_SWITCH_B_PORT, true); assertTrue(islRepository.findAll().isEmpty()); }
|
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; }
|
@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); }
|
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); }
|
@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))); }
|
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); }
|
@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); }
|
PathComputerFactory { public PathComputer getPathComputer() { return new InMemoryPathComputer(availableNetworkFactory, new BestWeightAndShortestPathFinder(config.getMaxAllowedDepth()), config); } PathComputerFactory(PathComputerConfig config, AvailableNetworkFactory availableNetworkFactory); PathComputer getPathComputer(); }
|
@Test public void shouldCreateAnInstance() { PathComputerFactory factory = new PathComputerFactory( mock(PathComputerConfig.class), mock(AvailableNetworkFactory.class)); PathComputer pathComputer = factory.getPathComputer(); assertTrue(pathComputer instanceof InMemoryPathComputer); }
|
AvailableNetworkFactory { public AvailableNetwork getAvailableNetwork(Flow flow, Collection<PathId> reusePathsResources) throws RecoverableException { BuildStrategy buildStrategy = BuildStrategy.from(config.getNetworkStrategy()); AvailableNetwork network = new AvailableNetwork(); try { Collection<Isl> links = getAvailableIsls(buildStrategy, flow); links.forEach(network::addLink); if (!reusePathsResources.isEmpty() && !flow.isIgnoreBandwidth()) { reusePathsResources.forEach(pathId -> { Collection<Isl> flowLinks = islRepository.findActiveAndOccupiedByFlowPathWithAvailableBandwidth( pathId, flow.getBandwidth(), flow.getEncapsulationType()); flowLinks.forEach(network::addLink); }); } } catch (PersistenceException e) { throw new RecoverableException("An error from the database", e); } if (flow.getGroupId() != null) { log.info("Filling AvailableNetwork diverse weighs for group with id {}", flow.getGroupId()); Collection<PathId> flowPaths = flowPathRepository.findPathIdsByFlowGroupId(flow.getGroupId()); if (!reusePathsResources.isEmpty()) { flowPaths = flowPaths.stream() .filter(s -> !reusePathsResources.contains(s)) .collect(Collectors.toList()); } flowPaths.forEach(pathId -> flowPathRepository.findById(pathId) .ifPresent(flowPath -> { network.processDiversitySegments(flowPath.getSegments()); network.processDiversitySegmentsWithPop(flowPath.getSegments()); })); } return network; } AvailableNetworkFactory(PathComputerConfig config, RepositoryFactory repositoryFactory); AvailableNetwork getAvailableNetwork(Flow flow, Collection<PathId> reusePathsResources); }
|
@Test public void shouldBuildAvailableNetworkUsingCostStrategy() throws RecoverableException { Flow flow = getFlow(false); Isl isl = getIsl(flow); when(config.getNetworkStrategy()).thenReturn("COST"); when(islRepository.findActiveWithAvailableBandwidth(flow.getBandwidth(), flow.getEncapsulationType())) .thenReturn(Collections.singletonList(isl)); AvailableNetwork availableNetwork = availableNetworkFactory.getAvailableNetwork(flow, Collections.emptyList()); assertAvailableNetworkIsCorrect(isl, availableNetwork); }
@Test public void shouldIncreaseDiversityGroupUseCounter() throws RecoverableException { List<Isl> isls = new ArrayList<>(); isls.addAll(getBidirectionalIsls(switchA, 1, switchB, 2)); isls.addAll(getBidirectionalIsls(switchB, 3, switchC, 4)); final Flow diverseFlow = Flow.builder() .flowId(FLOW_ID_1) .groupId(GROUP_ID) .srcSwitch(switchB) .destSwitch(switchD) .build(); FlowPath forwardPath = FlowPath.builder() .srcSwitch(switchB) .destSwitch(switchD) .pathId(FORWARD_PATH_ID) .segments(Collections.singletonList(PathSegment.builder() .srcSwitch(switchB).srcPort(SRC_PORT).destSwitch(switchD).destPort(DEST_PORT).build())) .build(); when(flowPathRepository.findById(FORWARD_PATH_ID)).thenReturn(java.util.Optional.of(forwardPath)); FlowPath reversePath = FlowPath.builder() .srcSwitch(switchD) .destSwitch(switchB) .pathId(REVERSE_PATH_ID) .segments(Collections.singletonList(PathSegment.builder() .srcSwitch(switchD).srcPort(DEST_PORT).destSwitch(switchB).destPort(SRC_PORT).build())) .build(); when(flowPathRepository.findById(REVERSE_PATH_ID)).thenReturn(java.util.Optional.of(reversePath)); Flow flow = getFlow(false); flow.setSrcSwitch(switchA); flow.setDestSwitch(switchC); flow.setGroupId(GROUP_ID); when(config.getNetworkStrategy()).thenReturn(BuildStrategy.COST.name()); when(islRepository.findActiveWithAvailableBandwidth(flow.getBandwidth(), flow.getEncapsulationType())) .thenReturn(isls); when(flowPathRepository.findPathIdsByFlowGroupId(GROUP_ID)) .thenReturn(Lists.newArrayList(FORWARD_PATH_ID, REVERSE_PATH_ID)); AvailableNetwork availableNetwork = availableNetworkFactory.getAvailableNetwork(flow, Collections.emptyList()); assertEquals(2, availableNetwork.getSwitch(switchB.getSwitchId()).getDiversityGroupUseCounter()); }
@Test public void shouldBuildAvailableNetworkUsingCostStrategyWithIgnoreBandwidth() throws RecoverableException { Flow flow = getFlow(true); Isl isl = getIsl(flow); when(config.getNetworkStrategy()).thenReturn("COST"); when(islRepository.findAllActiveByEncapsulationType(flow.getEncapsulationType())) .thenReturn(Collections.singletonList(isl)); AvailableNetwork availableNetwork = availableNetworkFactory.getAvailableNetwork(flow, Collections.emptyList()); assertAvailableNetworkIsCorrect(isl, availableNetwork); }
@Test public void shouldBuildAvailableNetworkUsingSymmetricCostStrategy() throws RecoverableException { Flow flow = getFlow(false); Isl isl = getIsl(flow); when(config.getNetworkStrategy()).thenReturn("SYMMETRIC_COST"); when(islRepository.findSymmetricActiveWithAvailableBandwidth(flow.getBandwidth(), flow.getEncapsulationType())) .thenReturn(Collections.singletonList(isl)); AvailableNetwork availableNetwork = availableNetworkFactory.getAvailableNetwork(flow, Collections.emptyList()); assertAvailableNetworkIsCorrect(isl, availableNetwork); }
@Test public void shouldBuildAvailableNetworkUsingSymmetricCostStrategyWithIgnoreBandwidth() throws RecoverableException { Flow flow = getFlow(true); Isl isl = getIsl(flow); when(config.getNetworkStrategy()).thenReturn("SYMMETRIC_COST"); when(islRepository.findAllActiveByEncapsulationType(flow.getEncapsulationType())) .thenReturn(Collections.singletonList(isl)); AvailableNetwork availableNetwork = availableNetworkFactory.getAvailableNetwork(flow, Collections.emptyList()); assertAvailableNetworkIsCorrect(isl, availableNetwork); }
|
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); }
|
@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)); }
|
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); }
|
@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); }
|
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); }
|
@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); }
|
FlowRerouteService { public void handleRequest(String key, FlowRerouteRequest reroute, final CommandContext commandContext) { log.debug("Handling flow reroute request with key {} and flow ID: {}", key, reroute.getFlowId()); try { checkRequestsCollision(key, reroute.getFlowId(), commandContext); } catch (Exception e) { log.error(e.getMessage()); FlowRerouteFsm fsm = fsms.get(key); if (fsm != null) { removeIfFinished(fsm, key); } return; } final String flowId = reroute.getFlowId(); if (isRerouteAlreadyInProgress(flowId)) { carrier.sendRerouteResultStatus(flowId, new RerouteInProgressError(), commandContext.getCorrelationId()); return; } FlowRerouteFsm fsm = fsmFactory.newInstance(commandContext, flowId); fsms.put(key, fsm); FlowRerouteContext context = FlowRerouteContext.builder() .flowId(flowId) .affectedIsl(reroute.getAffectedIsl()) .forceReroute(reroute.isForce()) .ignoreBandwidth(reroute.isIgnoreBandwidth()) .effectivelyDown(reroute.isEffectivelyDown()) .rerouteReason(reroute.getReason()) .build(); fsmExecutor.fire(fsm, Event.NEXT, context); removeIfFinished(fsm, key); } FlowRerouteService(FlowRerouteHubCarrier carrier, PersistenceManager persistenceManager,
PathComputer pathComputer, FlowResourcesManager flowResourcesManager,
int pathAllocationRetriesLimit, int pathAllocationRetryDelay,
int speakerCommandRetriesLimit); void handleRequest(String key, FlowRerouteRequest reroute, final CommandContext commandContext); void handleAsyncResponse(String key, SpeakerFlowSegmentResponse flowResponse); void handleTimeout(String key); }
|
@Test public void shouldSkipRerouteIfNoNewPathFound() throws RecoverableException, UnroutableFlowException { Flow origin = makeFlow(); preparePathComputation(origin.getFlowId(), make2SwitchesPathPair()); FlowRerouteRequest request = new FlowRerouteRequest(origin.getFlowId(), false, false, false, Collections.emptySet(), null); makeService().handleRequest(dummyRequestKey, request, commandContext); verifyNoSpeakerInteraction(carrier); verifyNorthboundSuccessResponse(carrier); Flow result = verifyFlowStatus(origin.getFlowId(), FlowStatus.UP); verifyNoPathReplace(origin, result); }
@Test public void shouldCompleteRerouteOnErrorDuringCompletingFlowPathRemoval() throws RecoverableException, UnroutableFlowException { Flow origin = makeFlow(); preparePathComputation(origin.getFlowId(), make3SwitchesPathPair()); FlowPathRepository repository = setupFlowPathRepositorySpy(); doThrow(new RuntimeException(injectedErrorMessage)) .when(repository) .remove(eq(origin.getForwardPathId())); FlowRerouteService service = makeService(); FlowRerouteRequest request = new FlowRerouteRequest(origin.getFlowId(), false, false, false, Collections.emptySet(), null); service.handleRequest(currentRequestKey, request, commandContext); verifyFlowStatus(origin.getFlowId(), FlowStatus.IN_PROGRESS); verifyNorthboundSuccessResponse(carrier); FlowSegmentRequest speakerRequest; while ((speakerRequest = requests.poll()) != null) { produceAsyncResponse(service, speakerRequest); } Flow result = verifyFlowStatus(origin.getFlowId(), FlowStatus.UP); verifyPathReplace(origin, result); }
@Test public void shouldSuccessfullyRerouteFlow() throws RecoverableException, UnroutableFlowException { Flow origin = makeFlow(); origin.setStatus(FlowStatus.DOWN); transactionManager.doInTransaction(() -> repositoryFactory.createFlowRepository().updateStatus(origin.getFlowId(), FlowStatus.DOWN)); preparePathComputation(origin.getFlowId(), make3SwitchesPathPair(origin.getPathComputationStrategy())); FlowRerouteService service = makeService(); FlowRerouteRequest request = new FlowRerouteRequest(origin.getFlowId(), false, false, false, Collections.emptySet(), null); service.handleRequest(currentRequestKey, request, commandContext); verifyFlowStatus(origin.getFlowId(), FlowStatus.IN_PROGRESS); verifyNorthboundSuccessResponse(carrier); FlowSegmentRequest speakerRequest; while ((speakerRequest = requests.poll()) != null) { produceAsyncResponse(service, speakerRequest); } Flow result = verifyFlowStatus(origin.getFlowId(), FlowStatus.UP); verifyPathReplace(origin, result); RerouteResultInfoData expected = RerouteResultInfoData.builder() .flowId(origin.getFlowId()) .success(true) .build(); verify(carrier).sendRerouteResultStatus(eq(origin.getFlowId()), isNull(), any(String.class)); }
@Test public void shouldSuccessfullyHandleOverlappingRequests() throws RecoverableException, UnroutableFlowException { Flow origin = makeFlow(); origin.setStatus(FlowStatus.DOWN); transactionManager.doInTransaction(() -> repositoryFactory.createFlowRepository().updateStatus(origin.getFlowId(), FlowStatus.DOWN)); when(pathComputer.getPath(makeFlowArgumentMatch(origin.getFlowId()), any(), any())) .thenReturn(make2SwitchAltPathPair()) .thenReturn(make3SwitchesPathPair()); FlowRerouteService service = makeService(); FlowRerouteRequest rerouteRequest = new FlowRerouteRequest(origin.getFlowId(), false, false, false, Collections.emptySet(), null); service.handleRequest(currentRequestKey, rerouteRequest, commandContext); verifyFlowStatus(origin.getFlowId(), FlowStatus.IN_PROGRESS); String overlappingKey = dummyRequestKey + "2"; service.handleRequest(overlappingKey, rerouteRequest, commandContext); verifyFlowStatus(origin.getFlowId(), FlowStatus.IN_PROGRESS); FlowSegmentRequest request; while ((request = requests.poll()) != null) { produceAsyncResponse(service, request); } Flow result = verifyFlowStatus(origin.getFlowId(), FlowStatus.UP); verifyPathReplace(origin, result); FlowPath forwardPath = result.getForwardPath(); Assert.assertNotNull(forwardPath); Assert.assertEquals(1, forwardPath.getSegments().size()); verify(carrier).sendRerouteResultStatus(eq(origin.getFlowId()), argThat(hasProperty("message", equalTo("Reroute is in progress"))), any(String.class)); }
@Test public void shouldIgnoreEffectivelyDownStateIfSamePaths() throws RecoverableException, UnroutableFlowException { Flow origin = makeFlow(); preparePathComputation(origin.getFlowId(), make2SwitchesPathPair()); FlowRerouteService service = makeService(); FlowRerouteRequest request = new FlowRerouteRequest(origin.getFlowId(), false, true, false, Collections.emptySet(), null); service.handleRequest(currentRequestKey, request, commandContext); FlowSegmentRequest speakerRequest; while ((speakerRequest = requests.poll()) != null) { produceAsyncResponse(service, speakerRequest); } Flow result = verifyFlowStatus(origin.getFlowId(), FlowStatus.UP); verifyNoPathReplace(origin, result); }
@Test public void shouldProcessRerouteForValidRequest() throws RecoverableException, UnroutableFlowException { Flow origin = makeFlow(); origin.setTargetPathComputationStrategy(LATENCY); setupFlowRepositorySpy().findById(origin.getFlowId()) .ifPresent(foundPath -> foundPath.setTargetPathComputationStrategy(LATENCY)); preparePathComputation(origin.getFlowId(), make3SwitchesPathPair(origin.getTargetPathComputationStrategy())); FlowRerouteService service = makeService(); IslEndpoint affectedEndpoint = extractIslEndpoint(origin); FlowRerouteRequest request = new FlowRerouteRequest(origin.getFlowId(), false, true, false, Collections.singleton(affectedEndpoint), null); service.handleRequest(currentRequestKey, request, commandContext); verifyFlowStatus(origin.getFlowId(), FlowStatus.IN_PROGRESS); FlowSegmentRequest speakerRequest; while ((speakerRequest = requests.poll()) != null) { produceAsyncResponse(service, speakerRequest); } Flow result = verifyFlowStatus(origin.getFlowId(), FlowStatus.UP); verifyPathReplace(origin, result); assertEquals(LATENCY, result.getPathComputationStrategy()); assertNull(result.getTargetPathComputationStrategy()); }
@Test public void shouldSkipRerouteOnOutdatedRequest() { Flow origin = makeFlow(); FlowRerouteService service = makeService(); IslEndpoint affectedEndpoint = extractIslEndpoint(origin); IslEndpoint notAffectedEndpoint = new IslEndpoint( affectedEndpoint.getSwitchId(), affectedEndpoint.getPortNumber() + 1); FlowRerouteRequest request = new FlowRerouteRequest(origin.getFlowId(), false, true, false, Collections.singleton(affectedEndpoint), null); service.handleRequest(currentRequestKey, request, commandContext); Flow result = verifyFlowStatus(origin.getFlowId(), FlowStatus.UP); verifyNoPathReplace(origin, result); }
@Test public void shouldMoveFlowToDegradedIfPathWithRequiredLatencyNotFound() throws Exception { Flow origin = makeFlow(); origin.setTargetPathComputationStrategy(MAX_LATENCY); setupFlowRepositorySpy().findById(origin.getFlowId()) .ifPresent(foundPath -> foundPath.setTargetPathComputationStrategy(MAX_LATENCY)); when(pathComputer.getPath(makeFlowArgumentMatch(origin.getFlowId()), any(Collection.class), eq(LATENCY))) .thenReturn(make3SwitchesPathPair(LATENCY)); FlowRerouteService service = makeService(); IslEndpoint affectedEndpoint = extractIslEndpoint(origin); FlowRerouteRequest request = new FlowRerouteRequest(origin.getFlowId(), false, true, false, Collections.singleton(affectedEndpoint), null); service.handleRequest(currentRequestKey, request, commandContext); verifyFlowStatus(origin.getFlowId(), FlowStatus.IN_PROGRESS); FlowSegmentRequest speakerRequest; while ((speakerRequest = requests.poll()) != null) { produceAsyncResponse(service, speakerRequest); } Flow result = verifyFlowStatus(origin.getFlowId(), FlowStatus.DEGRADED); verifyPathReplace(origin, result); assertEquals(MAX_LATENCY, result.getPathComputationStrategy()); assertNull(result.getTargetPathComputationStrategy()); }
|
FlowDeleteService { public void handleRequest(String key, CommandContext commandContext, String flowId) { log.debug("Handling flow delete request with key {} and flow ID: {}", key, flowId); if (fsms.containsKey(key)) { log.error("Attempt to create a FSM with key {}, while there's another active FSM with the same key.", key); return; } String eventKey = commandContext.getCorrelationId(); if (flowEventRepository.existsByTaskId(eventKey)) { log.error("Attempt to reuse key %s, but there's a history record(s) for it.", eventKey); return; } FlowDeleteFsm fsm = fsmFactory.newInstance(commandContext, flowId); fsms.put(key, fsm); fsmExecutor.fire(fsm, Event.NEXT, FlowDeleteContext.builder().build()); removeIfFinished(fsm, key); } FlowDeleteService(FlowDeleteHubCarrier carrier, PersistenceManager persistenceManager,
FlowResourcesManager flowResourcesManager,
int speakerCommandRetriesLimit); void handleRequest(String key, CommandContext commandContext, String flowId); void handleAsyncResponse(String key, SpeakerFlowSegmentResponse flowResponse); void handleTimeout(String key); }
|
@Test public void shouldFailDeleteFlowIfNoFlowFound() { String flowId = "dummy-flow"; FlowRepository repository = persistenceManager.getRepositoryFactory().createFlowRepository(); Assert.assertFalse(repository.findById(flowId).isPresent()); makeService().handleRequest(dummyRequestKey, commandContext, flowId); verifyNoSpeakerInteraction(carrier); verifyNorthboundErrorResponse(carrier, ErrorType.NOT_FOUND); }
@Test public void shouldFailDeleteFlowOnLockedFlow() { Flow flow = makeFlow(); setupFlowRepositorySpy().findById(flow.getFlowId()) .ifPresent(foundFlow -> foundFlow.setStatus(FlowStatus.IN_PROGRESS)); makeService().handleRequest(dummyRequestKey, commandContext, flow.getFlowId()); verifyNoSpeakerInteraction(carrier); verifyNorthboundErrorResponse(carrier, ErrorType.REQUEST_INVALID); verifyFlowStatus(flow.getFlowId(), FlowStatus.IN_PROGRESS); }
@Test public void shouldCompleteDeleteOnLockedSwitches() { String flowId = makeFlow().getFlowId(); FlowDeleteService service = makeService(); service.handleRequest(dummyRequestKey, commandContext, flowId); Flow flow = verifyFlowStatus(flowId, FlowStatus.IN_PROGRESS); verifyNorthboundSuccessResponse(carrier); produceSpeakerResponses(service); verify(carrier, times(4)).sendSpeakerRequest(any()); verifyFlowIsMissing(flow); }
@Test public void shouldCompleteDeleteOnErrorDuringCompletingFlowPathRemoval() { Flow target = makeFlow(); FlowPath forwardPath = target.getForwardPath(); Assert.assertNotNull(forwardPath); FlowPathRepository repository = setupFlowPathRepositorySpy(); doThrow(new RuntimeException(injectedErrorMessage)) .when(repository) .remove(eq(forwardPath.getPathId())); FlowDeleteService service = makeService(); service.handleRequest(dummyRequestKey, commandContext, target.getFlowId()); verifyFlowStatus(target.getFlowId(), FlowStatus.IN_PROGRESS); verifyNorthboundSuccessResponse(carrier); produceSpeakerResponses(service); verify(carrier, times(4)).sendSpeakerRequest(any()); verifyFlowIsMissing(target); }
@Test public void shouldCompleteDeleteOnErrorDuringResourceDeallocation() { Flow target = makeFlow(); FlowPath forwardPath = target.getForwardPath(); Assert.assertNotNull(forwardPath); doThrow(new RuntimeException(injectedErrorMessage)) .when(flowResourcesManager) .deallocatePathResources(MockitoHamcrest.argThat( Matchers.hasProperty("forward", Matchers.<PathResources>hasProperty("pathId", is(forwardPath.getPathId()))))); FlowDeleteService service = makeService(); service.handleRequest(dummyRequestKey, commandContext, target.getFlowId()); verifyFlowStatus(target.getFlowId(), FlowStatus.IN_PROGRESS); verifyNorthboundSuccessResponse(carrier); produceSpeakerResponses(service); verify(carrier, times(4)).sendSpeakerRequest(any()); verifyFlowIsMissing(target); }
@Test public void shouldCompleteDeleteOnErrorDuringRemovingFlow() { Flow target = makeFlow(); FlowRepository repository = setupFlowRepositorySpy(); doThrow(new RuntimeException(injectedErrorMessage)) .when(repository) .remove(eq(target.getFlowId())); FlowDeleteService service = makeService(); service.handleRequest(dummyRequestKey, commandContext, target.getFlowId()); verifyFlowStatus(target.getFlowId(), FlowStatus.IN_PROGRESS); verifyNorthboundSuccessResponse(carrier); verify(carrier, times(4)).sendSpeakerRequest(any()); produceSpeakerResponses(service); verifyFlowStatus(target.getFlowId(), FlowStatus.IN_PROGRESS); }
@Test public void shouldSuccessfullyDeleteFlow() { Flow target = makeFlow(); FlowDeleteService service = makeService(); service.handleRequest(dummyRequestKey, commandContext, target.getFlowId()); verifyFlowStatus(target.getFlowId(), FlowStatus.IN_PROGRESS); verifyNorthboundSuccessResponse(carrier); produceSpeakerResponses(service); verify(carrier, times(4)).sendSpeakerRequest(any()); verifyFlowIsMissing(target); }
|
RequestedFlowMapper { public RequestedFlow toRequestedFlow(FlowRequest request) { RequestedFlow flow = generatedMap(request); RequestedFlowIncrementalMapper.INSTANCE.mapSource(flow, request.getSource()); RequestedFlowIncrementalMapper.INSTANCE.mapDestination(flow, request.getDestination()); return flow; } RequestedFlow toRequestedFlow(FlowRequest request); @Mapping(source = "flowId", target = "flowId") @Mapping(target = "srcSwitch", expression = "java(flow.getSrcSwitchId())") @Mapping(source = "srcPort", target = "srcPort") @Mapping(source = "srcVlan", target = "srcVlan") @Mapping(target = "destSwitch", expression = "java(flow.getDestSwitchId())") @Mapping(source = "destPort", target = "destPort") @Mapping(source = "destVlan", target = "destVlan") @Mapping(source = "encapsulationType", target = "flowEncapsulationType") @Mapping(target = "diverseFlowId", ignore = true) abstract RequestedFlow toRequestedFlow(Flow flow); @Mapping(source = "flowId", target = "flowId") @Mapping(source = "sourceSwitch", target = "srcSwitch") @Mapping(source = "sourcePort", target = "srcPort") @Mapping(source = "sourceVlan", target = "srcVlan") @Mapping(source = "destinationSwitch", target = "destSwitch") @Mapping(source = "destinationPort", target = "destPort") @Mapping(source = "destinationVlan", target = "destVlan") @Mapping(target = "priority", ignore = true) @Mapping(target = "pinned", ignore = true) @Mapping(target = "allocateProtectedPath", ignore = true) @Mapping(target = "diverseFlowId", ignore = true) @Mapping(target = "description", ignore = true) @Mapping(target = "bandwidth", ignore = true) @Mapping(target = "ignoreBandwidth", ignore = true) @Mapping(target = "periodicPings", ignore = true) @Mapping(target = "maxLatency", ignore = true) @Mapping(target = "flowEncapsulationType", ignore = true) @Mapping(target = "pathComputationStrategy", ignore = true) @Mapping(target = "detectConnectedDevices", ignore = true) @Mapping(target = "srcWithMultiTable", ignore = true) @Mapping(target = "destWithMultiTable", ignore = true) @Mapping(target = "srcInnerVlan", ignore = true) @Mapping(target = "destInnerVlan", ignore = true) abstract RequestedFlow toRequestedFlow(SwapFlowDto flow); @Mapping(source = "flowId", target = "flowId") @Mapping(target = "srcSwitch", expression = "java(org.openkilda.model.Switch.builder().switchId(requestedFlow.getSrcSwitch()).build())") @Mapping(source = "srcPort", target = "srcPort") @Mapping(source = "srcVlan", target = "srcVlan") @Mapping(target = "destSwitch", expression = "java(org.openkilda.model.Switch.builder().switchId(requestedFlow.getDestSwitch()).build())") @Mapping(source = "destPort", target = "destPort") @Mapping(source = "destVlan", target = "destVlan") @Mapping(source = "flowEncapsulationType", target = "encapsulationType") @Mapping(target = "groupId", ignore = true) @Mapping(target = "status", ignore = true) @Mapping(target = "statusInfo", ignore = true) @Mapping(target = "targetPathComputationStrategy", ignore = true) abstract Flow toFlow(RequestedFlow requestedFlow); abstract FlowEncapsulationType map(org.openkilda.messaging.payload.flow.FlowEncapsulationType source); FlowEndpoint mapSource(RequestedFlow flow); FlowEndpoint mapDest(RequestedFlow flow); PathComputationStrategy mapComputationStrategy(String raw); @Mapping(target = "flowId", source = "flowId") @Mapping(target = "source", expression = "java(new FlowEndpoint(flow.getSrcSwitchId(), " + "flow.getSrcPort(), flow.getSrcVlan()))") @Mapping(target = "destination", expression = "java(new FlowEndpoint(flow.getDestSwitchId(), " + "flow.getDestPort(), flow.getDestVlan()))") @Mapping(target = "encapsulationType", source = "encapsulationType") @Mapping(target = "pathComputationStrategy", expression = "java(java.util.Optional.ofNullable(flow.getPathComputationStrategy())" + ".map(pcs -> pcs.toString().toLowerCase())" + ".orElse(null))") @Mapping(target = "bandwidth", source = "bandwidth") @Mapping(target = "ignoreBandwidth", source = "ignoreBandwidth") @Mapping(target = "periodicPings", source = "periodicPings") @Mapping(target = "allocateProtectedPath", source = "allocateProtectedPath") @Mapping(target = "description", source = "description") @Mapping(target = "maxLatency", source = "maxLatency") @Mapping(target = "priority", source = "priority") @Mapping(target = "pinned", source = "pinned") @Mapping(target = "detectConnectedDevices", source = "detectConnectedDevices") @Mapping(target = "transitEncapsulationId", ignore = true) @Mapping(target = "diverseFlowId", ignore = true) @Mapping(target = "type", ignore = true) @Mapping(target = "bulkUpdateFlowIds", ignore = true) @Mapping(target = "doNotRevert", ignore = true) abstract FlowRequest toFlowRequest(Flow flow); abstract DetectConnectedDevicesDto toDetectConnectedDevices(DetectConnectedDevices detectConnectedDevices); @Mapping(target = "flowId", source = "flowId") @Mapping(target = "source.datapath", source = "srcSwitch") @Mapping(target = "source.portNumber", source = "srcPort") @Mapping(target = "source.vlanId", source = "srcVlan") @Mapping(target = "source.innerVlanId", source = "srcInnerVlan") @Mapping(target = "destination.datapath", source = "destSwitch") @Mapping(target = "destination.portNumber", source = "destPort") @Mapping(target = "destination.vlanId", source = "destVlan") @Mapping(target = "destination.innerVlanId", source = "destInnerVlan") abstract ActivateFlowMonitoringInfoData toActivateFlowMonitoringInfoData(RequestedFlow flow); static final RequestedFlowMapper INSTANCE; }
|
@Test public void mapFlowRequestToRequestedFlowTest() { RequestedFlow requestedFlow = RequestedFlowMapper.INSTANCE.toRequestedFlow(flowRequest); assertEquals(FLOW_ID, requestedFlow.getFlowId()); assertEquals(SRC_SWITCH_ID, requestedFlow.getSrcSwitch()); assertEquals(SRC_PORT, requestedFlow.getSrcPort()); assertEquals(SRC_VLAN, requestedFlow.getSrcVlan()); assertEquals(SRC_INNER_VLAN, requestedFlow.getSrcInnerVlan()); assertEquals(DST_SWITCH_ID, requestedFlow.getDestSwitch()); assertEquals(DST_PORT, requestedFlow.getDestPort()); assertEquals(DST_VLAN, requestedFlow.getDestVlan()); assertEquals(DST_INNER_VLAN, requestedFlow.getDestInnerVlan()); assertEquals(PRIORITY, requestedFlow.getPriority()); assertEquals(DIVERSE_FLOW_ID, requestedFlow.getDiverseFlowId()); assertEquals(DESCRIPTION, requestedFlow.getDescription()); assertEquals(BANDWIDTH, requestedFlow.getBandwidth()); assertEquals(MAX_LATENCY, requestedFlow.getMaxLatency()); assertEquals(ENCAPSULATION_TYPE, requestedFlow.getFlowEncapsulationType()); assertTrue(requestedFlow.isPinned()); assertTrue(requestedFlow.isAllocateProtectedPath()); assertTrue(requestedFlow.isIgnoreBandwidth()); assertTrue(requestedFlow.isPeriodicPings()); assertEquals(new DetectConnectedDevices(true, true, true, true, true, true, true, true), requestedFlow.getDetectConnectedDevices()); }
@Test public void mapFlowRequestToRequestedFlow() { RequestedFlow result = RequestedFlowMapper.INSTANCE.toRequestedFlow(flowRequest); assertEquals(FLOW_ID, result.getFlowId()); assertEquals(SRC_SWITCH_ID, result.getSrcSwitch()); assertEquals(SRC_PORT, result.getSrcPort()); assertEquals(SRC_VLAN, result.getSrcVlan()); assertEquals(SRC_INNER_VLAN, result.getSrcInnerVlan()); assertEquals(DST_SWITCH_ID, result.getDestSwitch()); assertEquals(DST_PORT, result.getDestPort()); assertEquals(DST_VLAN, result.getDestVlan()); assertEquals(DST_INNER_VLAN, result.getDestInnerVlan()); assertEquals(PRIORITY, result.getPriority()); assertTrue(result.isPinned()); assertTrue(result.isAllocateProtectedPath()); assertEquals(DIVERSE_FLOW_ID, result.getDiverseFlowId()); assertEquals(DESCRIPTION, result.getDescription()); assertEquals(BANDWIDTH, result.getBandwidth()); assertTrue(result.isIgnoreBandwidth()); assertTrue(result.isPeriodicPings()); assertEquals(MAX_LATENCY, result.getMaxLatency()); assertEquals(ENCAPSULATION_TYPE, result.getFlowEncapsulationType()); assertEquals(PATH_COMPUTATION_STRATEGY, result.getPathComputationStrategy()); assertEquals( new DetectConnectedDevices(true, true, true, true, true, true, true, true), result.getDetectConnectedDevices()); assertFalse(result.isSrcWithMultiTable()); assertFalse(result.isDestWithMultiTable()); }
@Test public void mapSwapDtoToRequesterFlowTest() { SwapFlowDto swapFlowDto = SwapFlowDto.builder() .flowId(FLOW_ID) .sourceSwitch(SRC_SWITCH_ID) .sourcePort(SRC_PORT) .sourceVlan(SRC_VLAN) .destinationSwitch(DST_SWITCH_ID) .destinationPort(DST_PORT) .destinationVlan(DST_VLAN) .build(); RequestedFlow requestedFlow = RequestedFlowMapper.INSTANCE.toRequestedFlow(swapFlowDto); assertEquals(FLOW_ID, requestedFlow.getFlowId()); assertEquals(SRC_SWITCH_ID, requestedFlow.getSrcSwitch()); assertEquals(SRC_PORT, requestedFlow.getSrcPort()); assertEquals(SRC_VLAN, requestedFlow.getSrcVlan()); assertEquals(DST_SWITCH_ID, requestedFlow.getDestSwitch()); assertEquals(DST_PORT, requestedFlow.getDestPort()); assertEquals(DST_VLAN, requestedFlow.getDestVlan()); }
|
RequestedFlowMapper { @Mapping(target = "flowId", source = "flowId") @Mapping(target = "source", expression = "java(new FlowEndpoint(flow.getSrcSwitchId(), " + "flow.getSrcPort(), flow.getSrcVlan()))") @Mapping(target = "destination", expression = "java(new FlowEndpoint(flow.getDestSwitchId(), " + "flow.getDestPort(), flow.getDestVlan()))") @Mapping(target = "encapsulationType", source = "encapsulationType") @Mapping(target = "pathComputationStrategy", expression = "java(java.util.Optional.ofNullable(flow.getPathComputationStrategy())" + ".map(pcs -> pcs.toString().toLowerCase())" + ".orElse(null))") @Mapping(target = "bandwidth", source = "bandwidth") @Mapping(target = "ignoreBandwidth", source = "ignoreBandwidth") @Mapping(target = "periodicPings", source = "periodicPings") @Mapping(target = "allocateProtectedPath", source = "allocateProtectedPath") @Mapping(target = "description", source = "description") @Mapping(target = "maxLatency", source = "maxLatency") @Mapping(target = "priority", source = "priority") @Mapping(target = "pinned", source = "pinned") @Mapping(target = "detectConnectedDevices", source = "detectConnectedDevices") @Mapping(target = "transitEncapsulationId", ignore = true) @Mapping(target = "diverseFlowId", ignore = true) @Mapping(target = "type", ignore = true) @Mapping(target = "bulkUpdateFlowIds", ignore = true) @Mapping(target = "doNotRevert", ignore = true) public abstract FlowRequest toFlowRequest(Flow flow); RequestedFlow toRequestedFlow(FlowRequest request); @Mapping(source = "flowId", target = "flowId") @Mapping(target = "srcSwitch", expression = "java(flow.getSrcSwitchId())") @Mapping(source = "srcPort", target = "srcPort") @Mapping(source = "srcVlan", target = "srcVlan") @Mapping(target = "destSwitch", expression = "java(flow.getDestSwitchId())") @Mapping(source = "destPort", target = "destPort") @Mapping(source = "destVlan", target = "destVlan") @Mapping(source = "encapsulationType", target = "flowEncapsulationType") @Mapping(target = "diverseFlowId", ignore = true) abstract RequestedFlow toRequestedFlow(Flow flow); @Mapping(source = "flowId", target = "flowId") @Mapping(source = "sourceSwitch", target = "srcSwitch") @Mapping(source = "sourcePort", target = "srcPort") @Mapping(source = "sourceVlan", target = "srcVlan") @Mapping(source = "destinationSwitch", target = "destSwitch") @Mapping(source = "destinationPort", target = "destPort") @Mapping(source = "destinationVlan", target = "destVlan") @Mapping(target = "priority", ignore = true) @Mapping(target = "pinned", ignore = true) @Mapping(target = "allocateProtectedPath", ignore = true) @Mapping(target = "diverseFlowId", ignore = true) @Mapping(target = "description", ignore = true) @Mapping(target = "bandwidth", ignore = true) @Mapping(target = "ignoreBandwidth", ignore = true) @Mapping(target = "periodicPings", ignore = true) @Mapping(target = "maxLatency", ignore = true) @Mapping(target = "flowEncapsulationType", ignore = true) @Mapping(target = "pathComputationStrategy", ignore = true) @Mapping(target = "detectConnectedDevices", ignore = true) @Mapping(target = "srcWithMultiTable", ignore = true) @Mapping(target = "destWithMultiTable", ignore = true) @Mapping(target = "srcInnerVlan", ignore = true) @Mapping(target = "destInnerVlan", ignore = true) abstract RequestedFlow toRequestedFlow(SwapFlowDto flow); @Mapping(source = "flowId", target = "flowId") @Mapping(target = "srcSwitch", expression = "java(org.openkilda.model.Switch.builder().switchId(requestedFlow.getSrcSwitch()).build())") @Mapping(source = "srcPort", target = "srcPort") @Mapping(source = "srcVlan", target = "srcVlan") @Mapping(target = "destSwitch", expression = "java(org.openkilda.model.Switch.builder().switchId(requestedFlow.getDestSwitch()).build())") @Mapping(source = "destPort", target = "destPort") @Mapping(source = "destVlan", target = "destVlan") @Mapping(source = "flowEncapsulationType", target = "encapsulationType") @Mapping(target = "groupId", ignore = true) @Mapping(target = "status", ignore = true) @Mapping(target = "statusInfo", ignore = true) @Mapping(target = "targetPathComputationStrategy", ignore = true) abstract Flow toFlow(RequestedFlow requestedFlow); abstract FlowEncapsulationType map(org.openkilda.messaging.payload.flow.FlowEncapsulationType source); FlowEndpoint mapSource(RequestedFlow flow); FlowEndpoint mapDest(RequestedFlow flow); PathComputationStrategy mapComputationStrategy(String raw); @Mapping(target = "flowId", source = "flowId") @Mapping(target = "source", expression = "java(new FlowEndpoint(flow.getSrcSwitchId(), " + "flow.getSrcPort(), flow.getSrcVlan()))") @Mapping(target = "destination", expression = "java(new FlowEndpoint(flow.getDestSwitchId(), " + "flow.getDestPort(), flow.getDestVlan()))") @Mapping(target = "encapsulationType", source = "encapsulationType") @Mapping(target = "pathComputationStrategy", expression = "java(java.util.Optional.ofNullable(flow.getPathComputationStrategy())" + ".map(pcs -> pcs.toString().toLowerCase())" + ".orElse(null))") @Mapping(target = "bandwidth", source = "bandwidth") @Mapping(target = "ignoreBandwidth", source = "ignoreBandwidth") @Mapping(target = "periodicPings", source = "periodicPings") @Mapping(target = "allocateProtectedPath", source = "allocateProtectedPath") @Mapping(target = "description", source = "description") @Mapping(target = "maxLatency", source = "maxLatency") @Mapping(target = "priority", source = "priority") @Mapping(target = "pinned", source = "pinned") @Mapping(target = "detectConnectedDevices", source = "detectConnectedDevices") @Mapping(target = "transitEncapsulationId", ignore = true) @Mapping(target = "diverseFlowId", ignore = true) @Mapping(target = "type", ignore = true) @Mapping(target = "bulkUpdateFlowIds", ignore = true) @Mapping(target = "doNotRevert", ignore = true) abstract FlowRequest toFlowRequest(Flow flow); abstract DetectConnectedDevicesDto toDetectConnectedDevices(DetectConnectedDevices detectConnectedDevices); @Mapping(target = "flowId", source = "flowId") @Mapping(target = "source.datapath", source = "srcSwitch") @Mapping(target = "source.portNumber", source = "srcPort") @Mapping(target = "source.vlanId", source = "srcVlan") @Mapping(target = "source.innerVlanId", source = "srcInnerVlan") @Mapping(target = "destination.datapath", source = "destSwitch") @Mapping(target = "destination.portNumber", source = "destPort") @Mapping(target = "destination.vlanId", source = "destVlan") @Mapping(target = "destination.innerVlanId", source = "destInnerVlan") abstract ActivateFlowMonitoringInfoData toActivateFlowMonitoringInfoData(RequestedFlow flow); static final RequestedFlowMapper INSTANCE; }
|
@Test public void mapFlowToFlowRequestTest() { FlowRequest flowRequest = RequestedFlowMapper.INSTANCE.toFlowRequest(flow); assertEquals(FLOW_ID, flowRequest.getFlowId()); assertEquals(SRC_SWITCH_ID, flowRequest.getSource().getSwitchId()); assertEquals(SRC_PORT, (int) flowRequest.getSource().getPortNumber()); assertEquals(SRC_VLAN, flowRequest.getSource().getOuterVlanId()); assertEquals(DST_SWITCH_ID, flowRequest.getDestination().getSwitchId()); assertEquals(DST_PORT, (int) flowRequest.getDestination().getPortNumber()); assertEquals(DST_VLAN, flowRequest.getDestination().getOuterVlanId()); assertEquals(PRIORITY, flowRequest.getPriority()); assertEquals(DESCRIPTION, flowRequest.getDescription()); assertEquals(BANDWIDTH, flowRequest.getBandwidth()); assertEquals(MAX_LATENCY, flowRequest.getMaxLatency()); assertEquals(org.openkilda.messaging.payload.flow.FlowEncapsulationType.TRANSIT_VLAN, flowRequest.getEncapsulationType()); assertEquals(PATH_COMPUTATION_STRATEGY.toString().toLowerCase(), flowRequest.getPathComputationStrategy()); assertTrue(flowRequest.isPinned()); assertTrue(flowRequest.isAllocateProtectedPath()); assertTrue(flowRequest.isIgnoreBandwidth()); assertTrue(flowRequest.isPeriodicPings()); assertEquals(new DetectConnectedDevicesDto(true, true, true, true, true, true, true, true), flowRequest.getDetectConnectedDevices()); }
|
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); }
|
@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)); }
|
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); }
|
@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()); }
|
FlowPathBuilder { public boolean isSamePath(Path path, FlowPath flowPath) { if (!path.getSrcSwitchId().equals(flowPath.getSrcSwitchId()) || !path.getDestSwitchId().equals(flowPath.getDestSwitchId()) || path.getSegments().size() != flowPath.getSegments().size()) { return false; } Iterator<Segment> pathIt = path.getSegments().iterator(); Iterator<PathSegment> flowPathIt = flowPath.getSegments().iterator(); while (pathIt.hasNext() && flowPathIt.hasNext()) { Path.Segment pathSegment = pathIt.next(); PathSegment flowSegment = flowPathIt.next(); if (!pathSegment.getSrcSwitchId().equals(flowSegment.getSrcSwitchId()) || !pathSegment.getDestSwitchId().equals(flowSegment.getDestSwitchId()) || pathSegment.getSrcPort() != flowSegment.getSrcPort() || pathSegment.getDestPort() != flowSegment.getDestPort()) { return false; } } return true; } boolean isSamePath(Path path, FlowPath flowPath); boolean arePathsOverlapped(Path path, FlowPath flowPath); FlowPath buildFlowPath(Flow flow, PathResources pathResources, Path path, FlowSegmentCookie cookie,
boolean forceToIgnoreBandwidth); }
|
@Test public void shouldDetectSameSwitchPaths() { SwitchId switchId = new SwitchId(1); Switch switchEntity = Switch.builder().switchId(switchId).build(); Path path = Path.builder() .srcSwitchId(switchId) .destSwitchId(switchId) .segments(Collections.emptyList()) .build(); FlowPath flowPath = FlowPath.builder() .srcSwitch(switchEntity) .destSwitch(switchEntity) .pathId(new PathId("test_path_id")) .build(); assertTrue(builder.isSamePath(path, flowPath)); }
@Test public void shouldDetectNotSameSwitchPaths() { SwitchId switchId1 = new SwitchId(1); SwitchId switchId2 = new SwitchId(2); Switch switch2 = Switch.builder().switchId(switchId2).build(); Path path = Path.builder() .srcSwitchId(switchId1) .destSwitchId(switchId1) .segments(Collections.emptyList()) .build(); FlowPath flowPath = FlowPath.builder() .srcSwitch(switch2) .destSwitch(switch2) .pathId(new PathId("test_path_id")) .build(); assertFalse(builder.isSamePath(path, flowPath)); }
@Test public void shouldDetectSame2SwitchPaths() { SwitchId switchId1 = new SwitchId(1); Switch switch1 = Switch.builder().switchId(switchId1).build(); SwitchId switchId2 = new SwitchId(2); Switch switch2 = Switch.builder().switchId(switchId2).build(); Path path = Path.builder() .srcSwitchId(switchId1) .destSwitchId(switchId2) .segments(Collections.singletonList(Segment.builder() .srcSwitchId(switchId1) .srcPort(1) .destSwitchId(switchId2) .destPort(2) .build())) .build(); FlowPath flowPath = FlowPath.builder() .srcSwitch(switch1) .destSwitch(switch2) .pathId(new PathId("test_path_id")) .segments(Collections.singletonList(PathSegment.builder() .srcSwitch(switch1).srcPort(1).destSwitch(switch2).destPort(2).build())) .build(); assertTrue(builder.isSamePath(path, flowPath)); }
@Test public void shouldDetectDifferenceInPortsFor2SwitchPaths() { SwitchId switchId1 = new SwitchId(1); Switch switch1 = Switch.builder().switchId(switchId1).build(); SwitchId switchId2 = new SwitchId(2); Switch switch2 = Switch.builder().switchId(switchId2).build(); Path path = Path.builder() .srcSwitchId(switchId1) .destSwitchId(switchId2) .segments(Collections.singletonList(Segment.builder() .srcSwitchId(switchId1) .srcPort(1) .destSwitchId(switchId2) .destPort(2) .build())) .build(); FlowPath flowPath = FlowPath.builder() .srcSwitch(switch1) .destSwitch(switch2) .pathId(new PathId("test_path_id")) .segments(Collections.singletonList(PathSegment.builder() .srcSwitch(switch1).srcPort(2).destSwitch(switch2).destPort(3).build())) .build(); assertFalse(builder.isSamePath(path, flowPath)); }
@Test public void shouldDetectSame3SwitchPaths() { SwitchId switchId1 = new SwitchId(1); Switch switch1 = Switch.builder().switchId(switchId1).build(); SwitchId switchId2 = new SwitchId(2); Switch switch2 = Switch.builder().switchId(switchId2).build(); SwitchId switchId3 = new SwitchId(3); Switch switch3 = Switch.builder().switchId(switchId3).build(); Path path = Path.builder() .srcSwitchId(switchId1) .destSwitchId(switchId2) .segments(asList(Segment.builder() .srcSwitchId(switchId1) .srcPort(1) .destSwitchId(switchId3) .destPort(2) .build(), Segment.builder() .srcSwitchId(switchId3) .srcPort(1) .destSwitchId(switchId2) .destPort(2) .build())) .build(); FlowPath flowPath = FlowPath.builder() .srcSwitch(switch1) .destSwitch(switch2) .pathId(new PathId("test_path_id")) .segments(asList( PathSegment.builder().srcSwitch(switch1).srcPort(1).destSwitch(switch3).destPort(2).build(), PathSegment.builder().srcSwitch(switch3).srcPort(1).destSwitch(switch2).destPort(2).build())) .build(); assertTrue(builder.isSamePath(path, flowPath)); }
|
FlowPathBuilder { public FlowPath buildFlowPath(Flow flow, PathResources pathResources, Path path, FlowSegmentCookie cookie, boolean forceToIgnoreBandwidth) { Map<SwitchId, Switch> switches = new HashMap<>(); Map<SwitchId, SwitchProperties> switchProperties = new HashMap<>(); switches.put(flow.getSrcSwitchId(), flow.getSrcSwitch()); switches.put(flow.getDestSwitchId(), flow.getDestSwitch()); Switch srcSwitch = switches.get(path.getSrcSwitchId()); if (srcSwitch == null) { throw new IllegalArgumentException(format("Path %s has different end-point %s than flow %s", pathResources.getPathId(), path.getSrcSwitchId(), flow.getFlowId())); } Switch destSwitch = switches.get(path.getDestSwitchId()); if (destSwitch == null) { throw new IllegalArgumentException(format("Path %s has different end-point %s than flow %s", pathResources.getPathId(), path.getDestSwitchId(), flow.getFlowId())); } Optional<SwitchProperties> srcSwitchProperties = switchPropertiesRepository.findBySwitchId( flow.getSrcSwitchId()); DetectConnectedDevices.DetectConnectedDevicesBuilder detectConnectedDevices = flow.getDetectConnectedDevices().toBuilder(); if (srcSwitchProperties.isPresent()) { switchProperties.put(flow.getSrcSwitchId(), srcSwitchProperties.get()); flow.setSrcWithMultiTable(srcSwitchProperties.get().isMultiTable()); detectConnectedDevices.srcSwitchLldp(srcSwitchProperties.get().isSwitchLldp()); detectConnectedDevices.srcSwitchArp(srcSwitchProperties.get().isSwitchArp()); } Optional<SwitchProperties> dstSwitchProperties = switchPropertiesRepository.findBySwitchId( flow.getDestSwitchId()); if (dstSwitchProperties.isPresent()) { switchProperties.put(flow.getDestSwitchId(), dstSwitchProperties.get()); flow.setDestWithMultiTable(dstSwitchProperties.get().isMultiTable()); detectConnectedDevices.dstSwitchLldp(dstSwitchProperties.get().isSwitchLldp()); detectConnectedDevices.dstSwitchArp(dstSwitchProperties.get().isSwitchArp()); } flow.setDetectConnectedDevices(detectConnectedDevices.build()); FlowPath flowPath = FlowPath.builder() .pathId(pathResources.getPathId()) .srcSwitch(srcSwitch) .destSwitch(destSwitch) .meterId(pathResources.getMeterId()) .cookie(cookie) .bandwidth(flow.getBandwidth()) .ignoreBandwidth(flow.isIgnoreBandwidth() || forceToIgnoreBandwidth) .latency(path.getLatency()) .build(); List<PathSegment> segments = path.getSegments().stream() .map(segment -> { Switch segmentSrcSwitch = switches.get(segment.getSrcSwitchId()); if (segmentSrcSwitch == null) { segmentSrcSwitch = switchRepository.findById(segment.getSrcSwitchId()) .orElseThrow(() -> new IllegalArgumentException( format("Path %s has unknown end-point %s", pathResources.getPathId(), segment.getSrcSwitchId()))); switches.put(segment.getSrcSwitchId(), segmentSrcSwitch); } SwitchProperties segmentSrcSwitchProperties = switchProperties.get(segment.getSrcSwitchId()); if (segmentSrcSwitchProperties == null) { segmentSrcSwitchProperties = switchPropertiesRepository.findBySwitchId(segment.getSrcSwitchId()) .orElseThrow(() -> new IllegalArgumentException( format("Path %s has end-point %s without switch properties", pathResources.getPathId(), segment.getSrcSwitchId()))); switchProperties.put(segment.getSrcSwitchId(), segmentSrcSwitchProperties); } Switch segmentDestSwitch = switches.get(segment.getDestSwitchId()); if (segmentDestSwitch == null) { segmentDestSwitch = switchRepository.findById(segment.getDestSwitchId()) .orElseThrow(() -> new IllegalArgumentException( format("Path %s has unknown end-point %s", pathResources.getPathId(), segment.getDestSwitchId()))); switches.put(segment.getDestSwitchId(), segmentDestSwitch); } SwitchProperties segmentDstSwitchProperties = switchProperties.get(segment.getDestSwitchId()); if (segmentDstSwitchProperties == null) { segmentDstSwitchProperties = switchPropertiesRepository .findBySwitchId(segment.getDestSwitchId()) .orElseThrow(() -> new IllegalArgumentException( format("Path %s has end-point %s without switch properties", pathResources.getPathId(), segment.getDestSwitchId()))); switchProperties.put(segment.getDestSwitchId(), segmentDstSwitchProperties); } return PathSegment.builder() .srcSwitch(segmentSrcSwitch) .srcWithMultiTable(segmentSrcSwitchProperties.isMultiTable()) .srcPort(segment.getSrcPort()) .destSwitch(segmentDestSwitch) .destWithMultiTable(segmentDstSwitchProperties.isMultiTable()) .destPort(segment.getDestPort()) .latency(segment.getLatency()) .build(); }) .collect(Collectors.toList()); flowPath.setSegments(segments); return flowPath; } boolean isSamePath(Path path, FlowPath flowPath); boolean arePathsOverlapped(Path path, FlowPath flowPath); FlowPath buildFlowPath(Flow flow, PathResources pathResources, Path path, FlowSegmentCookie cookie,
boolean forceToIgnoreBandwidth); }
|
@Test public void shouldBuildFlowPathFor1SwitchPath() { SwitchId switchId = new SwitchId(1); Path path = Path.builder() .srcSwitchId(switchId) .destSwitchId(switchId) .segments(Collections.emptyList()) .build(); Flow flow = Flow.builder() .flowId("test_flow") .srcSwitch(Switch.builder().switchId(switchId).build()) .destSwitch(Switch.builder().switchId(switchId).build()) .build(); PathId pathId = new PathId("test_path_id"); MeterId meterId = new MeterId(MeterId.MIN_FLOW_METER_ID); PathResources pathResources = PathResources.builder() .pathId(pathId) .meterId(meterId) .build(); FlowSegmentCookie cookie = new FlowSegmentCookie(FlowPathDirection.FORWARD, 1); FlowPath flowPath = builder.buildFlowPath(flow, pathResources, path, cookie, false); assertEquals(pathId, flowPath.getPathId()); assertEquals(meterId, flowPath.getMeterId()); assertEquals(cookie, flowPath.getCookie()); assertThat(flowPath.getSegments(), empty()); }
@Test public void shouldBuildFlowPathFor2SwitchPath() { SwitchId switchId1 = new SwitchId(1); SwitchId switchId2 = new SwitchId(2); Path path = Path.builder() .srcSwitchId(switchId1) .destSwitchId(switchId2) .segments(Collections.singletonList(Segment.builder() .srcSwitchId(switchId1) .srcPort(1) .destSwitchId(switchId2) .destPort(2) .build())) .build(); Flow flow = Flow.builder() .flowId("test_flow") .srcSwitch(Switch.builder().switchId(switchId1).build()) .destSwitch(Switch.builder().switchId(switchId2).build()) .build(); PathId pathId = new PathId("test_path_id"); MeterId meterId = new MeterId(MeterId.MIN_FLOW_METER_ID); PathResources pathResources = PathResources.builder() .pathId(pathId) .meterId(meterId) .build(); FlowSegmentCookie cookie = new FlowSegmentCookie(FlowPathDirection.FORWARD, 1); FlowPath flowPath = builder.buildFlowPath(flow, pathResources, path, cookie, false); assertEquals(switchId1, flowPath.getSrcSwitchId()); assertEquals(switchId2, flowPath.getDestSwitchId()); assertEquals(pathId, flowPath.getPathId()); assertEquals(meterId, flowPath.getMeterId()); assertEquals(cookie, flowPath.getCookie()); assertThat(flowPath.getSegments(), hasSize(1)); }
@Test public void shouldBuildFlowPathFor3SwitchPath() { SwitchId switchId1 = new SwitchId(1); SwitchId switchId2 = new SwitchId(2); SwitchId switchId3 = new SwitchId(3); Path path = Path.builder() .srcSwitchId(switchId1) .destSwitchId(switchId2) .segments(asList(Segment.builder() .srcSwitchId(switchId1) .srcPort(1) .destSwitchId(switchId3) .destPort(2) .build(), Segment.builder() .srcSwitchId(switchId3) .srcPort(1) .destSwitchId(switchId2) .destPort(2) .build())) .build(); Flow flow = Flow.builder() .flowId("test_flow") .srcSwitch(Switch.builder().switchId(switchId1).build()) .destSwitch(Switch.builder().switchId(switchId2).build()) .build(); PathId pathId = new PathId("test_path_id"); MeterId meterId = new MeterId(MeterId.MIN_FLOW_METER_ID); PathResources pathResources = PathResources.builder() .pathId(pathId) .meterId(meterId) .build(); FlowSegmentCookie cookie = new FlowSegmentCookie(FlowPathDirection.FORWARD, 1); FlowPath flowPath = builder.buildFlowPath(flow, pathResources, path, cookie, false); assertEquals(switchId1, flowPath.getSrcSwitchId()); assertEquals(switchId2, flowPath.getDestSwitchId()); assertEquals(pathId, flowPath.getPathId()); assertEquals(meterId, flowPath.getMeterId()); assertEquals(cookie, flowPath.getCookie()); assertThat(flowPath.getSegments(), hasSize(2)); }
|
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); }
|
@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())); }
|
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); }
|
@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())); }
|
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); }
|
@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); }
|
IntersectionComputer { public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); } 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); }
|
@Test public void noGroupIntersections() { List<FlowPath> paths = getFlowPaths(); IntersectionComputer computer = new IntersectionComputer(FLOW_ID, PATH_ID, PATH_ID_REVERSE, paths); OverlappingSegmentsStats stats = computer.getOverlappingStats(); assertEquals(ZERO_STATS, stats); }
@Test public void noGroupIntersectionsInOneFlow() { List<FlowPath> paths = getFlowPaths(); paths.addAll(getFlowPaths(NEW_PATH_ID, NEW_PATH_ID_REVERSE, flow)); IntersectionComputer computer = new IntersectionComputer(FLOW_ID, PATH_ID, PATH_ID_REVERSE, paths); OverlappingSegmentsStats stats = computer.getOverlappingStats(); assertEquals(ZERO_STATS, stats); }
@Test public void shouldNoIntersections() { List<FlowPath> paths = getFlowPaths(); FlowPath path = FlowPath.builder() .pathId(NEW_PATH_ID) .srcSwitch(makeSwitch(SWITCH_ID_D)) .destSwitch(makeSwitch(SWITCH_ID_E)) .segments(Lists.newArrayList( buildPathSegment(SWITCH_ID_D, SWITCH_ID_E, 10, 10))) .build(); flow.addPaths(path); FlowPath revPath = FlowPath.builder() .pathId(NEW_PATH_ID_REVERSE) .srcSwitch(makeSwitch(SWITCH_ID_E)) .destSwitch(makeSwitch(SWITCH_ID_D)) .segments(Lists.newArrayList( buildPathSegment(SWITCH_ID_E, SWITCH_ID_D, 10, 10))) .build(); flow2.addPaths(revPath); paths.addAll(Lists.newArrayList(path, revPath)); IntersectionComputer computer = new IntersectionComputer(FLOW_ID, PATH_ID, PATH_ID_REVERSE, paths); OverlappingSegmentsStats stats = computer.getOverlappingStats(NEW_PATH_ID, NEW_PATH_ID_REVERSE); assertEquals(ZERO_STATS, stats); }
@Test public void shouldNotIntersectPathInSameFlow() { List<FlowPath> paths = getFlowPaths(); FlowPath newPath = FlowPath.builder() .pathId(NEW_PATH_ID) .srcSwitch(makeSwitch(SWITCH_ID_A)) .destSwitch(makeSwitch(SWITCH_ID_D)) .segments(Lists.newArrayList( buildPathSegment(SWITCH_ID_A, SWITCH_ID_D, 10, 10))) .build(); flow.addPaths(newPath); paths.add(newPath); IntersectionComputer computer = new IntersectionComputer(FLOW_ID, PATH_ID, PATH_ID_REVERSE, paths); OverlappingSegmentsStats stats = computer.getOverlappingStats(NEW_PATH_ID, NEW_PATH_ID_REVERSE); assertEquals(ZERO_STATS, stats); }
@Test public void shouldNotFailIfNoSegments() { IntersectionComputer computer = new IntersectionComputer(FLOW_ID, PATH_ID, PATH_ID_REVERSE, Collections.emptyList()); OverlappingSegmentsStats stats = computer.getOverlappingStats(NEW_PATH_ID, NEW_PATH_ID_REVERSE); assertEquals(ZERO_STATS, stats); }
@Test public void shouldNotFailIfNoIntersectionSegments() { List<FlowPath> paths = getFlowPaths(); IntersectionComputer computer = new IntersectionComputer(FLOW_ID, PATH_ID, PATH_ID_REVERSE, paths); OverlappingSegmentsStats stats = computer.getOverlappingStats(NEW_PATH_ID, NEW_PATH_ID_REVERSE); assertEquals(ZERO_STATS, stats); }
@Test public void switchIntersectionByPathId() { List<FlowPath> paths = getFlowPaths(); FlowPath newPath = FlowPath.builder() .pathId(NEW_PATH_ID) .srcSwitch(makeSwitch(SWITCH_ID_A)) .destSwitch(makeSwitch(SWITCH_ID_D)) .segments(Lists.newArrayList( buildPathSegment(SWITCH_ID_A, SWITCH_ID_D, 10, 10))) .build(); flow2.addPaths(newPath); paths.add(newPath); IntersectionComputer computer = new IntersectionComputer(FLOW_ID, PATH_ID, PATH_ID_REVERSE, paths); OverlappingSegmentsStats stats = computer.getOverlappingStats(NEW_PATH_ID, NEW_PATH_ID_REVERSE); assertEquals(new OverlappingSegmentsStats(0, 1, 0, 33), stats); }
@Test public void partialIntersection() { List<FlowPath> paths = getFlowPaths(); FlowPath newPath = FlowPath.builder() .pathId(NEW_PATH_ID) .srcSwitch(makeSwitch(SWITCH_ID_A)) .destSwitch(makeSwitch(SWITCH_ID_B)) .segments(Lists.newArrayList( buildPathSegment(SWITCH_ID_A, SWITCH_ID_B, 1, 1))) .build(); flow2.addPaths(newPath); paths.add(newPath); IntersectionComputer computer = new IntersectionComputer(FLOW_ID, PATH_ID, PATH_ID_REVERSE, paths); OverlappingSegmentsStats stats = computer.getOverlappingStats(NEW_PATH_ID, NEW_PATH_ID_REVERSE); assertEquals(new OverlappingSegmentsStats(1, 2, 50, 66), stats); }
@Test public void fullIntersection() { List<FlowPath> paths = getFlowPaths(); paths.addAll(getFlowPaths(NEW_PATH_ID, NEW_PATH_ID_REVERSE, flow2)); IntersectionComputer computer = new IntersectionComputer(FLOW_ID, PATH_ID, PATH_ID_REVERSE, paths); OverlappingSegmentsStats stats = computer.getOverlappingStats(NEW_PATH_ID, NEW_PATH_ID_REVERSE); assertEquals(new OverlappingSegmentsStats(2, 3, 100, 100), stats); }
|
LinkOperationsService { public Collection<Isl> updateEnableBfdFlag(Endpoint source, Endpoint destination, boolean flagValue) throws IslNotFoundException { return transactionManager.doInTransaction(() -> { List<Isl> processed = new ArrayList<>(2); boolean madeChange; madeChange = updateUniIslEnableBfdFlag(source, destination, flagValue, processed); madeChange |= updateUniIslEnableBfdFlag(destination, source, flagValue, processed); if (processed.size() != 2) { throw new IslNotFoundException(source, destination); } if (madeChange) { carrier.islBfdFlagChanged(processed.get(0)); } return processed; }); } 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); }
|
@Test public void shouldPropagateBfdEnableFlagUpdateOnFullUpdate() throws IslNotFoundException { createIsl(IslStatus.ACTIVE); Collection<Isl> result = linkOperationsService.updateEnableBfdFlag( Endpoint.of(TEST_SWITCH_A_ID, TEST_SWITCH_A_PORT), Endpoint.of(TEST_SWITCH_B_ID, TEST_SWITCH_B_PORT), true); Assert.assertEquals(2, result.size()); verifyBfdEnabledStatus(true); verify(carrier, times(1)).islBfdFlagChanged(any(Isl.class)); verifyNoMoreInteractions(carrier); reset(carrier); result = linkOperationsService.updateEnableBfdFlag( Endpoint.of(TEST_SWITCH_A_ID, TEST_SWITCH_A_PORT), Endpoint.of(TEST_SWITCH_B_ID, TEST_SWITCH_B_PORT), true); Assert.assertEquals(2, result.size()); verifyZeroInteractions(carrier); }
@Test public void shouldPropagateBfdEnableFlagUpdateOnPartialUpdate() throws IslNotFoundException { createIsl(IslStatus.ACTIVE); islRepository.findByEndpoints(TEST_SWITCH_A_ID, TEST_SWITCH_A_PORT, TEST_SWITCH_B_ID, TEST_SWITCH_B_PORT) .ifPresent(isl -> { isl.setEnableBfd(true); }); Collection<Isl> result = linkOperationsService.updateEnableBfdFlag( Endpoint.of(TEST_SWITCH_A_ID, TEST_SWITCH_A_PORT), Endpoint.of(TEST_SWITCH_B_ID, TEST_SWITCH_B_PORT), true); Assert.assertEquals(2, result.size()); verifyBfdEnabledStatus(true); verify(carrier, times(1)).islBfdFlagChanged(any(Isl.class)); verifyNoMoreInteractions(carrier); }
@Test(expected = IslNotFoundException.class) public void shouldFailIfThereIsNoIslForBfdEnableFlagUpdateRequest() throws IslNotFoundException { linkOperationsService.updateEnableBfdFlag( Endpoint.of(TEST_SWITCH_A_ID, TEST_SWITCH_A_PORT), Endpoint.of(TEST_SWITCH_B_ID, TEST_SWITCH_B_PORT), true); }
@Test(expected = IslNotFoundException.class) public void shouldFailIfThereIsUniIslOnlyForBfdEnableFlagUpdateRequest() throws IslNotFoundException { Isl isl = Isl.builder() .srcSwitch(createSwitchIfNotExist(TEST_SWITCH_A_ID)) .srcPort(TEST_SWITCH_A_PORT) .destSwitch(createSwitchIfNotExist(TEST_SWITCH_B_ID)) .destPort(TEST_SWITCH_B_PORT) .cost(0) .status(IslStatus.ACTIVE) .build(); islRepository.add(isl); linkOperationsService.updateEnableBfdFlag( Endpoint.of(TEST_SWITCH_A_ID, TEST_SWITCH_A_PORT), Endpoint.of(TEST_SWITCH_B_ID, TEST_SWITCH_B_PORT), true); }
|
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); }
|
@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)); }
|
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; }
|
@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); }
|
FlowMapper { @Mapping(source = "srcPort", target = "sourcePort") @Mapping(source = "srcVlan", target = "sourceVlan") @Mapping(source = "srcInnerVlan", target = "sourceInnerVlan") @Mapping(source = "destPort", target = "destinationPort") @Mapping(source = "destVlan", target = "destinationVlan") @Mapping(source = "destInnerVlan", target = "destinationInnerVlan") @Mapping(target = "sourceSwitch", expression = "java(flow.getSrcSwitchId())") @Mapping(target = "destinationSwitch", expression = "java(flow.getDestSwitchId())") @Mapping(source = "status", target = "state") @Mapping(source = "timeModify", target = "lastUpdated") @Mapping(source = "timeCreate", target = "createdTime") @Mapping(target = "flowStatusDetails", expression = "java(flow.isAllocateProtectedPath() ? " + "new FlowStatusDetails(flow.getMainFlowPrioritizedPathsStatus(), " + "flow.getProtectedFlowPrioritizedPathsStatus()) : null)") @Mapping(target = "cookie", ignore = true) @Mapping(target = "meterId", ignore = true) @Mapping(target = "transitEncapsulationId", ignore = true) @Mapping(target = "diverseWith", ignore = true) public abstract FlowDto map(Flow flow); @Mapping(source = "srcPort", target = "sourcePort") @Mapping(source = "srcVlan", target = "sourceVlan") @Mapping(source = "srcInnerVlan", target = "sourceInnerVlan") @Mapping(source = "destPort", target = "destinationPort") @Mapping(source = "destVlan", target = "destinationVlan") @Mapping(source = "destInnerVlan", target = "destinationInnerVlan") @Mapping(target = "sourceSwitch", expression = "java(flow.getSrcSwitchId())") @Mapping(target = "destinationSwitch", expression = "java(flow.getDestSwitchId())") @Mapping(source = "status", target = "state") @Mapping(source = "timeModify", target = "lastUpdated") @Mapping(source = "timeCreate", target = "createdTime") @Mapping(target = "flowStatusDetails", expression = "java(flow.isAllocateProtectedPath() ? " + "new FlowStatusDetails(flow.getMainFlowPrioritizedPathsStatus(), " + "flow.getProtectedFlowPrioritizedPathsStatus()) : null)") @Mapping(target = "cookie", ignore = true) @Mapping(target = "meterId", ignore = true) @Mapping(target = "transitEncapsulationId", ignore = true) @Mapping(target = "diverseWith", ignore = true) abstract FlowDto map(Flow flow); FlowDto map(Flow flow, Set<String> diverseWith); Flow map(FlowPairDto<FlowDto, FlowDto> flowPair, Supplier<KildaConfiguration> kildaConfiguration); Flow map(FlowDto flow, Supplier<KildaConfiguration> kildaConfiguration); Instant map(String value); String map(Instant value); FlowState map(FlowStatus status); FlowStatus map(FlowState status); org.openkilda.messaging.payload.flow.FlowEncapsulationType map(FlowEncapsulationType encapsulationType); Flow buildFlow(SwapFlowDto flow); static final FlowMapper INSTANCE; }
|
@Test public void testFlowPairToDto() { PathInfoData pathInfoData = new PathInfoData(); pathInfoData.setLatency(1L); pathInfoData.setPath(asList( new PathNode(SRC_SWITCH_ID, 1, 1, 1L, 1L), new PathNode(DST_SWITCH_ID, 2, 2, 2L, 2L) )); FlowDto forwardFlow = new FlowDto(); forwardFlow.setSourceSwitch(SRC_SWITCH_ID); forwardFlow.setDestinationSwitch(DST_SWITCH_ID); forwardFlow.setFlowId("12"); forwardFlow.setCookie(11); forwardFlow.setSourcePort(113); forwardFlow.setSourceVlan(1112); forwardFlow.setDestinationPort(113); forwardFlow.setDestinationVlan(1112); forwardFlow.setBandwidth(23); forwardFlow.setDescription("SOME FLOW"); forwardFlow.setLastUpdated("2011-12-03T10:15:30Z"); forwardFlow.setTransitEncapsulationId(87); forwardFlow.setMeterId(65); forwardFlow.setIgnoreBandwidth(true); forwardFlow.setPeriodicPings(true); forwardFlow.setEncapsulationType(FlowEncapsulationType.TRANSIT_VLAN); forwardFlow.setDetectConnectedDevices(new DetectConnectedDevicesDto( false, true, true, false, false, false, true, true)); PathInfoData reversePathInfoData = new PathInfoData(); reversePathInfoData.setLatency(1L); reversePathInfoData.setPath(asList( new PathNode(DST_SWITCH_ID, 2, 2, 2L, 2L), new PathNode(SRC_SWITCH_ID, 1, 1, 1L, 1L) )); FlowDto reverseFlow = new FlowDto(); reverseFlow.setSourceSwitch(forwardFlow.getDestinationSwitch()); reverseFlow.setDestinationSwitch(SRC_SWITCH_ID); reverseFlow.setFlowId("12"); reverseFlow.setCookie(12); reverseFlow.setSourcePort(113); reverseFlow.setSourceVlan(1112); reverseFlow.setDestinationPort(113); reverseFlow.setDestinationVlan(1112); reverseFlow.setBandwidth(23); reverseFlow.setDescription("SOME FLOW"); reverseFlow.setLastUpdated("2011-12-03T10:15:30Z"); reverseFlow.setTransitEncapsulationId(88); reverseFlow.setMeterId(66); reverseFlow.setIgnoreBandwidth(true); reverseFlow.setPeriodicPings(true); reverseFlow.setEncapsulationType(FlowEncapsulationType.TRANSIT_VLAN); reverseFlow.setDetectConnectedDevices(new DetectConnectedDevicesDto( true, false, false, true, false, false, true, true)); FlowPairDto<FlowDto, FlowDto> pair = new FlowPairDto<>(forwardFlow, reverseFlow); Flow p = FlowMapper.INSTANCE.map(pair, () -> KildaConfiguration.DEFAULTS); assertEquals(p.getFlowId(), pair.getLeft().getFlowId()); assertDetectConnectedDevices(forwardFlow.getDetectConnectedDevices(), p.getDetectConnectedDevices()); }
@Test public void testStatusDetailsMapping() { Flow flow = Flow.builder() .flowId("test_flow") .srcSwitch(Switch.builder().switchId(SRC_SWITCH_ID).build()) .destSwitch(Switch.builder().switchId(DST_SWITCH_ID).build()) .allocateProtectedPath(true) .build(); FlowPath forwardFlowPath = FlowPath.builder() .pathId(new PathId("forward_flow_path")) .srcSwitch(Switch.builder().switchId(SRC_SWITCH_ID).build()) .destSwitch(Switch.builder().switchId(DST_SWITCH_ID).build()) .cookie(new FlowSegmentCookie(FlowPathDirection.FORWARD, 1)) .status(FlowPathStatus.ACTIVE) .build(); flow.setForwardPath(forwardFlowPath); FlowPath reverseFlowPath = FlowPath.builder() .pathId(new PathId("reverse_flow_path")) .srcSwitch(Switch.builder().switchId(DST_SWITCH_ID).build()) .destSwitch(Switch.builder().switchId(SRC_SWITCH_ID).build()) .cookie(new FlowSegmentCookie(FlowPathDirection.REVERSE, 1)) .status(FlowPathStatus.ACTIVE) .build(); flow.setReversePath(reverseFlowPath); FlowPath forwardProtectedFlowPath = FlowPath.builder() .pathId(new PathId("forward_protected_flow_path")) .srcSwitch(Switch.builder().switchId(SRC_SWITCH_ID).build()) .destSwitch(Switch.builder().switchId(DST_SWITCH_ID).build()) .cookie(new FlowSegmentCookie(FlowPathDirection.FORWARD, 2)) .status(FlowPathStatus.INACTIVE) .build(); flow.setProtectedForwardPath(forwardProtectedFlowPath); FlowPath reverseProtectedFlowPath = FlowPath.builder() .pathId(new PathId("reverse_protected_flow_path")) .srcSwitch(Switch.builder().switchId(DST_SWITCH_ID).build()) .destSwitch(Switch.builder().switchId(SRC_SWITCH_ID).build()) .cookie(new FlowSegmentCookie(FlowPathDirection.REVERSE, 2)) .status(FlowPathStatus.INACTIVE) .build(); flow.setProtectedReversePath(reverseProtectedFlowPath); FlowDto flowDto = FlowMapper.INSTANCE.map(flow); assertNotNull(flowDto.getFlowStatusDetails()); assertEquals(FlowPathStatus.ACTIVE, flowDto.getFlowStatusDetails().getMainFlowPathStatus()); assertEquals(FlowPathStatus.INACTIVE, flowDto.getFlowStatusDetails().getProtectedFlowPathStatus()); assertDetectConnectedDevices(flowDto.getDetectConnectedDevices(), flow.getDetectConnectedDevices()); }
|
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; }
|
@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()); }
|
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); }
|
@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); }
|
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); }
|
@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); }
|
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); }
|
@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)); }); }
|
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); }
|
@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); }); }
|
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); }
|
@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); } }); }
|
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); }
|
@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(); }); }
|
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); }
|
@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); }); }
|
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); }
|
@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); } }); }
|
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); }
|
@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)); }); }
|
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); }
|
@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(); }); }
|
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(); }
|
@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()); }
|
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; }
|
@Test public void testNoviflowTimstampToLong() { long seconds = 123456789; long nanoseconds = 987654321; long timestampNovi = (seconds << 32) + nanoseconds; assertEquals(123456789_987654321L, noviflowTimestamp(timestampNovi)); }
|
RequestedFlowMapper { @Mapping(target = "flowId", source = "flowId") @Mapping(target = "source", expression = "java(new FlowEndpoint(flow.getSrcSwitchId(), " + "flow.getSrcPort(), flow.getSrcVlan()))") @Mapping(target = "destination", expression = "java(new FlowEndpoint(flow.getDestSwitchId(), " + "flow.getDestPort(), flow.getDestVlan()))") @Mapping(target = "encapsulationType", source = "encapsulationType") @Mapping(target = "pathComputationStrategy", expression = "java(java.util.Optional.ofNullable(flow.getPathComputationStrategy())" + ".map(pcs -> pcs.toString().toLowerCase())" + ".orElse(null))") @Mapping(target = "bandwidth", source = "bandwidth") @Mapping(target = "ignoreBandwidth", source = "ignoreBandwidth") @Mapping(target = "periodicPings", source = "periodicPings") @Mapping(target = "allocateProtectedPath", source = "allocateProtectedPath") @Mapping(target = "description", source = "description") @Mapping(target = "maxLatency", source = "maxLatency") @Mapping(target = "priority", source = "priority") @Mapping(target = "pinned", source = "pinned") @Mapping(target = "detectConnectedDevices", source = "detectConnectedDevices") @Mapping(target = "transitEncapsulationId", ignore = true) @Mapping(target = "diverseFlowId", ignore = true) @Mapping(target = "type", ignore = true) @Mapping(target = "bulkUpdateFlowIds", ignore = true) @Mapping(target = "doNotRevert", ignore = true) public abstract FlowRequest toFlowRequest(Flow flow); @Mapping(target = "flowId", source = "flowId") @Mapping(target = "source", expression = "java(new FlowEndpoint(flow.getSrcSwitchId(), " + "flow.getSrcPort(), flow.getSrcVlan()))") @Mapping(target = "destination", expression = "java(new FlowEndpoint(flow.getDestSwitchId(), " + "flow.getDestPort(), flow.getDestVlan()))") @Mapping(target = "encapsulationType", source = "encapsulationType") @Mapping(target = "pathComputationStrategy", expression = "java(java.util.Optional.ofNullable(flow.getPathComputationStrategy())" + ".map(pcs -> pcs.toString().toLowerCase())" + ".orElse(null))") @Mapping(target = "bandwidth", source = "bandwidth") @Mapping(target = "ignoreBandwidth", source = "ignoreBandwidth") @Mapping(target = "periodicPings", source = "periodicPings") @Mapping(target = "allocateProtectedPath", source = "allocateProtectedPath") @Mapping(target = "description", source = "description") @Mapping(target = "maxLatency", source = "maxLatency") @Mapping(target = "priority", source = "priority") @Mapping(target = "pinned", source = "pinned") @Mapping(target = "detectConnectedDevices", source = "detectConnectedDevices") @Mapping(target = "transitEncapsulationId", ignore = true) @Mapping(target = "diverseFlowId", ignore = true) @Mapping(target = "type", ignore = true) @Mapping(target = "bulkUpdateFlowIds", ignore = true) @Mapping(target = "doNotRevert", ignore = true) abstract FlowRequest toFlowRequest(Flow flow); static final RequestedFlowMapper INSTANCE; }
|
@Test public void mapFlowToFlowRequestTest() { FlowRequest flowRequest = RequestedFlowMapper.INSTANCE.toFlowRequest(flow); assertEquals(FLOW_ID, flowRequest.getFlowId()); assertEquals(SRC_SWITCH_ID, flowRequest.getSource().getSwitchId()); assertEquals(SRC_PORT, flowRequest.getSource().getPortNumber()); assertEquals(SRC_VLAN, flowRequest.getSource().getOuterVlanId()); assertEquals(DST_SWITCH_ID, flowRequest.getDestination().getSwitchId()); assertEquals(DST_PORT, flowRequest.getDestination().getPortNumber()); assertEquals(DST_VLAN, flowRequest.getDestination().getOuterVlanId()); assertEquals(PRIORITY, flowRequest.getPriority()); assertEquals(DESCRIPTION, flowRequest.getDescription()); assertEquals(BANDWIDTH, flowRequest.getBandwidth()); assertEquals(MAX_LATENCY, flowRequest.getMaxLatency()); assertEquals(org.openkilda.messaging.payload.flow.FlowEncapsulationType.TRANSIT_VLAN, flowRequest.getEncapsulationType()); assertEquals(PATH_COMPUTATION_STRATEGY, flowRequest.getPathComputationStrategy()); assertTrue(flowRequest.isPinned()); assertTrue(flowRequest.isAllocateProtectedPath()); assertTrue(flowRequest.isIgnoreBandwidth()); assertTrue(flowRequest.isPeriodicPings()); assertEquals(new DetectConnectedDevicesDto(true, true, true, true, true, true, true, true), flowRequest.getDetectConnectedDevices()); }
|
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); }
|
@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); }
|
FlowController extends BaseController { @ApiOperation(value = "Creates new flow", response = FlowResponsePayload.class) @PutMapping @ResponseStatus(HttpStatus.OK) public CompletableFuture<FlowResponsePayload> createFlow(@RequestBody FlowCreatePayload flow) { return flowService.createFlow(flow); } @ApiOperation(value = "Creates new flow", response = FlowResponsePayload.class) @PutMapping @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> createFlow(@RequestBody FlowCreatePayload flow); @ApiOperation(value = "Gets flow", response = FlowResponsePayload.class) @GetMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> getFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Deletes flow", response = FlowResponsePayload.class) @DeleteMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> deleteFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Updates flow", response = FlowResponsePayload.class) @PutMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> updateFlow(@PathVariable(name = "flow-id") String flowId,
@RequestBody FlowUpdatePayload flow); @ApiOperation(value = "Updates flow", response = FlowResponsePayload.class) @PatchMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> patchFlow(@PathVariable(name = "flow-id") String flowId,
@RequestBody FlowPatchDto flowPatchDto); @ApiOperation(value = "Dumps all flows", response = FlowResponsePayload.class, responseContainer = "List") @GetMapping @ResponseStatus(HttpStatus.OK) CompletableFuture<List<FlowResponsePayload>> getFlows(); @ApiOperation(value = "Delete all flows. Requires special authorization", response = FlowResponsePayload.class, responseContainer = "List") @DeleteMapping @ResponseStatus(HttpStatus.OK) @ExtraAuthRequired CompletableFuture<List<FlowResponsePayload>> deleteFlows(); @ApiOperation(value = "Gets flow status", response = FlowIdStatusPayload.class) @GetMapping(value = "/status/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowIdStatusPayload> statusFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Gets flow path", response = FlowPathPayload.class) @GetMapping(value = "/{flow-id}/path") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowPathPayload> pathFlow(@PathVariable(name = "flow-id") String flowId); @Deprecated @ApiOperation(value = "Push flows without expectation of modifying switches. It can push to switch and validate.", response = BatchResults.class) @PutMapping(path = "/push") @ResponseStatus(HttpStatus.OK) CompletableFuture<BatchResults> pushFlows(); @Deprecated @ApiOperation(value = "Unpush flows without expectation of modifying switches. It can push to switch and validate.", response = BatchResults.class) @PutMapping(path = "/unpush") @ResponseStatus(HttpStatus.OK) CompletableFuture<BatchResults> unpushFlows(); @ApiOperation(value = "Reroute flow", response = FlowReroutePayload.class) @PatchMapping(path = "/{flow_id}/reroute") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowReroutePayload> rerouteFlow(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Swap paths for flow with protected path", response = FlowResponsePayload.class) @PatchMapping(path = "/{flow_id}/swap") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> swapFlowPaths(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Sync flow", response = FlowReroutePayload.class) @ApiResponses(value = { @ApiResponse(code = 200, response = FlowReroutePayload.class, message = "Operation is successful")}) @PatchMapping(path = "/{flow_id}/sync") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowReroutePayload> syncFlow(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Validate flow, comparing the DB to each switch", response = FlowValidationDto.class, responseContainer = "List") @GetMapping(path = "/{flow_id}/validate") @ResponseStatus(HttpStatus.OK) CompletableFuture<List<FlowValidationDto>> validateFlow(@PathVariable("flow_id") String flowId); @ApiOperation( value = "Verify flow - using special network packet that is being routed in the same way as client traffic", response = PingOutput.class) @PutMapping(path = "/{flow_id}/ping") @ResponseStatus(HttpStatus.OK) CompletableFuture<PingOutput> pingFlow(
@RequestBody PingInput payload,
@PathVariable("flow_id") String flowId); @ApiOperation(value = "Invalidate (purge) Flow Resources Cache(s)") @DeleteMapping(path = "/cache") @ResponseStatus(HttpStatus.OK) void invalidateFlowCache(); @ApiOperation(value = "Update burst parameter in meter", response = FlowMeterEntries.class) @PatchMapping(path = "/{flow_id}/meters") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowMeterEntries> updateMetersBurst(@PathVariable("flow_id") String flowId); @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @ApiOperation(value = "Gets history for flow", response = FlowHistoryEntry.class, responseContainer = "List") @GetMapping(path = "/{flow_id}/history") CompletableFuture<ResponseEntity<List<FlowHistoryEntry>>> getHistory(
@PathVariable("flow_id") String flowId,
@ApiParam(value = "default: 0 (1 January 1970 00:00:00).")
@RequestParam(value = "timeFrom", required = false) Optional<Long> optionalTimeFrom,
@ApiParam(value = "default: now.")
@RequestParam(value = "timeTo", required = false) Optional<Long> optionalTimeTo,
@ApiParam(value = "Return at most N latest records. "
+ "Default: if `timeFrom` or/and `timeTo` parameters are presented default value of "
+ "`maxCount` is infinite (all records in time interval will be returned). "
+ "Otherwise default value of `maxCount` will be equal to 100. In This case response will contain "
+ "header 'Content-Range'.")
@RequestParam(value = "max_count", required = false) Optional<Integer> optionalMaxCount); @ApiOperation(value = "Gets flow connected devices", response = FlowConnectedDevicesResponse.class) @GetMapping(path = "/{flow_id}/devices") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowConnectedDevicesResponse> getConnectedDevices(
@PathVariable("flow_id") String flowId,
@ApiParam(value = "Device will be included in response if it's `time_last_seen` >= `since`. "
+ "Example of `since` value: `2019-09-30T16:14:12.538Z`",
required = false)
@RequestParam(value = "since", required = false) Optional<String> since); }
|
@Test @WithMockUser(username = USERNAME, password = PASSWORD, roles = ROLE) public void createFlow() throws Exception { MvcResult mvcResult = mockMvc.perform(put("/v1/flows") .header(CORRELATION_ID, testCorrelationId()) .contentType(APPLICATION_JSON_VALUE) .content(MAPPER.writeValueAsString(TestMessageMock.flow))) .andReturn(); MvcResult result = mockMvc.perform(asyncDispatch(mvcResult)) .andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON_UTF8_VALUE)) .andReturn(); System.out.println("RESPONSE: " + result.getResponse().getContentAsString()); FlowPayload response = MAPPER.readValue(result.getResponse().getContentAsString(), FlowPayload.class); assertEquals(TestMessageMock.flow, response); }
|
FlowController extends BaseController { @ApiOperation(value = "Gets flow", response = FlowResponsePayload.class) @GetMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) public CompletableFuture<FlowResponsePayload> getFlow(@PathVariable(name = "flow-id") String flowId) { return flowService.getFlow(flowId); } @ApiOperation(value = "Creates new flow", response = FlowResponsePayload.class) @PutMapping @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> createFlow(@RequestBody FlowCreatePayload flow); @ApiOperation(value = "Gets flow", response = FlowResponsePayload.class) @GetMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> getFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Deletes flow", response = FlowResponsePayload.class) @DeleteMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> deleteFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Updates flow", response = FlowResponsePayload.class) @PutMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> updateFlow(@PathVariable(name = "flow-id") String flowId,
@RequestBody FlowUpdatePayload flow); @ApiOperation(value = "Updates flow", response = FlowResponsePayload.class) @PatchMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> patchFlow(@PathVariable(name = "flow-id") String flowId,
@RequestBody FlowPatchDto flowPatchDto); @ApiOperation(value = "Dumps all flows", response = FlowResponsePayload.class, responseContainer = "List") @GetMapping @ResponseStatus(HttpStatus.OK) CompletableFuture<List<FlowResponsePayload>> getFlows(); @ApiOperation(value = "Delete all flows. Requires special authorization", response = FlowResponsePayload.class, responseContainer = "List") @DeleteMapping @ResponseStatus(HttpStatus.OK) @ExtraAuthRequired CompletableFuture<List<FlowResponsePayload>> deleteFlows(); @ApiOperation(value = "Gets flow status", response = FlowIdStatusPayload.class) @GetMapping(value = "/status/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowIdStatusPayload> statusFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Gets flow path", response = FlowPathPayload.class) @GetMapping(value = "/{flow-id}/path") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowPathPayload> pathFlow(@PathVariable(name = "flow-id") String flowId); @Deprecated @ApiOperation(value = "Push flows without expectation of modifying switches. It can push to switch and validate.", response = BatchResults.class) @PutMapping(path = "/push") @ResponseStatus(HttpStatus.OK) CompletableFuture<BatchResults> pushFlows(); @Deprecated @ApiOperation(value = "Unpush flows without expectation of modifying switches. It can push to switch and validate.", response = BatchResults.class) @PutMapping(path = "/unpush") @ResponseStatus(HttpStatus.OK) CompletableFuture<BatchResults> unpushFlows(); @ApiOperation(value = "Reroute flow", response = FlowReroutePayload.class) @PatchMapping(path = "/{flow_id}/reroute") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowReroutePayload> rerouteFlow(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Swap paths for flow with protected path", response = FlowResponsePayload.class) @PatchMapping(path = "/{flow_id}/swap") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> swapFlowPaths(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Sync flow", response = FlowReroutePayload.class) @ApiResponses(value = { @ApiResponse(code = 200, response = FlowReroutePayload.class, message = "Operation is successful")}) @PatchMapping(path = "/{flow_id}/sync") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowReroutePayload> syncFlow(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Validate flow, comparing the DB to each switch", response = FlowValidationDto.class, responseContainer = "List") @GetMapping(path = "/{flow_id}/validate") @ResponseStatus(HttpStatus.OK) CompletableFuture<List<FlowValidationDto>> validateFlow(@PathVariable("flow_id") String flowId); @ApiOperation( value = "Verify flow - using special network packet that is being routed in the same way as client traffic", response = PingOutput.class) @PutMapping(path = "/{flow_id}/ping") @ResponseStatus(HttpStatus.OK) CompletableFuture<PingOutput> pingFlow(
@RequestBody PingInput payload,
@PathVariable("flow_id") String flowId); @ApiOperation(value = "Invalidate (purge) Flow Resources Cache(s)") @DeleteMapping(path = "/cache") @ResponseStatus(HttpStatus.OK) void invalidateFlowCache(); @ApiOperation(value = "Update burst parameter in meter", response = FlowMeterEntries.class) @PatchMapping(path = "/{flow_id}/meters") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowMeterEntries> updateMetersBurst(@PathVariable("flow_id") String flowId); @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @ApiOperation(value = "Gets history for flow", response = FlowHistoryEntry.class, responseContainer = "List") @GetMapping(path = "/{flow_id}/history") CompletableFuture<ResponseEntity<List<FlowHistoryEntry>>> getHistory(
@PathVariable("flow_id") String flowId,
@ApiParam(value = "default: 0 (1 January 1970 00:00:00).")
@RequestParam(value = "timeFrom", required = false) Optional<Long> optionalTimeFrom,
@ApiParam(value = "default: now.")
@RequestParam(value = "timeTo", required = false) Optional<Long> optionalTimeTo,
@ApiParam(value = "Return at most N latest records. "
+ "Default: if `timeFrom` or/and `timeTo` parameters are presented default value of "
+ "`maxCount` is infinite (all records in time interval will be returned). "
+ "Otherwise default value of `maxCount` will be equal to 100. In This case response will contain "
+ "header 'Content-Range'.")
@RequestParam(value = "max_count", required = false) Optional<Integer> optionalMaxCount); @ApiOperation(value = "Gets flow connected devices", response = FlowConnectedDevicesResponse.class) @GetMapping(path = "/{flow_id}/devices") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowConnectedDevicesResponse> getConnectedDevices(
@PathVariable("flow_id") String flowId,
@ApiParam(value = "Device will be included in response if it's `time_last_seen` >= `since`. "
+ "Example of `since` value: `2019-09-30T16:14:12.538Z`",
required = false)
@RequestParam(value = "since", required = false) Optional<String> since); }
|
@Test @WithMockUser(username = USERNAME, password = PASSWORD, roles = ROLE) public void getFlow() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/v1/flows/{flow-id}", TestMessageMock.FLOW_ID) .header(CORRELATION_ID, testCorrelationId()) .contentType(APPLICATION_JSON_VALUE)) .andReturn(); MvcResult result = mockMvc.perform(asyncDispatch(mvcResult)) .andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON_UTF8_VALUE)) .andReturn(); FlowPayload response = MAPPER.readValue(result.getResponse().getContentAsString(), FlowPayload.class); assertEquals(TestMessageMock.flow, response); }
|
FlowController extends BaseController { @ApiOperation(value = "Deletes flow", response = FlowResponsePayload.class) @DeleteMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) public CompletableFuture<FlowResponsePayload> deleteFlow(@PathVariable(name = "flow-id") String flowId) { return flowService.deleteFlow(flowId); } @ApiOperation(value = "Creates new flow", response = FlowResponsePayload.class) @PutMapping @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> createFlow(@RequestBody FlowCreatePayload flow); @ApiOperation(value = "Gets flow", response = FlowResponsePayload.class) @GetMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> getFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Deletes flow", response = FlowResponsePayload.class) @DeleteMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> deleteFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Updates flow", response = FlowResponsePayload.class) @PutMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> updateFlow(@PathVariable(name = "flow-id") String flowId,
@RequestBody FlowUpdatePayload flow); @ApiOperation(value = "Updates flow", response = FlowResponsePayload.class) @PatchMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> patchFlow(@PathVariable(name = "flow-id") String flowId,
@RequestBody FlowPatchDto flowPatchDto); @ApiOperation(value = "Dumps all flows", response = FlowResponsePayload.class, responseContainer = "List") @GetMapping @ResponseStatus(HttpStatus.OK) CompletableFuture<List<FlowResponsePayload>> getFlows(); @ApiOperation(value = "Delete all flows. Requires special authorization", response = FlowResponsePayload.class, responseContainer = "List") @DeleteMapping @ResponseStatus(HttpStatus.OK) @ExtraAuthRequired CompletableFuture<List<FlowResponsePayload>> deleteFlows(); @ApiOperation(value = "Gets flow status", response = FlowIdStatusPayload.class) @GetMapping(value = "/status/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowIdStatusPayload> statusFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Gets flow path", response = FlowPathPayload.class) @GetMapping(value = "/{flow-id}/path") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowPathPayload> pathFlow(@PathVariable(name = "flow-id") String flowId); @Deprecated @ApiOperation(value = "Push flows without expectation of modifying switches. It can push to switch and validate.", response = BatchResults.class) @PutMapping(path = "/push") @ResponseStatus(HttpStatus.OK) CompletableFuture<BatchResults> pushFlows(); @Deprecated @ApiOperation(value = "Unpush flows without expectation of modifying switches. It can push to switch and validate.", response = BatchResults.class) @PutMapping(path = "/unpush") @ResponseStatus(HttpStatus.OK) CompletableFuture<BatchResults> unpushFlows(); @ApiOperation(value = "Reroute flow", response = FlowReroutePayload.class) @PatchMapping(path = "/{flow_id}/reroute") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowReroutePayload> rerouteFlow(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Swap paths for flow with protected path", response = FlowResponsePayload.class) @PatchMapping(path = "/{flow_id}/swap") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> swapFlowPaths(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Sync flow", response = FlowReroutePayload.class) @ApiResponses(value = { @ApiResponse(code = 200, response = FlowReroutePayload.class, message = "Operation is successful")}) @PatchMapping(path = "/{flow_id}/sync") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowReroutePayload> syncFlow(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Validate flow, comparing the DB to each switch", response = FlowValidationDto.class, responseContainer = "List") @GetMapping(path = "/{flow_id}/validate") @ResponseStatus(HttpStatus.OK) CompletableFuture<List<FlowValidationDto>> validateFlow(@PathVariable("flow_id") String flowId); @ApiOperation( value = "Verify flow - using special network packet that is being routed in the same way as client traffic", response = PingOutput.class) @PutMapping(path = "/{flow_id}/ping") @ResponseStatus(HttpStatus.OK) CompletableFuture<PingOutput> pingFlow(
@RequestBody PingInput payload,
@PathVariable("flow_id") String flowId); @ApiOperation(value = "Invalidate (purge) Flow Resources Cache(s)") @DeleteMapping(path = "/cache") @ResponseStatus(HttpStatus.OK) void invalidateFlowCache(); @ApiOperation(value = "Update burst parameter in meter", response = FlowMeterEntries.class) @PatchMapping(path = "/{flow_id}/meters") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowMeterEntries> updateMetersBurst(@PathVariable("flow_id") String flowId); @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @ApiOperation(value = "Gets history for flow", response = FlowHistoryEntry.class, responseContainer = "List") @GetMapping(path = "/{flow_id}/history") CompletableFuture<ResponseEntity<List<FlowHistoryEntry>>> getHistory(
@PathVariable("flow_id") String flowId,
@ApiParam(value = "default: 0 (1 January 1970 00:00:00).")
@RequestParam(value = "timeFrom", required = false) Optional<Long> optionalTimeFrom,
@ApiParam(value = "default: now.")
@RequestParam(value = "timeTo", required = false) Optional<Long> optionalTimeTo,
@ApiParam(value = "Return at most N latest records. "
+ "Default: if `timeFrom` or/and `timeTo` parameters are presented default value of "
+ "`maxCount` is infinite (all records in time interval will be returned). "
+ "Otherwise default value of `maxCount` will be equal to 100. In This case response will contain "
+ "header 'Content-Range'.")
@RequestParam(value = "max_count", required = false) Optional<Integer> optionalMaxCount); @ApiOperation(value = "Gets flow connected devices", response = FlowConnectedDevicesResponse.class) @GetMapping(path = "/{flow_id}/devices") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowConnectedDevicesResponse> getConnectedDevices(
@PathVariable("flow_id") String flowId,
@ApiParam(value = "Device will be included in response if it's `time_last_seen` >= `since`. "
+ "Example of `since` value: `2019-09-30T16:14:12.538Z`",
required = false)
@RequestParam(value = "since", required = false) Optional<String> since); }
|
@Test @WithMockUser(username = USERNAME, password = PASSWORD, roles = ROLE) public void deleteFlow() throws Exception { MvcResult mvcResult = mockMvc.perform(delete("/v1/flows/{flow-id}", TestMessageMock.FLOW_ID) .header(CORRELATION_ID, testCorrelationId()) .contentType(APPLICATION_JSON_VALUE)) .andReturn(); MvcResult result = mockMvc.perform(asyncDispatch(mvcResult)) .andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON_UTF8_VALUE)) .andReturn(); FlowPayload response = MAPPER.readValue(result.getResponse().getContentAsString(), FlowPayload.class); assertEquals(TestMessageMock.flow, response); }
|
FlowController extends BaseController { @ApiOperation(value = "Delete all flows. Requires special authorization", response = FlowResponsePayload.class, responseContainer = "List") @DeleteMapping @ResponseStatus(HttpStatus.OK) @ExtraAuthRequired public CompletableFuture<List<FlowResponsePayload>> deleteFlows() { return flowService.deleteAllFlows(); } @ApiOperation(value = "Creates new flow", response = FlowResponsePayload.class) @PutMapping @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> createFlow(@RequestBody FlowCreatePayload flow); @ApiOperation(value = "Gets flow", response = FlowResponsePayload.class) @GetMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> getFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Deletes flow", response = FlowResponsePayload.class) @DeleteMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> deleteFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Updates flow", response = FlowResponsePayload.class) @PutMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> updateFlow(@PathVariable(name = "flow-id") String flowId,
@RequestBody FlowUpdatePayload flow); @ApiOperation(value = "Updates flow", response = FlowResponsePayload.class) @PatchMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> patchFlow(@PathVariable(name = "flow-id") String flowId,
@RequestBody FlowPatchDto flowPatchDto); @ApiOperation(value = "Dumps all flows", response = FlowResponsePayload.class, responseContainer = "List") @GetMapping @ResponseStatus(HttpStatus.OK) CompletableFuture<List<FlowResponsePayload>> getFlows(); @ApiOperation(value = "Delete all flows. Requires special authorization", response = FlowResponsePayload.class, responseContainer = "List") @DeleteMapping @ResponseStatus(HttpStatus.OK) @ExtraAuthRequired CompletableFuture<List<FlowResponsePayload>> deleteFlows(); @ApiOperation(value = "Gets flow status", response = FlowIdStatusPayload.class) @GetMapping(value = "/status/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowIdStatusPayload> statusFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Gets flow path", response = FlowPathPayload.class) @GetMapping(value = "/{flow-id}/path") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowPathPayload> pathFlow(@PathVariable(name = "flow-id") String flowId); @Deprecated @ApiOperation(value = "Push flows without expectation of modifying switches. It can push to switch and validate.", response = BatchResults.class) @PutMapping(path = "/push") @ResponseStatus(HttpStatus.OK) CompletableFuture<BatchResults> pushFlows(); @Deprecated @ApiOperation(value = "Unpush flows without expectation of modifying switches. It can push to switch and validate.", response = BatchResults.class) @PutMapping(path = "/unpush") @ResponseStatus(HttpStatus.OK) CompletableFuture<BatchResults> unpushFlows(); @ApiOperation(value = "Reroute flow", response = FlowReroutePayload.class) @PatchMapping(path = "/{flow_id}/reroute") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowReroutePayload> rerouteFlow(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Swap paths for flow with protected path", response = FlowResponsePayload.class) @PatchMapping(path = "/{flow_id}/swap") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> swapFlowPaths(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Sync flow", response = FlowReroutePayload.class) @ApiResponses(value = { @ApiResponse(code = 200, response = FlowReroutePayload.class, message = "Operation is successful")}) @PatchMapping(path = "/{flow_id}/sync") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowReroutePayload> syncFlow(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Validate flow, comparing the DB to each switch", response = FlowValidationDto.class, responseContainer = "List") @GetMapping(path = "/{flow_id}/validate") @ResponseStatus(HttpStatus.OK) CompletableFuture<List<FlowValidationDto>> validateFlow(@PathVariable("flow_id") String flowId); @ApiOperation( value = "Verify flow - using special network packet that is being routed in the same way as client traffic", response = PingOutput.class) @PutMapping(path = "/{flow_id}/ping") @ResponseStatus(HttpStatus.OK) CompletableFuture<PingOutput> pingFlow(
@RequestBody PingInput payload,
@PathVariable("flow_id") String flowId); @ApiOperation(value = "Invalidate (purge) Flow Resources Cache(s)") @DeleteMapping(path = "/cache") @ResponseStatus(HttpStatus.OK) void invalidateFlowCache(); @ApiOperation(value = "Update burst parameter in meter", response = FlowMeterEntries.class) @PatchMapping(path = "/{flow_id}/meters") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowMeterEntries> updateMetersBurst(@PathVariable("flow_id") String flowId); @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @ApiOperation(value = "Gets history for flow", response = FlowHistoryEntry.class, responseContainer = "List") @GetMapping(path = "/{flow_id}/history") CompletableFuture<ResponseEntity<List<FlowHistoryEntry>>> getHistory(
@PathVariable("flow_id") String flowId,
@ApiParam(value = "default: 0 (1 January 1970 00:00:00).")
@RequestParam(value = "timeFrom", required = false) Optional<Long> optionalTimeFrom,
@ApiParam(value = "default: now.")
@RequestParam(value = "timeTo", required = false) Optional<Long> optionalTimeTo,
@ApiParam(value = "Return at most N latest records. "
+ "Default: if `timeFrom` or/and `timeTo` parameters are presented default value of "
+ "`maxCount` is infinite (all records in time interval will be returned). "
+ "Otherwise default value of `maxCount` will be equal to 100. In This case response will contain "
+ "header 'Content-Range'.")
@RequestParam(value = "max_count", required = false) Optional<Integer> optionalMaxCount); @ApiOperation(value = "Gets flow connected devices", response = FlowConnectedDevicesResponse.class) @GetMapping(path = "/{flow_id}/devices") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowConnectedDevicesResponse> getConnectedDevices(
@PathVariable("flow_id") String flowId,
@ApiParam(value = "Device will be included in response if it's `time_last_seen` >= `since`. "
+ "Example of `since` value: `2019-09-30T16:14:12.538Z`",
required = false)
@RequestParam(value = "since", required = false) Optional<String> since); }
|
@Test @WithMockUser(username = USERNAME, password = PASSWORD, roles = ROLE) public void deleteFlows() throws Exception { MvcResult mvcResult = mockMvc.perform(delete("/v1/flows") .header(CORRELATION_ID, testCorrelationId()) .header(EXTRA_AUTH, System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(119)) .contentType(APPLICATION_JSON_VALUE)) .andReturn(); MvcResult result = mockMvc.perform(asyncDispatch(mvcResult)) .andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON_UTF8_VALUE)) .andReturn(); FlowPayload[] response = MAPPER.readValue(result.getResponse().getContentAsString(), FlowPayload[].class); assertEquals(TestMessageMock.flow, response[0]); }
|
FlowController extends BaseController { @ApiOperation(value = "Updates flow", response = FlowResponsePayload.class) @PutMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) public CompletableFuture<FlowResponsePayload> updateFlow(@PathVariable(name = "flow-id") String flowId, @RequestBody FlowUpdatePayload flow) { return flowService.updateFlow(flow); } @ApiOperation(value = "Creates new flow", response = FlowResponsePayload.class) @PutMapping @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> createFlow(@RequestBody FlowCreatePayload flow); @ApiOperation(value = "Gets flow", response = FlowResponsePayload.class) @GetMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> getFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Deletes flow", response = FlowResponsePayload.class) @DeleteMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> deleteFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Updates flow", response = FlowResponsePayload.class) @PutMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> updateFlow(@PathVariable(name = "flow-id") String flowId,
@RequestBody FlowUpdatePayload flow); @ApiOperation(value = "Updates flow", response = FlowResponsePayload.class) @PatchMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> patchFlow(@PathVariable(name = "flow-id") String flowId,
@RequestBody FlowPatchDto flowPatchDto); @ApiOperation(value = "Dumps all flows", response = FlowResponsePayload.class, responseContainer = "List") @GetMapping @ResponseStatus(HttpStatus.OK) CompletableFuture<List<FlowResponsePayload>> getFlows(); @ApiOperation(value = "Delete all flows. Requires special authorization", response = FlowResponsePayload.class, responseContainer = "List") @DeleteMapping @ResponseStatus(HttpStatus.OK) @ExtraAuthRequired CompletableFuture<List<FlowResponsePayload>> deleteFlows(); @ApiOperation(value = "Gets flow status", response = FlowIdStatusPayload.class) @GetMapping(value = "/status/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowIdStatusPayload> statusFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Gets flow path", response = FlowPathPayload.class) @GetMapping(value = "/{flow-id}/path") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowPathPayload> pathFlow(@PathVariable(name = "flow-id") String flowId); @Deprecated @ApiOperation(value = "Push flows without expectation of modifying switches. It can push to switch and validate.", response = BatchResults.class) @PutMapping(path = "/push") @ResponseStatus(HttpStatus.OK) CompletableFuture<BatchResults> pushFlows(); @Deprecated @ApiOperation(value = "Unpush flows without expectation of modifying switches. It can push to switch and validate.", response = BatchResults.class) @PutMapping(path = "/unpush") @ResponseStatus(HttpStatus.OK) CompletableFuture<BatchResults> unpushFlows(); @ApiOperation(value = "Reroute flow", response = FlowReroutePayload.class) @PatchMapping(path = "/{flow_id}/reroute") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowReroutePayload> rerouteFlow(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Swap paths for flow with protected path", response = FlowResponsePayload.class) @PatchMapping(path = "/{flow_id}/swap") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> swapFlowPaths(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Sync flow", response = FlowReroutePayload.class) @ApiResponses(value = { @ApiResponse(code = 200, response = FlowReroutePayload.class, message = "Operation is successful")}) @PatchMapping(path = "/{flow_id}/sync") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowReroutePayload> syncFlow(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Validate flow, comparing the DB to each switch", response = FlowValidationDto.class, responseContainer = "List") @GetMapping(path = "/{flow_id}/validate") @ResponseStatus(HttpStatus.OK) CompletableFuture<List<FlowValidationDto>> validateFlow(@PathVariable("flow_id") String flowId); @ApiOperation( value = "Verify flow - using special network packet that is being routed in the same way as client traffic", response = PingOutput.class) @PutMapping(path = "/{flow_id}/ping") @ResponseStatus(HttpStatus.OK) CompletableFuture<PingOutput> pingFlow(
@RequestBody PingInput payload,
@PathVariable("flow_id") String flowId); @ApiOperation(value = "Invalidate (purge) Flow Resources Cache(s)") @DeleteMapping(path = "/cache") @ResponseStatus(HttpStatus.OK) void invalidateFlowCache(); @ApiOperation(value = "Update burst parameter in meter", response = FlowMeterEntries.class) @PatchMapping(path = "/{flow_id}/meters") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowMeterEntries> updateMetersBurst(@PathVariable("flow_id") String flowId); @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @ApiOperation(value = "Gets history for flow", response = FlowHistoryEntry.class, responseContainer = "List") @GetMapping(path = "/{flow_id}/history") CompletableFuture<ResponseEntity<List<FlowHistoryEntry>>> getHistory(
@PathVariable("flow_id") String flowId,
@ApiParam(value = "default: 0 (1 January 1970 00:00:00).")
@RequestParam(value = "timeFrom", required = false) Optional<Long> optionalTimeFrom,
@ApiParam(value = "default: now.")
@RequestParam(value = "timeTo", required = false) Optional<Long> optionalTimeTo,
@ApiParam(value = "Return at most N latest records. "
+ "Default: if `timeFrom` or/and `timeTo` parameters are presented default value of "
+ "`maxCount` is infinite (all records in time interval will be returned). "
+ "Otherwise default value of `maxCount` will be equal to 100. In This case response will contain "
+ "header 'Content-Range'.")
@RequestParam(value = "max_count", required = false) Optional<Integer> optionalMaxCount); @ApiOperation(value = "Gets flow connected devices", response = FlowConnectedDevicesResponse.class) @GetMapping(path = "/{flow_id}/devices") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowConnectedDevicesResponse> getConnectedDevices(
@PathVariable("flow_id") String flowId,
@ApiParam(value = "Device will be included in response if it's `time_last_seen` >= `since`. "
+ "Example of `since` value: `2019-09-30T16:14:12.538Z`",
required = false)
@RequestParam(value = "since", required = false) Optional<String> since); }
|
@Test @WithMockUser(username = USERNAME, password = PASSWORD, roles = ROLE) public void updateFlow() throws Exception { MvcResult mvcResult = mockMvc.perform(put("/v1/flows/{flow-id}", TestMessageMock.FLOW_ID) .header(CORRELATION_ID, testCorrelationId()) .contentType(APPLICATION_JSON_VALUE) .content(MAPPER.writeValueAsString(TestMessageMock.flow))) .andReturn(); MvcResult result = mockMvc.perform(asyncDispatch(mvcResult)) .andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON_UTF8_VALUE)) .andReturn(); FlowPayload response = MAPPER.readValue(result.getResponse().getContentAsString(), FlowPayload.class); assertEquals(TestMessageMock.flow, response); }
|
FlowController extends BaseController { @ApiOperation(value = "Dumps all flows", response = FlowResponsePayload.class, responseContainer = "List") @GetMapping @ResponseStatus(HttpStatus.OK) public CompletableFuture<List<FlowResponsePayload>> getFlows() { return flowService.getAllFlows(); } @ApiOperation(value = "Creates new flow", response = FlowResponsePayload.class) @PutMapping @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> createFlow(@RequestBody FlowCreatePayload flow); @ApiOperation(value = "Gets flow", response = FlowResponsePayload.class) @GetMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> getFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Deletes flow", response = FlowResponsePayload.class) @DeleteMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> deleteFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Updates flow", response = FlowResponsePayload.class) @PutMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> updateFlow(@PathVariable(name = "flow-id") String flowId,
@RequestBody FlowUpdatePayload flow); @ApiOperation(value = "Updates flow", response = FlowResponsePayload.class) @PatchMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> patchFlow(@PathVariable(name = "flow-id") String flowId,
@RequestBody FlowPatchDto flowPatchDto); @ApiOperation(value = "Dumps all flows", response = FlowResponsePayload.class, responseContainer = "List") @GetMapping @ResponseStatus(HttpStatus.OK) CompletableFuture<List<FlowResponsePayload>> getFlows(); @ApiOperation(value = "Delete all flows. Requires special authorization", response = FlowResponsePayload.class, responseContainer = "List") @DeleteMapping @ResponseStatus(HttpStatus.OK) @ExtraAuthRequired CompletableFuture<List<FlowResponsePayload>> deleteFlows(); @ApiOperation(value = "Gets flow status", response = FlowIdStatusPayload.class) @GetMapping(value = "/status/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowIdStatusPayload> statusFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Gets flow path", response = FlowPathPayload.class) @GetMapping(value = "/{flow-id}/path") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowPathPayload> pathFlow(@PathVariable(name = "flow-id") String flowId); @Deprecated @ApiOperation(value = "Push flows without expectation of modifying switches. It can push to switch and validate.", response = BatchResults.class) @PutMapping(path = "/push") @ResponseStatus(HttpStatus.OK) CompletableFuture<BatchResults> pushFlows(); @Deprecated @ApiOperation(value = "Unpush flows without expectation of modifying switches. It can push to switch and validate.", response = BatchResults.class) @PutMapping(path = "/unpush") @ResponseStatus(HttpStatus.OK) CompletableFuture<BatchResults> unpushFlows(); @ApiOperation(value = "Reroute flow", response = FlowReroutePayload.class) @PatchMapping(path = "/{flow_id}/reroute") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowReroutePayload> rerouteFlow(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Swap paths for flow with protected path", response = FlowResponsePayload.class) @PatchMapping(path = "/{flow_id}/swap") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> swapFlowPaths(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Sync flow", response = FlowReroutePayload.class) @ApiResponses(value = { @ApiResponse(code = 200, response = FlowReroutePayload.class, message = "Operation is successful")}) @PatchMapping(path = "/{flow_id}/sync") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowReroutePayload> syncFlow(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Validate flow, comparing the DB to each switch", response = FlowValidationDto.class, responseContainer = "List") @GetMapping(path = "/{flow_id}/validate") @ResponseStatus(HttpStatus.OK) CompletableFuture<List<FlowValidationDto>> validateFlow(@PathVariable("flow_id") String flowId); @ApiOperation( value = "Verify flow - using special network packet that is being routed in the same way as client traffic", response = PingOutput.class) @PutMapping(path = "/{flow_id}/ping") @ResponseStatus(HttpStatus.OK) CompletableFuture<PingOutput> pingFlow(
@RequestBody PingInput payload,
@PathVariable("flow_id") String flowId); @ApiOperation(value = "Invalidate (purge) Flow Resources Cache(s)") @DeleteMapping(path = "/cache") @ResponseStatus(HttpStatus.OK) void invalidateFlowCache(); @ApiOperation(value = "Update burst parameter in meter", response = FlowMeterEntries.class) @PatchMapping(path = "/{flow_id}/meters") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowMeterEntries> updateMetersBurst(@PathVariable("flow_id") String flowId); @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @ApiOperation(value = "Gets history for flow", response = FlowHistoryEntry.class, responseContainer = "List") @GetMapping(path = "/{flow_id}/history") CompletableFuture<ResponseEntity<List<FlowHistoryEntry>>> getHistory(
@PathVariable("flow_id") String flowId,
@ApiParam(value = "default: 0 (1 January 1970 00:00:00).")
@RequestParam(value = "timeFrom", required = false) Optional<Long> optionalTimeFrom,
@ApiParam(value = "default: now.")
@RequestParam(value = "timeTo", required = false) Optional<Long> optionalTimeTo,
@ApiParam(value = "Return at most N latest records. "
+ "Default: if `timeFrom` or/and `timeTo` parameters are presented default value of "
+ "`maxCount` is infinite (all records in time interval will be returned). "
+ "Otherwise default value of `maxCount` will be equal to 100. In This case response will contain "
+ "header 'Content-Range'.")
@RequestParam(value = "max_count", required = false) Optional<Integer> optionalMaxCount); @ApiOperation(value = "Gets flow connected devices", response = FlowConnectedDevicesResponse.class) @GetMapping(path = "/{flow_id}/devices") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowConnectedDevicesResponse> getConnectedDevices(
@PathVariable("flow_id") String flowId,
@ApiParam(value = "Device will be included in response if it's `time_last_seen` >= `since`. "
+ "Example of `since` value: `2019-09-30T16:14:12.538Z`",
required = false)
@RequestParam(value = "since", required = false) Optional<String> since); }
|
@Test @WithMockUser(username = USERNAME, password = PASSWORD, roles = ROLE) public void getFlows() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/v1/flows", TestMessageMock.FLOW_ID) .header(CORRELATION_ID, testCorrelationId()) .contentType(APPLICATION_JSON_VALUE)) .andReturn(); MvcResult result = mockMvc.perform(asyncDispatch(mvcResult)) .andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON_UTF8_VALUE)) .andReturn(); List<FlowPayload> response = MAPPER.readValue( result.getResponse().getContentAsString(), new TypeReference<List<FlowPayload>>() {}); assertEquals(Collections.singletonList(TestMessageMock.flow), response); }
|
FlowController extends BaseController { @ApiOperation(value = "Gets flow status", response = FlowIdStatusPayload.class) @GetMapping(value = "/status/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) public CompletableFuture<FlowIdStatusPayload> statusFlow(@PathVariable(name = "flow-id") String flowId) { return flowService.statusFlow(flowId); } @ApiOperation(value = "Creates new flow", response = FlowResponsePayload.class) @PutMapping @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> createFlow(@RequestBody FlowCreatePayload flow); @ApiOperation(value = "Gets flow", response = FlowResponsePayload.class) @GetMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> getFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Deletes flow", response = FlowResponsePayload.class) @DeleteMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> deleteFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Updates flow", response = FlowResponsePayload.class) @PutMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> updateFlow(@PathVariable(name = "flow-id") String flowId,
@RequestBody FlowUpdatePayload flow); @ApiOperation(value = "Updates flow", response = FlowResponsePayload.class) @PatchMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> patchFlow(@PathVariable(name = "flow-id") String flowId,
@RequestBody FlowPatchDto flowPatchDto); @ApiOperation(value = "Dumps all flows", response = FlowResponsePayload.class, responseContainer = "List") @GetMapping @ResponseStatus(HttpStatus.OK) CompletableFuture<List<FlowResponsePayload>> getFlows(); @ApiOperation(value = "Delete all flows. Requires special authorization", response = FlowResponsePayload.class, responseContainer = "List") @DeleteMapping @ResponseStatus(HttpStatus.OK) @ExtraAuthRequired CompletableFuture<List<FlowResponsePayload>> deleteFlows(); @ApiOperation(value = "Gets flow status", response = FlowIdStatusPayload.class) @GetMapping(value = "/status/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowIdStatusPayload> statusFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Gets flow path", response = FlowPathPayload.class) @GetMapping(value = "/{flow-id}/path") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowPathPayload> pathFlow(@PathVariable(name = "flow-id") String flowId); @Deprecated @ApiOperation(value = "Push flows without expectation of modifying switches. It can push to switch and validate.", response = BatchResults.class) @PutMapping(path = "/push") @ResponseStatus(HttpStatus.OK) CompletableFuture<BatchResults> pushFlows(); @Deprecated @ApiOperation(value = "Unpush flows without expectation of modifying switches. It can push to switch and validate.", response = BatchResults.class) @PutMapping(path = "/unpush") @ResponseStatus(HttpStatus.OK) CompletableFuture<BatchResults> unpushFlows(); @ApiOperation(value = "Reroute flow", response = FlowReroutePayload.class) @PatchMapping(path = "/{flow_id}/reroute") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowReroutePayload> rerouteFlow(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Swap paths for flow with protected path", response = FlowResponsePayload.class) @PatchMapping(path = "/{flow_id}/swap") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> swapFlowPaths(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Sync flow", response = FlowReroutePayload.class) @ApiResponses(value = { @ApiResponse(code = 200, response = FlowReroutePayload.class, message = "Operation is successful")}) @PatchMapping(path = "/{flow_id}/sync") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowReroutePayload> syncFlow(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Validate flow, comparing the DB to each switch", response = FlowValidationDto.class, responseContainer = "List") @GetMapping(path = "/{flow_id}/validate") @ResponseStatus(HttpStatus.OK) CompletableFuture<List<FlowValidationDto>> validateFlow(@PathVariable("flow_id") String flowId); @ApiOperation( value = "Verify flow - using special network packet that is being routed in the same way as client traffic", response = PingOutput.class) @PutMapping(path = "/{flow_id}/ping") @ResponseStatus(HttpStatus.OK) CompletableFuture<PingOutput> pingFlow(
@RequestBody PingInput payload,
@PathVariable("flow_id") String flowId); @ApiOperation(value = "Invalidate (purge) Flow Resources Cache(s)") @DeleteMapping(path = "/cache") @ResponseStatus(HttpStatus.OK) void invalidateFlowCache(); @ApiOperation(value = "Update burst parameter in meter", response = FlowMeterEntries.class) @PatchMapping(path = "/{flow_id}/meters") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowMeterEntries> updateMetersBurst(@PathVariable("flow_id") String flowId); @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @ApiOperation(value = "Gets history for flow", response = FlowHistoryEntry.class, responseContainer = "List") @GetMapping(path = "/{flow_id}/history") CompletableFuture<ResponseEntity<List<FlowHistoryEntry>>> getHistory(
@PathVariable("flow_id") String flowId,
@ApiParam(value = "default: 0 (1 January 1970 00:00:00).")
@RequestParam(value = "timeFrom", required = false) Optional<Long> optionalTimeFrom,
@ApiParam(value = "default: now.")
@RequestParam(value = "timeTo", required = false) Optional<Long> optionalTimeTo,
@ApiParam(value = "Return at most N latest records. "
+ "Default: if `timeFrom` or/and `timeTo` parameters are presented default value of "
+ "`maxCount` is infinite (all records in time interval will be returned). "
+ "Otherwise default value of `maxCount` will be equal to 100. In This case response will contain "
+ "header 'Content-Range'.")
@RequestParam(value = "max_count", required = false) Optional<Integer> optionalMaxCount); @ApiOperation(value = "Gets flow connected devices", response = FlowConnectedDevicesResponse.class) @GetMapping(path = "/{flow_id}/devices") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowConnectedDevicesResponse> getConnectedDevices(
@PathVariable("flow_id") String flowId,
@ApiParam(value = "Device will be included in response if it's `time_last_seen` >= `since`. "
+ "Example of `since` value: `2019-09-30T16:14:12.538Z`",
required = false)
@RequestParam(value = "since", required = false) Optional<String> since); }
|
@Test @WithMockUser(username = USERNAME, password = PASSWORD, roles = ROLE) public void statusFlow() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/v1/flows/status/{flow-id}", TestMessageMock.FLOW_ID) .header(CORRELATION_ID, testCorrelationId()) .contentType(APPLICATION_JSON_VALUE)) .andReturn(); MvcResult result = mockMvc.perform(asyncDispatch(mvcResult)) .andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON_UTF8_VALUE)) .andReturn(); FlowIdStatusPayload response = MAPPER.readValue(result.getResponse().getContentAsString(), FlowIdStatusPayload.class); assertEquals(TestMessageMock.flowStatus, response); }
|
FlowController extends BaseController { @ApiOperation(value = "Gets flow path", response = FlowPathPayload.class) @GetMapping(value = "/{flow-id}/path") @ResponseStatus(HttpStatus.OK) public CompletableFuture<FlowPathPayload> pathFlow(@PathVariable(name = "flow-id") String flowId) { return flowService.pathFlow(flowId); } @ApiOperation(value = "Creates new flow", response = FlowResponsePayload.class) @PutMapping @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> createFlow(@RequestBody FlowCreatePayload flow); @ApiOperation(value = "Gets flow", response = FlowResponsePayload.class) @GetMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> getFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Deletes flow", response = FlowResponsePayload.class) @DeleteMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> deleteFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Updates flow", response = FlowResponsePayload.class) @PutMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> updateFlow(@PathVariable(name = "flow-id") String flowId,
@RequestBody FlowUpdatePayload flow); @ApiOperation(value = "Updates flow", response = FlowResponsePayload.class) @PatchMapping(value = "/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> patchFlow(@PathVariable(name = "flow-id") String flowId,
@RequestBody FlowPatchDto flowPatchDto); @ApiOperation(value = "Dumps all flows", response = FlowResponsePayload.class, responseContainer = "List") @GetMapping @ResponseStatus(HttpStatus.OK) CompletableFuture<List<FlowResponsePayload>> getFlows(); @ApiOperation(value = "Delete all flows. Requires special authorization", response = FlowResponsePayload.class, responseContainer = "List") @DeleteMapping @ResponseStatus(HttpStatus.OK) @ExtraAuthRequired CompletableFuture<List<FlowResponsePayload>> deleteFlows(); @ApiOperation(value = "Gets flow status", response = FlowIdStatusPayload.class) @GetMapping(value = "/status/{flow-id:.+}") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowIdStatusPayload> statusFlow(@PathVariable(name = "flow-id") String flowId); @ApiOperation(value = "Gets flow path", response = FlowPathPayload.class) @GetMapping(value = "/{flow-id}/path") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowPathPayload> pathFlow(@PathVariable(name = "flow-id") String flowId); @Deprecated @ApiOperation(value = "Push flows without expectation of modifying switches. It can push to switch and validate.", response = BatchResults.class) @PutMapping(path = "/push") @ResponseStatus(HttpStatus.OK) CompletableFuture<BatchResults> pushFlows(); @Deprecated @ApiOperation(value = "Unpush flows without expectation of modifying switches. It can push to switch and validate.", response = BatchResults.class) @PutMapping(path = "/unpush") @ResponseStatus(HttpStatus.OK) CompletableFuture<BatchResults> unpushFlows(); @ApiOperation(value = "Reroute flow", response = FlowReroutePayload.class) @PatchMapping(path = "/{flow_id}/reroute") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowReroutePayload> rerouteFlow(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Swap paths for flow with protected path", response = FlowResponsePayload.class) @PatchMapping(path = "/{flow_id}/swap") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowResponsePayload> swapFlowPaths(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Sync flow", response = FlowReroutePayload.class) @ApiResponses(value = { @ApiResponse(code = 200, response = FlowReroutePayload.class, message = "Operation is successful")}) @PatchMapping(path = "/{flow_id}/sync") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowReroutePayload> syncFlow(@PathVariable("flow_id") String flowId); @ApiOperation(value = "Validate flow, comparing the DB to each switch", response = FlowValidationDto.class, responseContainer = "List") @GetMapping(path = "/{flow_id}/validate") @ResponseStatus(HttpStatus.OK) CompletableFuture<List<FlowValidationDto>> validateFlow(@PathVariable("flow_id") String flowId); @ApiOperation( value = "Verify flow - using special network packet that is being routed in the same way as client traffic", response = PingOutput.class) @PutMapping(path = "/{flow_id}/ping") @ResponseStatus(HttpStatus.OK) CompletableFuture<PingOutput> pingFlow(
@RequestBody PingInput payload,
@PathVariable("flow_id") String flowId); @ApiOperation(value = "Invalidate (purge) Flow Resources Cache(s)") @DeleteMapping(path = "/cache") @ResponseStatus(HttpStatus.OK) void invalidateFlowCache(); @ApiOperation(value = "Update burst parameter in meter", response = FlowMeterEntries.class) @PatchMapping(path = "/{flow_id}/meters") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowMeterEntries> updateMetersBurst(@PathVariable("flow_id") String flowId); @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @ApiOperation(value = "Gets history for flow", response = FlowHistoryEntry.class, responseContainer = "List") @GetMapping(path = "/{flow_id}/history") CompletableFuture<ResponseEntity<List<FlowHistoryEntry>>> getHistory(
@PathVariable("flow_id") String flowId,
@ApiParam(value = "default: 0 (1 January 1970 00:00:00).")
@RequestParam(value = "timeFrom", required = false) Optional<Long> optionalTimeFrom,
@ApiParam(value = "default: now.")
@RequestParam(value = "timeTo", required = false) Optional<Long> optionalTimeTo,
@ApiParam(value = "Return at most N latest records. "
+ "Default: if `timeFrom` or/and `timeTo` parameters are presented default value of "
+ "`maxCount` is infinite (all records in time interval will be returned). "
+ "Otherwise default value of `maxCount` will be equal to 100. In This case response will contain "
+ "header 'Content-Range'.")
@RequestParam(value = "max_count", required = false) Optional<Integer> optionalMaxCount); @ApiOperation(value = "Gets flow connected devices", response = FlowConnectedDevicesResponse.class) @GetMapping(path = "/{flow_id}/devices") @ResponseStatus(HttpStatus.OK) CompletableFuture<FlowConnectedDevicesResponse> getConnectedDevices(
@PathVariable("flow_id") String flowId,
@ApiParam(value = "Device will be included in response if it's `time_last_seen` >= `since`. "
+ "Example of `since` value: `2019-09-30T16:14:12.538Z`",
required = false)
@RequestParam(value = "since", required = false) Optional<String> since); }
|
@Test @WithMockUser(username = USERNAME, password = PASSWORD, roles = ROLE) public void pathFlow() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/v1/flows/{flow-id}/path", TestMessageMock.FLOW_ID) .header(CORRELATION_ID, testCorrelationId()) .contentType(APPLICATION_JSON_VALUE)) .andReturn(); MvcResult result = mockMvc.perform(asyncDispatch(mvcResult)) .andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON_UTF8_VALUE)) .andReturn(); FlowPathPayload response = MAPPER.readValue(result.getResponse().getContentAsString(), FlowPathPayload.class); assertEquals(TestMessageMock.flowPath, response); }
|
FlowMapper { @Mapping(target = "bandwidth", source = "maximumBandwidth") @Mapping(target = "detectConnectedDevices", expression = "java(new DetectConnectedDevicesDto(" + "request.getSource().getDetectConnectedDevices().isLldp(), " + "request.getSource().getDetectConnectedDevices().isArp(), " + "request.getDestination().getDetectConnectedDevices().isLldp(), " + "request.getDestination().getDetectConnectedDevices().isArp()))") @Mapping(target = "transitEncapsulationId", ignore = true) @Mapping(target = "type", ignore = true) @Mapping(target = "bulkUpdateFlowIds", ignore = true) @Mapping(target = "doNotRevert", ignore = true) @Mapping(target = "maxLatency", expression = "java(request.getMaxLatency() != null ? request.getMaxLatency() * 1000000L : null)") public abstract FlowRequest toFlowRequest(FlowRequestV2 request); FlowPayload toFlowOutput(FlowDto f); FlowResponsePayload toFlowResponseOutput(FlowDto f); FlowResponseV2 toFlowResponseV2(FlowDto flowDto); @Mapping(target = "flowId", ignore = true) @Mapping(target = "maxLatency", expression = "java(flowPatchDto.getMaxLatency() != null ? flowPatchDto.getMaxLatency() * 1000000L : null)") @Mapping(target = "priority", source = "priority") @Mapping(target = "periodicPings", source = "periodicPings") @Mapping(target = "targetPathComputationStrategy", source = "targetPathComputationStrategy") @Mapping(target = "source", ignore = true) @Mapping(target = "destination", ignore = true) @Mapping(target = "bandwidth", ignore = true) @Mapping(target = "allocateProtectedPath", ignore = true) @Mapping(target = "diverseFlowId", ignore = true) @Mapping(target = "pathComputationStrategy", ignore = true) @Mapping(target = "pinned", ignore = true) @Mapping(target = "ignoreBandwidth", ignore = true) @Mapping(target = "description", ignore = true) @Mapping(target = "encapsulationType", ignore = true) abstract FlowPatch toFlowPatch(FlowPatchDto flowPatchDto); @Mapping(target = "flowId", ignore = true) @Mapping(target = "bandwidth", source = "maximumBandwidth") @Mapping(target = "allocateProtectedPath", source = "allocateProtectedPath") @Mapping(target = "maxLatency", expression = "java(flowPatchDto.getMaxLatency() != null ? flowPatchDto.getMaxLatency() * 1000000L : null)") @Mapping(target = "priority", source = "priority") @Mapping(target = "periodicPings", source = "periodicPings") @Mapping(target = "diverseFlowId", source = "diverseFlowId") abstract FlowPatch toFlowPatch(FlowPatchV2 flowPatchDto); @Mapping(target = "trackLldpConnectedDevices", expression = "java(flowPatchEndpoint.getDetectConnectedDevices() != null ? " + "flowPatchEndpoint.getDetectConnectedDevices().isLldp() : null)") @Mapping(target = "trackArpConnectedDevices", expression = "java(flowPatchEndpoint.getDetectConnectedDevices() != null ? " + "flowPatchEndpoint.getDetectConnectedDevices().isArp() : null)") abstract PatchEndpoint toPatchEndpoint(FlowPatchEndpoint flowPatchEndpoint); @Mapping(target = "bandwidth", source = "maximumBandwidth") @Mapping(target = "detectConnectedDevices", expression = "java(new DetectConnectedDevicesDto(" + "request.getSource().getDetectConnectedDevices().isLldp(), " + "request.getSource().getDetectConnectedDevices().isArp(), " + "request.getDestination().getDetectConnectedDevices().isLldp(), " + "request.getDestination().getDetectConnectedDevices().isArp()))") @Mapping(target = "transitEncapsulationId", ignore = true) @Mapping(target = "type", ignore = true) @Mapping(target = "bulkUpdateFlowIds", ignore = true) @Mapping(target = "doNotRevert", ignore = true) @Mapping(target = "maxLatency", expression = "java(request.getMaxLatency() != null ? request.getMaxLatency() * 1000000L : null)") abstract FlowRequest toFlowRequest(FlowRequestV2 request); @Mapping(target = "flowId", source = "id") @Mapping(target = "bandwidth", source = "maximumBandwidth") @Mapping(target = "detectConnectedDevices", ignore = true) @Mapping(target = "transitEncapsulationId", ignore = true) @Mapping(target = "type", ignore = true) @Mapping(target = "bulkUpdateFlowIds", ignore = true) @Mapping(target = "doNotRevert", ignore = true) @Mapping(target = "diverseFlowId", ignore = true) @Mapping(target = "maxLatency", expression = "java(payload.getMaxLatency() != null ? payload.getMaxLatency() * 1000000L : null)") abstract FlowRequest toFlowRequest(FlowPayload payload); @Mapping(target = "outerVlanId", source = "vlanId") @Mapping(target = "trackLldpConnectedDevices", source = "detectConnectedDevices.lldp") @Mapping(target = "trackArpConnectedDevices", source = "detectConnectedDevices.arp") abstract FlowEndpoint mapFlowEndpoint(FlowEndpointV2 input); @Mapping(target = "switchId", source = "datapath") @Mapping(target = "outerVlanId", source = "vlanId") @Mapping(target = "trackLldpConnectedDevices", source = "detectConnectedDevices.lldp") @Mapping(target = "trackArpConnectedDevices", source = "detectConnectedDevices.arp") abstract FlowEndpoint mapFlowEndpoint(FlowEndpointPayload input); FlowRequest toFlowCreateRequest(FlowRequestV2 source); FlowRequest toFlowCreateRequest(FlowCreatePayload source); FlowRequest toFlowUpdateRequest(FlowUpdatePayload source); abstract PingOutput toPingOutput(FlowPingResponse response); @Mapping(source = "flowId", target = "id") @Mapping(source = "path", target = "path") @Mapping(source = "rerouted", target = "rerouted") abstract FlowReroutePayload toReroutePayload(String flowId, PathInfoData path, boolean rerouted); @Mapping(source = "path", target = "path") abstract FlowRerouteResponseV2 toRerouteResponseV2(String flowId, PathInfoData path, boolean rerouted); @Mapping(source = "path", target = "nodes") abstract FlowPathV2 toFlowPathV2(PathInfoData path); @Mapping(target = "segmentLatency", ignore = true) abstract FlowPathV2.PathNodeV2 toPathNodeV2(PathNode pathNode); @Mapping(source = "flowId", target = "id") @Mapping(source = "state", target = "status") abstract FlowIdStatusPayload toFlowIdStatusPayload(FlowDto flow); @Mapping(target = "latency", source = "meters.networkLatency") abstract UniFlowPingOutput toUniFlowPing(UniFlowPingResponse response); SwapFlowPayload toSwapOutput(FlowDto flowDto); @Mapping(target = "sourceSwitch", expression = "java(request.getSource().getSwitchId())") @Mapping(target = "destinationSwitch", expression = "java(request.getDestination().getSwitchId())") @Mapping(target = "sourcePort", expression = "java(request.getSource().getPortNumber())") @Mapping(target = "destinationPort", expression = "java(request.getDestination().getPortNumber())") @Mapping(target = "sourceVlan", expression = "java(request.getSource().getVlanId())") @Mapping(target = "destinationVlan", expression = "java(request.getDestination().getVlanId())") abstract SwapFlowDto toSwapFlowDto(SwapFlowPayload request); abstract FlowValidationDto toFlowValidationDto(FlowValidationResponse response); String encodeFlowState(FlowState state); @Mapping(target = "mainPath", source = "mainFlowPathStatus") @Mapping(target = "protectedPath", source = "protectedFlowPathStatus") abstract PathStatus map(FlowStatusDetails flowStatusDetails); String map(FlowPathStatus flowPathStatus); String map(FlowEncapsulationType encapsulationType); FlowEncapsulationType map(String encapsulationType); String map(PathComputationStrategy pathComputationStrategy); PathComputationStrategy mapPathComputationStrategy(String pathComputationStrategy); org.openkilda.model.FlowEncapsulationType mapEncapsulationType(String encapsulationType); String getPingError(Ping.Errors error); }
|
@Test public void testFlowRequestV2Mapping() { FlowRequestV2 flowRequestV2 = FlowRequestV2.builder() .flowId(FLOW_ID) .encapsulationType(ENCAPSULATION_TYPE) .source(new FlowEndpointV2(SRC_SWITCH_ID, SRC_PORT, SRC_VLAN, SRC_DETECT_CONNECTED_DEVICES)) .destination(new FlowEndpointV2(DST_SWITCH_ID, DST_PORT, DST_VLAN, DST_DETECT_CONNECTED_DEVICES)) .description(DESCRIPTION) .maximumBandwidth(BANDWIDTH) .maxLatency(LATENCY) .priority(PRIORITY) .diverseFlowId(DIVERSE_FLOW_ID) .build(); FlowRequest flowRequest = flowMapper.toFlowRequest(flowRequestV2); assertEquals(FLOW_ID, flowRequest.getFlowId()); assertEquals(SRC_SWITCH_ID, flowRequest.getSource().getSwitchId()); assertEquals(SRC_PORT, (int) flowRequest.getSource().getPortNumber()); assertEquals(SRC_VLAN, flowRequest.getSource().getOuterVlanId()); assertEquals(DST_SWITCH_ID, flowRequest.getDestination().getSwitchId()); assertEquals(DST_PORT, (int) flowRequest.getDestination().getPortNumber()); assertEquals(DST_VLAN, flowRequest.getDestination().getOuterVlanId()); assertEquals(FlowEncapsulationType.TRANSIT_VLAN, flowRequest.getEncapsulationType()); assertEquals(DESCRIPTION, flowRequest.getDescription()); assertEquals(BANDWIDTH, flowRequest.getBandwidth()); assertEquals(LATENCY * 1000000L, (long) flowRequest.getMaxLatency()); assertEquals(PRIORITY, flowRequest.getPriority()); assertEquals(DIVERSE_FLOW_ID, flowRequest.getDiverseFlowId()); assertEquals(SRC_DETECT_CONNECTED_DEVICES.isLldp(), flowRequest.getDetectConnectedDevices().isSrcLldp()); assertEquals(SRC_DETECT_CONNECTED_DEVICES.isArp(), flowRequest.getDetectConnectedDevices().isSrcArp()); assertEquals(DST_DETECT_CONNECTED_DEVICES.isLldp(), flowRequest.getDetectConnectedDevices().isDstLldp()); assertEquals(DST_DETECT_CONNECTED_DEVICES.isArp(), flowRequest.getDetectConnectedDevices().isDstArp()); }
@Test(expected = IllegalArgumentException.class) public void testFlowRequestV2InvalidEncapsulation() { FlowRequestV2 flowRequestV2 = FlowRequestV2.builder() .flowId(FLOW_ID) .encapsulationType("abc") .source(new FlowEndpointV2(SRC_SWITCH_ID, SRC_PORT, SRC_VLAN, SRC_DETECT_CONNECTED_DEVICES)) .destination(new FlowEndpointV2(DST_SWITCH_ID, DST_PORT, DST_VLAN, DST_DETECT_CONNECTED_DEVICES)) .build(); flowMapper.toFlowRequest(flowRequestV2); }
|
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(); }
|
@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)); }
|
FlowMapper { public FlowRequest toFlowCreateRequest(FlowRequestV2 source) { return toFlowRequest(source).toBuilder().type(Type.CREATE).build(); } FlowPayload toFlowOutput(FlowDto f); FlowResponsePayload toFlowResponseOutput(FlowDto f); FlowResponseV2 toFlowResponseV2(FlowDto flowDto); @Mapping(target = "flowId", ignore = true) @Mapping(target = "maxLatency", expression = "java(flowPatchDto.getMaxLatency() != null ? flowPatchDto.getMaxLatency() * 1000000L : null)") @Mapping(target = "priority", source = "priority") @Mapping(target = "periodicPings", source = "periodicPings") @Mapping(target = "targetPathComputationStrategy", source = "targetPathComputationStrategy") @Mapping(target = "source", ignore = true) @Mapping(target = "destination", ignore = true) @Mapping(target = "bandwidth", ignore = true) @Mapping(target = "allocateProtectedPath", ignore = true) @Mapping(target = "diverseFlowId", ignore = true) @Mapping(target = "pathComputationStrategy", ignore = true) @Mapping(target = "pinned", ignore = true) @Mapping(target = "ignoreBandwidth", ignore = true) @Mapping(target = "description", ignore = true) @Mapping(target = "encapsulationType", ignore = true) abstract FlowPatch toFlowPatch(FlowPatchDto flowPatchDto); @Mapping(target = "flowId", ignore = true) @Mapping(target = "bandwidth", source = "maximumBandwidth") @Mapping(target = "allocateProtectedPath", source = "allocateProtectedPath") @Mapping(target = "maxLatency", expression = "java(flowPatchDto.getMaxLatency() != null ? flowPatchDto.getMaxLatency() * 1000000L : null)") @Mapping(target = "priority", source = "priority") @Mapping(target = "periodicPings", source = "periodicPings") @Mapping(target = "diverseFlowId", source = "diverseFlowId") abstract FlowPatch toFlowPatch(FlowPatchV2 flowPatchDto); @Mapping(target = "trackLldpConnectedDevices", expression = "java(flowPatchEndpoint.getDetectConnectedDevices() != null ? " + "flowPatchEndpoint.getDetectConnectedDevices().isLldp() : null)") @Mapping(target = "trackArpConnectedDevices", expression = "java(flowPatchEndpoint.getDetectConnectedDevices() != null ? " + "flowPatchEndpoint.getDetectConnectedDevices().isArp() : null)") abstract PatchEndpoint toPatchEndpoint(FlowPatchEndpoint flowPatchEndpoint); @Mapping(target = "bandwidth", source = "maximumBandwidth") @Mapping(target = "detectConnectedDevices", expression = "java(new DetectConnectedDevicesDto(" + "request.getSource().getDetectConnectedDevices().isLldp(), " + "request.getSource().getDetectConnectedDevices().isArp(), " + "request.getDestination().getDetectConnectedDevices().isLldp(), " + "request.getDestination().getDetectConnectedDevices().isArp()))") @Mapping(target = "transitEncapsulationId", ignore = true) @Mapping(target = "type", ignore = true) @Mapping(target = "bulkUpdateFlowIds", ignore = true) @Mapping(target = "doNotRevert", ignore = true) @Mapping(target = "maxLatency", expression = "java(request.getMaxLatency() != null ? request.getMaxLatency() * 1000000L : null)") abstract FlowRequest toFlowRequest(FlowRequestV2 request); @Mapping(target = "flowId", source = "id") @Mapping(target = "bandwidth", source = "maximumBandwidth") @Mapping(target = "detectConnectedDevices", ignore = true) @Mapping(target = "transitEncapsulationId", ignore = true) @Mapping(target = "type", ignore = true) @Mapping(target = "bulkUpdateFlowIds", ignore = true) @Mapping(target = "doNotRevert", ignore = true) @Mapping(target = "diverseFlowId", ignore = true) @Mapping(target = "maxLatency", expression = "java(payload.getMaxLatency() != null ? payload.getMaxLatency() * 1000000L : null)") abstract FlowRequest toFlowRequest(FlowPayload payload); @Mapping(target = "outerVlanId", source = "vlanId") @Mapping(target = "trackLldpConnectedDevices", source = "detectConnectedDevices.lldp") @Mapping(target = "trackArpConnectedDevices", source = "detectConnectedDevices.arp") abstract FlowEndpoint mapFlowEndpoint(FlowEndpointV2 input); @Mapping(target = "switchId", source = "datapath") @Mapping(target = "outerVlanId", source = "vlanId") @Mapping(target = "trackLldpConnectedDevices", source = "detectConnectedDevices.lldp") @Mapping(target = "trackArpConnectedDevices", source = "detectConnectedDevices.arp") abstract FlowEndpoint mapFlowEndpoint(FlowEndpointPayload input); FlowRequest toFlowCreateRequest(FlowRequestV2 source); FlowRequest toFlowCreateRequest(FlowCreatePayload source); FlowRequest toFlowUpdateRequest(FlowUpdatePayload source); abstract PingOutput toPingOutput(FlowPingResponse response); @Mapping(source = "flowId", target = "id") @Mapping(source = "path", target = "path") @Mapping(source = "rerouted", target = "rerouted") abstract FlowReroutePayload toReroutePayload(String flowId, PathInfoData path, boolean rerouted); @Mapping(source = "path", target = "path") abstract FlowRerouteResponseV2 toRerouteResponseV2(String flowId, PathInfoData path, boolean rerouted); @Mapping(source = "path", target = "nodes") abstract FlowPathV2 toFlowPathV2(PathInfoData path); @Mapping(target = "segmentLatency", ignore = true) abstract FlowPathV2.PathNodeV2 toPathNodeV2(PathNode pathNode); @Mapping(source = "flowId", target = "id") @Mapping(source = "state", target = "status") abstract FlowIdStatusPayload toFlowIdStatusPayload(FlowDto flow); @Mapping(target = "latency", source = "meters.networkLatency") abstract UniFlowPingOutput toUniFlowPing(UniFlowPingResponse response); SwapFlowPayload toSwapOutput(FlowDto flowDto); @Mapping(target = "sourceSwitch", expression = "java(request.getSource().getSwitchId())") @Mapping(target = "destinationSwitch", expression = "java(request.getDestination().getSwitchId())") @Mapping(target = "sourcePort", expression = "java(request.getSource().getPortNumber())") @Mapping(target = "destinationPort", expression = "java(request.getDestination().getPortNumber())") @Mapping(target = "sourceVlan", expression = "java(request.getSource().getVlanId())") @Mapping(target = "destinationVlan", expression = "java(request.getDestination().getVlanId())") abstract SwapFlowDto toSwapFlowDto(SwapFlowPayload request); abstract FlowValidationDto toFlowValidationDto(FlowValidationResponse response); String encodeFlowState(FlowState state); @Mapping(target = "mainPath", source = "mainFlowPathStatus") @Mapping(target = "protectedPath", source = "protectedFlowPathStatus") abstract PathStatus map(FlowStatusDetails flowStatusDetails); String map(FlowPathStatus flowPathStatus); String map(FlowEncapsulationType encapsulationType); FlowEncapsulationType map(String encapsulationType); String map(PathComputationStrategy pathComputationStrategy); PathComputationStrategy mapPathComputationStrategy(String pathComputationStrategy); org.openkilda.model.FlowEncapsulationType mapEncapsulationType(String encapsulationType); String getPingError(Ping.Errors error); }
|
@Test public void testFlowCreatePayloadToFlowRequest() { FlowRequest flowRequest = flowMapper.toFlowCreateRequest(FLOW_CREATE_PAYLOAD); assertEquals(FLOW_CREATE_PAYLOAD.getDiverseFlowId(), flowRequest.getDiverseFlowId()); assertEquals(Type.CREATE, flowRequest.getType()); assertFlowDtos(FLOW_CREATE_PAYLOAD, flowRequest); }
|
FlowMapper { public FlowRequest toFlowUpdateRequest(FlowUpdatePayload source) { FlowRequest target = toFlowRequest(source).toBuilder() .diverseFlowId(source.getDiverseFlowId()) .type(Type.UPDATE) .build(); if (source.getSource().getDetectConnectedDevices() != null) { DetectConnectedDevicesPayload srcDevs = source.getSource().getDetectConnectedDevices(); target.getDetectConnectedDevices().setSrcArp(srcDevs.isArp()); target.getDetectConnectedDevices().setSrcLldp(srcDevs.isLldp()); } if (source.getDestination().getDetectConnectedDevices() != null) { DetectConnectedDevicesPayload dstDevs = source.getDestination().getDetectConnectedDevices(); target.getDetectConnectedDevices().setDstArp(dstDevs.isArp()); target.getDetectConnectedDevices().setDstLldp(dstDevs.isLldp()); } return target; } FlowPayload toFlowOutput(FlowDto f); FlowResponsePayload toFlowResponseOutput(FlowDto f); FlowResponseV2 toFlowResponseV2(FlowDto flowDto); @Mapping(target = "flowId", ignore = true) @Mapping(target = "maxLatency", expression = "java(flowPatchDto.getMaxLatency() != null ? flowPatchDto.getMaxLatency() * 1000000L : null)") @Mapping(target = "priority", source = "priority") @Mapping(target = "periodicPings", source = "periodicPings") @Mapping(target = "targetPathComputationStrategy", source = "targetPathComputationStrategy") @Mapping(target = "source", ignore = true) @Mapping(target = "destination", ignore = true) @Mapping(target = "bandwidth", ignore = true) @Mapping(target = "allocateProtectedPath", ignore = true) @Mapping(target = "diverseFlowId", ignore = true) @Mapping(target = "pathComputationStrategy", ignore = true) @Mapping(target = "pinned", ignore = true) @Mapping(target = "ignoreBandwidth", ignore = true) @Mapping(target = "description", ignore = true) @Mapping(target = "encapsulationType", ignore = true) abstract FlowPatch toFlowPatch(FlowPatchDto flowPatchDto); @Mapping(target = "flowId", ignore = true) @Mapping(target = "bandwidth", source = "maximumBandwidth") @Mapping(target = "allocateProtectedPath", source = "allocateProtectedPath") @Mapping(target = "maxLatency", expression = "java(flowPatchDto.getMaxLatency() != null ? flowPatchDto.getMaxLatency() * 1000000L : null)") @Mapping(target = "priority", source = "priority") @Mapping(target = "periodicPings", source = "periodicPings") @Mapping(target = "diverseFlowId", source = "diverseFlowId") abstract FlowPatch toFlowPatch(FlowPatchV2 flowPatchDto); @Mapping(target = "trackLldpConnectedDevices", expression = "java(flowPatchEndpoint.getDetectConnectedDevices() != null ? " + "flowPatchEndpoint.getDetectConnectedDevices().isLldp() : null)") @Mapping(target = "trackArpConnectedDevices", expression = "java(flowPatchEndpoint.getDetectConnectedDevices() != null ? " + "flowPatchEndpoint.getDetectConnectedDevices().isArp() : null)") abstract PatchEndpoint toPatchEndpoint(FlowPatchEndpoint flowPatchEndpoint); @Mapping(target = "bandwidth", source = "maximumBandwidth") @Mapping(target = "detectConnectedDevices", expression = "java(new DetectConnectedDevicesDto(" + "request.getSource().getDetectConnectedDevices().isLldp(), " + "request.getSource().getDetectConnectedDevices().isArp(), " + "request.getDestination().getDetectConnectedDevices().isLldp(), " + "request.getDestination().getDetectConnectedDevices().isArp()))") @Mapping(target = "transitEncapsulationId", ignore = true) @Mapping(target = "type", ignore = true) @Mapping(target = "bulkUpdateFlowIds", ignore = true) @Mapping(target = "doNotRevert", ignore = true) @Mapping(target = "maxLatency", expression = "java(request.getMaxLatency() != null ? request.getMaxLatency() * 1000000L : null)") abstract FlowRequest toFlowRequest(FlowRequestV2 request); @Mapping(target = "flowId", source = "id") @Mapping(target = "bandwidth", source = "maximumBandwidth") @Mapping(target = "detectConnectedDevices", ignore = true) @Mapping(target = "transitEncapsulationId", ignore = true) @Mapping(target = "type", ignore = true) @Mapping(target = "bulkUpdateFlowIds", ignore = true) @Mapping(target = "doNotRevert", ignore = true) @Mapping(target = "diverseFlowId", ignore = true) @Mapping(target = "maxLatency", expression = "java(payload.getMaxLatency() != null ? payload.getMaxLatency() * 1000000L : null)") abstract FlowRequest toFlowRequest(FlowPayload payload); @Mapping(target = "outerVlanId", source = "vlanId") @Mapping(target = "trackLldpConnectedDevices", source = "detectConnectedDevices.lldp") @Mapping(target = "trackArpConnectedDevices", source = "detectConnectedDevices.arp") abstract FlowEndpoint mapFlowEndpoint(FlowEndpointV2 input); @Mapping(target = "switchId", source = "datapath") @Mapping(target = "outerVlanId", source = "vlanId") @Mapping(target = "trackLldpConnectedDevices", source = "detectConnectedDevices.lldp") @Mapping(target = "trackArpConnectedDevices", source = "detectConnectedDevices.arp") abstract FlowEndpoint mapFlowEndpoint(FlowEndpointPayload input); FlowRequest toFlowCreateRequest(FlowRequestV2 source); FlowRequest toFlowCreateRequest(FlowCreatePayload source); FlowRequest toFlowUpdateRequest(FlowUpdatePayload source); abstract PingOutput toPingOutput(FlowPingResponse response); @Mapping(source = "flowId", target = "id") @Mapping(source = "path", target = "path") @Mapping(source = "rerouted", target = "rerouted") abstract FlowReroutePayload toReroutePayload(String flowId, PathInfoData path, boolean rerouted); @Mapping(source = "path", target = "path") abstract FlowRerouteResponseV2 toRerouteResponseV2(String flowId, PathInfoData path, boolean rerouted); @Mapping(source = "path", target = "nodes") abstract FlowPathV2 toFlowPathV2(PathInfoData path); @Mapping(target = "segmentLatency", ignore = true) abstract FlowPathV2.PathNodeV2 toPathNodeV2(PathNode pathNode); @Mapping(source = "flowId", target = "id") @Mapping(source = "state", target = "status") abstract FlowIdStatusPayload toFlowIdStatusPayload(FlowDto flow); @Mapping(target = "latency", source = "meters.networkLatency") abstract UniFlowPingOutput toUniFlowPing(UniFlowPingResponse response); SwapFlowPayload toSwapOutput(FlowDto flowDto); @Mapping(target = "sourceSwitch", expression = "java(request.getSource().getSwitchId())") @Mapping(target = "destinationSwitch", expression = "java(request.getDestination().getSwitchId())") @Mapping(target = "sourcePort", expression = "java(request.getSource().getPortNumber())") @Mapping(target = "destinationPort", expression = "java(request.getDestination().getPortNumber())") @Mapping(target = "sourceVlan", expression = "java(request.getSource().getVlanId())") @Mapping(target = "destinationVlan", expression = "java(request.getDestination().getVlanId())") abstract SwapFlowDto toSwapFlowDto(SwapFlowPayload request); abstract FlowValidationDto toFlowValidationDto(FlowValidationResponse response); String encodeFlowState(FlowState state); @Mapping(target = "mainPath", source = "mainFlowPathStatus") @Mapping(target = "protectedPath", source = "protectedFlowPathStatus") abstract PathStatus map(FlowStatusDetails flowStatusDetails); String map(FlowPathStatus flowPathStatus); String map(FlowEncapsulationType encapsulationType); FlowEncapsulationType map(String encapsulationType); String map(PathComputationStrategy pathComputationStrategy); PathComputationStrategy mapPathComputationStrategy(String pathComputationStrategy); org.openkilda.model.FlowEncapsulationType mapEncapsulationType(String encapsulationType); String getPingError(Ping.Errors error); }
|
@Test public void testFlowUpdatePayloadToFlowRequest() { FlowRequest flowRequest = flowMapper.toFlowUpdateRequest(FLOW_UPDATE_PAYLOAD); assertEquals(FLOW_UPDATE_PAYLOAD.getDiverseFlowId(), flowRequest.getDiverseFlowId()); assertEquals(Type.UPDATE, flowRequest.getType()); assertFlowDtos(FLOW_UPDATE_PAYLOAD, flowRequest); }
|
FlowMapper { @Mapping(target = "flowId", ignore = true) @Mapping(target = "maxLatency", expression = "java(flowPatchDto.getMaxLatency() != null ? flowPatchDto.getMaxLatency() * 1000000L : null)") @Mapping(target = "priority", source = "priority") @Mapping(target = "periodicPings", source = "periodicPings") @Mapping(target = "targetPathComputationStrategy", source = "targetPathComputationStrategy") @Mapping(target = "source", ignore = true) @Mapping(target = "destination", ignore = true) @Mapping(target = "bandwidth", ignore = true) @Mapping(target = "allocateProtectedPath", ignore = true) @Mapping(target = "diverseFlowId", ignore = true) @Mapping(target = "pathComputationStrategy", ignore = true) @Mapping(target = "pinned", ignore = true) @Mapping(target = "ignoreBandwidth", ignore = true) @Mapping(target = "description", ignore = true) @Mapping(target = "encapsulationType", ignore = true) public abstract FlowPatch toFlowPatch(FlowPatchDto flowPatchDto); FlowPayload toFlowOutput(FlowDto f); FlowResponsePayload toFlowResponseOutput(FlowDto f); FlowResponseV2 toFlowResponseV2(FlowDto flowDto); @Mapping(target = "flowId", ignore = true) @Mapping(target = "maxLatency", expression = "java(flowPatchDto.getMaxLatency() != null ? flowPatchDto.getMaxLatency() * 1000000L : null)") @Mapping(target = "priority", source = "priority") @Mapping(target = "periodicPings", source = "periodicPings") @Mapping(target = "targetPathComputationStrategy", source = "targetPathComputationStrategy") @Mapping(target = "source", ignore = true) @Mapping(target = "destination", ignore = true) @Mapping(target = "bandwidth", ignore = true) @Mapping(target = "allocateProtectedPath", ignore = true) @Mapping(target = "diverseFlowId", ignore = true) @Mapping(target = "pathComputationStrategy", ignore = true) @Mapping(target = "pinned", ignore = true) @Mapping(target = "ignoreBandwidth", ignore = true) @Mapping(target = "description", ignore = true) @Mapping(target = "encapsulationType", ignore = true) abstract FlowPatch toFlowPatch(FlowPatchDto flowPatchDto); @Mapping(target = "flowId", ignore = true) @Mapping(target = "bandwidth", source = "maximumBandwidth") @Mapping(target = "allocateProtectedPath", source = "allocateProtectedPath") @Mapping(target = "maxLatency", expression = "java(flowPatchDto.getMaxLatency() != null ? flowPatchDto.getMaxLatency() * 1000000L : null)") @Mapping(target = "priority", source = "priority") @Mapping(target = "periodicPings", source = "periodicPings") @Mapping(target = "diverseFlowId", source = "diverseFlowId") abstract FlowPatch toFlowPatch(FlowPatchV2 flowPatchDto); @Mapping(target = "trackLldpConnectedDevices", expression = "java(flowPatchEndpoint.getDetectConnectedDevices() != null ? " + "flowPatchEndpoint.getDetectConnectedDevices().isLldp() : null)") @Mapping(target = "trackArpConnectedDevices", expression = "java(flowPatchEndpoint.getDetectConnectedDevices() != null ? " + "flowPatchEndpoint.getDetectConnectedDevices().isArp() : null)") abstract PatchEndpoint toPatchEndpoint(FlowPatchEndpoint flowPatchEndpoint); @Mapping(target = "bandwidth", source = "maximumBandwidth") @Mapping(target = "detectConnectedDevices", expression = "java(new DetectConnectedDevicesDto(" + "request.getSource().getDetectConnectedDevices().isLldp(), " + "request.getSource().getDetectConnectedDevices().isArp(), " + "request.getDestination().getDetectConnectedDevices().isLldp(), " + "request.getDestination().getDetectConnectedDevices().isArp()))") @Mapping(target = "transitEncapsulationId", ignore = true) @Mapping(target = "type", ignore = true) @Mapping(target = "bulkUpdateFlowIds", ignore = true) @Mapping(target = "doNotRevert", ignore = true) @Mapping(target = "maxLatency", expression = "java(request.getMaxLatency() != null ? request.getMaxLatency() * 1000000L : null)") abstract FlowRequest toFlowRequest(FlowRequestV2 request); @Mapping(target = "flowId", source = "id") @Mapping(target = "bandwidth", source = "maximumBandwidth") @Mapping(target = "detectConnectedDevices", ignore = true) @Mapping(target = "transitEncapsulationId", ignore = true) @Mapping(target = "type", ignore = true) @Mapping(target = "bulkUpdateFlowIds", ignore = true) @Mapping(target = "doNotRevert", ignore = true) @Mapping(target = "diverseFlowId", ignore = true) @Mapping(target = "maxLatency", expression = "java(payload.getMaxLatency() != null ? payload.getMaxLatency() * 1000000L : null)") abstract FlowRequest toFlowRequest(FlowPayload payload); @Mapping(target = "outerVlanId", source = "vlanId") @Mapping(target = "trackLldpConnectedDevices", source = "detectConnectedDevices.lldp") @Mapping(target = "trackArpConnectedDevices", source = "detectConnectedDevices.arp") abstract FlowEndpoint mapFlowEndpoint(FlowEndpointV2 input); @Mapping(target = "switchId", source = "datapath") @Mapping(target = "outerVlanId", source = "vlanId") @Mapping(target = "trackLldpConnectedDevices", source = "detectConnectedDevices.lldp") @Mapping(target = "trackArpConnectedDevices", source = "detectConnectedDevices.arp") abstract FlowEndpoint mapFlowEndpoint(FlowEndpointPayload input); FlowRequest toFlowCreateRequest(FlowRequestV2 source); FlowRequest toFlowCreateRequest(FlowCreatePayload source); FlowRequest toFlowUpdateRequest(FlowUpdatePayload source); abstract PingOutput toPingOutput(FlowPingResponse response); @Mapping(source = "flowId", target = "id") @Mapping(source = "path", target = "path") @Mapping(source = "rerouted", target = "rerouted") abstract FlowReroutePayload toReroutePayload(String flowId, PathInfoData path, boolean rerouted); @Mapping(source = "path", target = "path") abstract FlowRerouteResponseV2 toRerouteResponseV2(String flowId, PathInfoData path, boolean rerouted); @Mapping(source = "path", target = "nodes") abstract FlowPathV2 toFlowPathV2(PathInfoData path); @Mapping(target = "segmentLatency", ignore = true) abstract FlowPathV2.PathNodeV2 toPathNodeV2(PathNode pathNode); @Mapping(source = "flowId", target = "id") @Mapping(source = "state", target = "status") abstract FlowIdStatusPayload toFlowIdStatusPayload(FlowDto flow); @Mapping(target = "latency", source = "meters.networkLatency") abstract UniFlowPingOutput toUniFlowPing(UniFlowPingResponse response); SwapFlowPayload toSwapOutput(FlowDto flowDto); @Mapping(target = "sourceSwitch", expression = "java(request.getSource().getSwitchId())") @Mapping(target = "destinationSwitch", expression = "java(request.getDestination().getSwitchId())") @Mapping(target = "sourcePort", expression = "java(request.getSource().getPortNumber())") @Mapping(target = "destinationPort", expression = "java(request.getDestination().getPortNumber())") @Mapping(target = "sourceVlan", expression = "java(request.getSource().getVlanId())") @Mapping(target = "destinationVlan", expression = "java(request.getDestination().getVlanId())") abstract SwapFlowDto toSwapFlowDto(SwapFlowPayload request); abstract FlowValidationDto toFlowValidationDto(FlowValidationResponse response); String encodeFlowState(FlowState state); @Mapping(target = "mainPath", source = "mainFlowPathStatus") @Mapping(target = "protectedPath", source = "protectedFlowPathStatus") abstract PathStatus map(FlowStatusDetails flowStatusDetails); String map(FlowPathStatus flowPathStatus); String map(FlowEncapsulationType encapsulationType); FlowEncapsulationType map(String encapsulationType); String map(PathComputationStrategy pathComputationStrategy); PathComputationStrategy mapPathComputationStrategy(String pathComputationStrategy); org.openkilda.model.FlowEncapsulationType mapEncapsulationType(String encapsulationType); String getPingError(Ping.Errors error); }
|
@Test public void testFlowPatchDtoToFlowDto() { FlowPatchDto flowPatchDto = new FlowPatchDto(LATENCY, PRIORITY, PERIODIC_PINGS, TARGET_PATH_COMPUTATION_STRATEGY); FlowPatch flowPatch = flowMapper.toFlowPatch(flowPatchDto); assertEquals(flowPatchDto.getMaxLatency() * 1000000L, (long) flowPatch.getMaxLatency()); assertEquals(flowPatchDto.getPriority(), flowPatch.getPriority()); assertEquals(flowPatchDto.getPeriodicPings(), flowPatch.getPeriodicPings()); assertEquals(flowPatchDto.getTargetPathComputationStrategy(), flowPatch.getTargetPathComputationStrategy().name().toLowerCase()); }
@Test public void testFlowPatchV2ToFlowDto() { FlowPatchV2 flowPatchDto = new FlowPatchV2( new FlowPatchEndpoint(SRC_SWITCH_ID, SRC_PORT, SRC_VLAN, SRC_INNER_VLAN, SRC_DETECT_CONNECTED_DEVICES), new FlowPatchEndpoint(DST_SWITCH_ID, DST_PORT, DST_VLAN, DST_INNER_VLAN, DST_DETECT_CONNECTED_DEVICES), LATENCY, PRIORITY, PERIODIC_PINGS, TARGET_PATH_COMPUTATION_STRATEGY, DIVERSE_FLOW_ID, (long) BANDWIDTH, ALLOCATE_PROTECTED_PATH, PINNED, IGNORE_BANDWIDTH, DESCRIPTION, ENCAPSULATION_TYPE, PATH_COMPUTATION_STRATEGY); FlowPatch flowPatch = flowMapper.toFlowPatch(flowPatchDto); assertEquals(flowPatchDto.getSource().getSwitchId(), flowPatch.getSource().getSwitchId()); assertEquals(flowPatchDto.getSource().getPortNumber(), flowPatch.getSource().getPortNumber()); assertEquals(flowPatchDto.getSource().getVlanId(), flowPatch.getSource().getVlanId()); assertEquals(flowPatchDto.getSource().getInnerVlanId(), flowPatch.getSource().getInnerVlanId()); assertEquals(flowPatchDto.getSource().getDetectConnectedDevices().isLldp(), flowPatch.getSource().getTrackLldpConnectedDevices()); assertEquals(flowPatchDto.getSource().getDetectConnectedDevices().isArp(), flowPatch.getSource().getTrackArpConnectedDevices()); assertEquals(flowPatchDto.getDestination().getSwitchId(), flowPatch.getDestination().getSwitchId()); assertEquals(flowPatchDto.getDestination().getPortNumber(), flowPatch.getDestination().getPortNumber()); assertEquals(flowPatchDto.getDestination().getVlanId(), flowPatch.getDestination().getVlanId()); assertEquals(flowPatchDto.getDestination().getInnerVlanId(), flowPatch.getDestination().getInnerVlanId()); assertEquals(flowPatchDto.getDestination().getDetectConnectedDevices().isLldp(), flowPatch.getDestination().getTrackLldpConnectedDevices()); assertEquals(flowPatchDto.getDestination().getDetectConnectedDevices().isArp(), flowPatch.getDestination().getTrackArpConnectedDevices()); assertEquals(flowPatchDto.getMaxLatency() * 1000000L, (long) flowPatch.getMaxLatency()); assertEquals(flowPatchDto.getPriority(), flowPatch.getPriority()); assertEquals(flowPatchDto.getPeriodicPings(), flowPatch.getPeriodicPings()); assertEquals(flowPatchDto.getTargetPathComputationStrategy(), flowPatch.getTargetPathComputationStrategy().name().toLowerCase()); assertEquals(flowPatchDto.getDiverseFlowId(), flowPatch.getDiverseFlowId()); assertEquals(flowPatchDto.getMaximumBandwidth(), flowPatch.getBandwidth()); assertEquals(flowPatchDto.getAllocateProtectedPath(), flowPatch.getAllocateProtectedPath()); assertEquals(flowPatchDto.getPinned(), flowPatch.getPinned()); assertEquals(flowPatchDto.getIgnoreBandwidth(), flowPatch.getIgnoreBandwidth()); assertEquals(flowPatchDto.getDescription(), flowPatch.getDescription()); assertEquals(flowPatchDto.getEncapsulationType(), flowPatch.getEncapsulationType().name().toLowerCase()); assertEquals(flowPatchDto.getPathComputationStrategy(), flowPatch.getPathComputationStrategy().name().toLowerCase()); }
|
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); }
|
@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); }
|
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; }
|
@Test public void buildTsdbTupleFromIslOneWayLatency() throws JsonEncodeException, IOException { List<Object> tsdbTuple = statsBolt.buildTsdbTuple( SWITCH1_ID, NODE1.getPortNo(), SWITCH2_ID, NODE2.getPortNo(), LATENCY, TIMESTAMP); assertTsdbTuple(tsdbTuple); }
|
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); }
|
@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))); }
|
IslStatsService { public void handleIstStatusUpdateNotification(IslStatusUpdateNotification notification) { IslKey key = new IslKey(notification.getSrcSwitchId(), notification.getSrcPortNo(), notification.getDstSwitchId(), notification.getDstPortNo()); if (notification.getStatus() == IslStatus.MOVED) { handleIslMoved(key); handleIslMoved(key.getReverse()); } else if (notification.getStatus() == IslStatus.INACTIVE) { handleIslDown(key); handleIslDown(key.getReverse()); } } IslStatsService(IslStatsCarrier carrier, long latencyTimeout); void handleRoundTripLatencyMetric(long timestamp, IslRoundTripLatency data, Endpoint destination); void handleOneWayLatencyMetric(long timestamp, IslOneWayLatency data); void handleIstStatusUpdateNotification(IslStatusUpdateNotification notification); }
|
@Test public void handleOneWayLatencyEmitOnIslDownTest() { List<LatencyRecord> buffer = new ArrayList<>(); Instant time = Instant.now().minusSeconds(LATENCY_TIMEOUT).minusMillis(500); for (int i = 0; i < 4; i++) { sendForwardOneWayLatency(i, time); verifyNoMoreInteractions(carrier); buffer.add(new LatencyRecord(i, time.toEpochMilli())); time = time.plusSeconds(1); } buffer.remove(0); islStatsService.handleIstStatusUpdateNotification( new IslStatusUpdateNotification(SWITCH_ID_1, PORT_1, SWITCH_ID_2, PORT_2, INACTIVE)); assertEmitLatency(buffer); }
@Test public void handleOneWayLatencyIslMovedTest() { Instant time = Instant.now().minusSeconds(LATENCY_TIMEOUT).minusMillis(500); for (int i = 0; i < 4; i++) { sendForwardOneWayLatency(i, time); verifyNoMoreInteractions(carrier); time = time.plusSeconds(1); } islStatsService.handleIstStatusUpdateNotification( new IslStatusUpdateNotification(SWITCH_ID_1, PORT_1, SWITCH_ID_2, PORT_2, MOVED)); verifyNoMoreInteractions(carrier); }
@Test public void handleOneWayLatencyEmitOnEachIslDownTest() throws InterruptedException { List<LatencyRecord> buffer = new ArrayList<>(); Instant time = Instant.now().minusSeconds(LATENCY_TIMEOUT).minusMillis(500); for (int i = 0; i < 4; i++) { sendForwardOneWayLatency(i, time); verifyNoMoreInteractions(carrier); buffer.add(new LatencyRecord(i, time.toEpochMilli())); time = time.plusSeconds(1); } buffer.remove(0); islStatsService.handleIstStatusUpdateNotification( new IslStatusUpdateNotification(SWITCH_ID_1, PORT_1, SWITCH_ID_2, PORT_2, INACTIVE)); time = Instant.now(); int secondPartOfPacketsSize = 4; for (int i = 0; i < secondPartOfPacketsSize; i++) { sendForwardOneWayLatency(i + secondPartOfPacketsSize, time); buffer.add(new LatencyRecord(i + secondPartOfPacketsSize, time.toEpochMilli())); time = time.plusMillis(500); sleep(50); } islStatsService.handleIstStatusUpdateNotification( new IslStatusUpdateNotification(SWITCH_ID_1, PORT_1, SWITCH_ID_2, PORT_2, INACTIVE)); assertEmitLatency(buffer); }
@Test public void handleOneWayLatencyEmitOnFirstIslDownTest() throws InterruptedException { List<LatencyRecord> buffer = new ArrayList<>(); Instant time = Instant.now().minusSeconds(LATENCY_TIMEOUT).minusMillis(500); for (int i = 0; i < 4; i++) { sendForwardOneWayLatency(i, time); verifyNoMoreInteractions(carrier); buffer.add(new LatencyRecord(i, time.toEpochMilli())); time = time.plusSeconds(1); } buffer.remove(0); islStatsService.handleIstStatusUpdateNotification( new IslStatusUpdateNotification(SWITCH_ID_1, PORT_1, SWITCH_ID_2, PORT_2, INACTIVE)); time = Instant.now(); int secondPartOfPacketsSize = 4; for (int i = 0; i < secondPartOfPacketsSize; i++) { sendForwardOneWayLatency(i + secondPartOfPacketsSize, time); time = time.plusMillis(500); sleep(50); } assertEmitLatency(buffer); }
@Test public void handleOneWayLatencyNoEmitOnEachIslMoveTest() throws InterruptedException { Instant time = Instant.now().minusSeconds(LATENCY_TIMEOUT - 1); for (int i = 0; i < 4; i++) { sendForwardOneWayLatency(i, time); time = time.plusSeconds(1); } islStatsService.handleIstStatusUpdateNotification( new IslStatusUpdateNotification(SWITCH_ID_1, PORT_1, SWITCH_ID_2, PORT_2, MOVED)); time = time.plusSeconds(LATENCY_TIMEOUT + 1); int secondPartOfPacketsSize = 4; for (int i = 0; i < secondPartOfPacketsSize; i++) { sendForwardOneWayLatency(i + secondPartOfPacketsSize, time); time = time.plusMillis(50); sleep(50); } islStatsService.handleIstStatusUpdateNotification( new IslStatusUpdateNotification(SWITCH_ID_1, PORT_1, SWITCH_ID_2, PORT_2, MOVED)); verifyNoMoreInteractions(carrier); }
|
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); }
|
@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); }
|
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); }
|
@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); }
|
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; }
|
@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); }
|
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; }
|
@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)); }
|
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; }
|
@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)); }
|
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; }
|
@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)); }
|
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; }
|
@Test public void getNextUpdateTimeTest() { Instant actualTime = islLatencyService.getNextUpdateTime(); long expectedTime = System.currentTimeMillis() + LATENCY_UPDATE_INTERVAL * 1000; assertEquals(expectedTime, actualTime.toEpochMilli(), 50); }
|
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; }
|
@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<>())); }
|
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; }
|
@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()); } }
|
FlowController extends BaseController { @RequestMapping(value = "/all/history/{flowId}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.FW_FLOW_HISTORY }) public @ResponseBody List<FlowHistory> getFlowHistory(@PathVariable final String flowId, @RequestParam(name = "timeFrom", required = false) String timeFrom, @RequestParam(name = "timeTo", required = false) String timeTo) { return flowService.getFlowHistory(flowId, timeFrom, timeTo); } @RequestMapping(value = "/count", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody Collection<FlowCount> getFlowCount(); @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_FLOWS }) @ResponseBody List<FlowInfo> getFlows(
@RequestParam(name = "status", required = false) List<String> statuses,
@RequestParam(name = "controller", required = false) boolean controller); @RequestMapping(value = "/path/{flowId}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody FlowPayload getFlowPath(@PathVariable final String flowId); @RequestMapping(value = "/{flowId}/reroute", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody FlowPath rerouteFlow(@PathVariable final String flowId); @RequestMapping(value = "/{flowId}/validate", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody String validateFlow(@PathVariable final String flowId); @RequestMapping(value = "/{flowId}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_FLOWS }) @ResponseBody FlowInfo getFlowById(@PathVariable final String flowId,
@RequestParam(name = "controller", required = false) boolean controller); @RequestMapping(value = "/{flowId}/status", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody FlowStatus getFlowStatusById(@PathVariable final String flowId); @RequestMapping(method = RequestMethod.PUT) @ResponseStatus(HttpStatus.CREATED) @Permissions(values = { IConstants.Permission.FW_FLOW_CREATE }) @ResponseBody Flow createFlow(@RequestBody final Flow flow); @RequestMapping(value = "/{flowId}", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.CREATED) @Permissions(values = { IConstants.Permission.FW_FLOW_UPDATE }) @ResponseBody Flow updateFlow(@PathVariable("flowId") final String flowId, @RequestBody final Flow flow); @RequestMapping(value = "/{flowId}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.FW_FLOW_DELETE }) @ResponseBody Flow deleteFlow(@RequestBody final UserInfo userInfo, @PathVariable("flowId") final String flowId); @RequestMapping(value = "/{flowId}/sync", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.FW_FLOW_RESYNC }) @ResponseBody String resyncFlow(@PathVariable final String flowId); @RequestMapping(value = "/status", method = { RequestMethod.GET }) Set<String> getAllStatus(); @Scheduled(fixedDelayString = "${status.cron.time}") void getAllStatusWithCron(); @RequestMapping(value = "/{flowId}/ping", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.FW_FLOW_PING }) @ResponseBody String flowPing(@PathVariable final String flowId, @RequestBody final Flow flow); @RequestMapping(value = "/all/history/{flowId}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.FW_FLOW_HISTORY }) @ResponseBody List<FlowHistory> getFlowHistory(@PathVariable final String flowId,
@RequestParam(name = "timeFrom", required = false) String timeFrom,
@RequestParam(name = "timeTo", required = false) String timeTo); @RequestMapping(value = "/connected/devices/{flowId}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody FlowConnectedDevice getFlowConnectedDevice(@PathVariable final String flowId,
@RequestParam(name = "since", required = false) String timeLastSeen); }
|
@Test public void testGetFlowHistory() throws Exception { try { mockMvc.perform(get("/api/flows/all/history/{flowId}", TestFlowMock.FLOW_ID) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); assertTrue(true); } catch (Exception exception) { assertTrue(false); } }
@Test public void testGetFlowHistoryIfRequestParamsPassed() throws Exception { List<FlowHistory> flowHistories = new ArrayList<FlowHistory>(); try { when(flowController.getFlowHistory(TestFlowMock.FLOW_ID, TestFlowMock.TIME_FROM, TestFlowMock.TIME_TO)) .thenReturn(flowHistories); mockMvc.perform(get("/api/flows/all/history/{flowId}", TestFlowMock.FLOW_ID) .param("timeFrom", TestFlowMock.TIME_TO) .param("timeTo", TestFlowMock.TIME_TO) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); assertTrue(true); } catch (Exception exception) { assertTrue(false); } }
@Test public void testGetFlowsHistoryIfFlowIdNotPassed() throws Exception { List<FlowHistory> flowHistories = new ArrayList<FlowHistory>(); try { when(flowController.getFlowHistory(TestFlowMock.FLOW_ID_NULL, TestFlowMock.TIME_FROM, TestFlowMock.TIME_TO)) .thenReturn(flowHistories); mockMvc.perform(get("/api/flows/all/history/{flowId}", TestFlowMock.FLOW_ID_NULL) .param("timeFrom", TestFlowMock.TIME_FROM) .param("timeTo", TestFlowMock.TIME_TO) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); assertTrue(true); } catch (Exception exception) { assertTrue(false); } }
|
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(); }
|
@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); }
|
FlowController extends BaseController { @RequestMapping(value = "/{flowId}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_FLOWS }) public @ResponseBody FlowInfo getFlowById(@PathVariable final String flowId, @RequestParam(name = "controller", required = false) boolean controller) { LOGGER.info("Get flow by id. Flow id: '" + flowId + "'"); FlowInfo flowInfo = flowService.getFlowById(flowId, controller); return flowInfo; } @RequestMapping(value = "/count", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody Collection<FlowCount> getFlowCount(); @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_FLOWS }) @ResponseBody List<FlowInfo> getFlows(
@RequestParam(name = "status", required = false) List<String> statuses,
@RequestParam(name = "controller", required = false) boolean controller); @RequestMapping(value = "/path/{flowId}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody FlowPayload getFlowPath(@PathVariable final String flowId); @RequestMapping(value = "/{flowId}/reroute", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody FlowPath rerouteFlow(@PathVariable final String flowId); @RequestMapping(value = "/{flowId}/validate", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody String validateFlow(@PathVariable final String flowId); @RequestMapping(value = "/{flowId}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_FLOWS }) @ResponseBody FlowInfo getFlowById(@PathVariable final String flowId,
@RequestParam(name = "controller", required = false) boolean controller); @RequestMapping(value = "/{flowId}/status", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody FlowStatus getFlowStatusById(@PathVariable final String flowId); @RequestMapping(method = RequestMethod.PUT) @ResponseStatus(HttpStatus.CREATED) @Permissions(values = { IConstants.Permission.FW_FLOW_CREATE }) @ResponseBody Flow createFlow(@RequestBody final Flow flow); @RequestMapping(value = "/{flowId}", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.CREATED) @Permissions(values = { IConstants.Permission.FW_FLOW_UPDATE }) @ResponseBody Flow updateFlow(@PathVariable("flowId") final String flowId, @RequestBody final Flow flow); @RequestMapping(value = "/{flowId}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.FW_FLOW_DELETE }) @ResponseBody Flow deleteFlow(@RequestBody final UserInfo userInfo, @PathVariable("flowId") final String flowId); @RequestMapping(value = "/{flowId}/sync", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.FW_FLOW_RESYNC }) @ResponseBody String resyncFlow(@PathVariable final String flowId); @RequestMapping(value = "/status", method = { RequestMethod.GET }) Set<String> getAllStatus(); @Scheduled(fixedDelayString = "${status.cron.time}") void getAllStatusWithCron(); @RequestMapping(value = "/{flowId}/ping", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.FW_FLOW_PING }) @ResponseBody String flowPing(@PathVariable final String flowId, @RequestBody final Flow flow); @RequestMapping(value = "/all/history/{flowId}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.FW_FLOW_HISTORY }) @ResponseBody List<FlowHistory> getFlowHistory(@PathVariable final String flowId,
@RequestParam(name = "timeFrom", required = false) String timeFrom,
@RequestParam(name = "timeTo", required = false) String timeTo); @RequestMapping(value = "/connected/devices/{flowId}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody FlowConnectedDevice getFlowConnectedDevice(@PathVariable final String flowId,
@RequestParam(name = "since", required = false) String timeLastSeen); }
|
@Test public void testGetFlowById() throws Exception { FlowInfo flowInfo = new FlowInfo(); try { when(flowService.getFlowById(TestFlowMock.FLOW_ID, TestFlowMock.CONTROLLER_FLAG)).thenReturn(flowInfo); mockMvc.perform(get("/api/flows/{flowId}", TestFlowMock.FLOW_ID).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); assertTrue(true); } catch (Exception e) { assertTrue(false); } }
@Test public void testGetFlowByIdWhenFlowIdNotPassed() throws Exception { FlowInfo flowInfo = new FlowInfo(); try { when(flowService.getFlowById(TestFlowMock.FLOW_ID_NULL, TestFlowMock.CONTROLLER_FLAG)).thenReturn(flowInfo); mockMvc.perform(get("/api/flows/{flowId}", TestFlowMock.FLOW_ID_NULL, true) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isMethodNotAllowed()); assertTrue(true); } catch (Exception e) { assertTrue(false); } }
|
FlowController extends BaseController { @RequestMapping(value = "/path/{flowId}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) public @ResponseBody FlowPayload getFlowPath(@PathVariable final String flowId) { LOGGER.info("Get flow path. Flow id: '" + flowId + "'"); return flowService.getFlowPath(flowId); } @RequestMapping(value = "/count", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody Collection<FlowCount> getFlowCount(); @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_FLOWS }) @ResponseBody List<FlowInfo> getFlows(
@RequestParam(name = "status", required = false) List<String> statuses,
@RequestParam(name = "controller", required = false) boolean controller); @RequestMapping(value = "/path/{flowId}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody FlowPayload getFlowPath(@PathVariable final String flowId); @RequestMapping(value = "/{flowId}/reroute", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody FlowPath rerouteFlow(@PathVariable final String flowId); @RequestMapping(value = "/{flowId}/validate", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody String validateFlow(@PathVariable final String flowId); @RequestMapping(value = "/{flowId}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_FLOWS }) @ResponseBody FlowInfo getFlowById(@PathVariable final String flowId,
@RequestParam(name = "controller", required = false) boolean controller); @RequestMapping(value = "/{flowId}/status", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody FlowStatus getFlowStatusById(@PathVariable final String flowId); @RequestMapping(method = RequestMethod.PUT) @ResponseStatus(HttpStatus.CREATED) @Permissions(values = { IConstants.Permission.FW_FLOW_CREATE }) @ResponseBody Flow createFlow(@RequestBody final Flow flow); @RequestMapping(value = "/{flowId}", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.CREATED) @Permissions(values = { IConstants.Permission.FW_FLOW_UPDATE }) @ResponseBody Flow updateFlow(@PathVariable("flowId") final String flowId, @RequestBody final Flow flow); @RequestMapping(value = "/{flowId}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.FW_FLOW_DELETE }) @ResponseBody Flow deleteFlow(@RequestBody final UserInfo userInfo, @PathVariable("flowId") final String flowId); @RequestMapping(value = "/{flowId}/sync", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.FW_FLOW_RESYNC }) @ResponseBody String resyncFlow(@PathVariable final String flowId); @RequestMapping(value = "/status", method = { RequestMethod.GET }) Set<String> getAllStatus(); @Scheduled(fixedDelayString = "${status.cron.time}") void getAllStatusWithCron(); @RequestMapping(value = "/{flowId}/ping", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.FW_FLOW_PING }) @ResponseBody String flowPing(@PathVariable final String flowId, @RequestBody final Flow flow); @RequestMapping(value = "/all/history/{flowId}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.FW_FLOW_HISTORY }) @ResponseBody List<FlowHistory> getFlowHistory(@PathVariable final String flowId,
@RequestParam(name = "timeFrom", required = false) String timeFrom,
@RequestParam(name = "timeTo", required = false) String timeTo); @RequestMapping(value = "/connected/devices/{flowId}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody FlowConnectedDevice getFlowConnectedDevice(@PathVariable final String flowId,
@RequestParam(name = "since", required = false) String timeLastSeen); }
|
@Test public void testGetFlowPath() throws Exception { FlowPayload flowPayload = new FlowPayload(); try { when(flowService.getFlowPath(Mockito.anyString())).thenReturn(flowPayload); mockMvc.perform(get("/api/flows/path/{flowId}", TestFlowMock.FLOW_ID) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); assertTrue(true); } catch (Exception e) { assertTrue(false); } }
@Test public void testGetFlowPathWhenFlowIdNotPassed() throws Exception { FlowPayload flowPayload = new FlowPayload(); try { when(flowService.getFlowPath(Mockito.anyString())).thenReturn(flowPayload); mockMvc.perform(get("/api/flows/get/path/{flowId}", TestFlowMock.FLOW_ID_NULL) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); assertTrue(true); } catch (Exception e) { assertTrue(false); } }
|
SwitchController { @RequestMapping(path = "/{switchId}/flows", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) public @ResponseBody ResponseEntity<List<?>> getPortFlows(@PathVariable final String switchId, @RequestParam(value = "port", required = false) final String port, @RequestParam(value = "inventory", required = false) final boolean inventory) { return serviceSwitch.getPortFlows(switchId, port, inventory); } @RequestMapping(value = "/list") @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_SWITCHES }) @ResponseBody List<SwitchInfo> getSwitchesDetail(
@RequestParam(value = "storeConfigurationStatus", required = false)
final boolean storeConfigurationStatus,
@RequestParam(value = "controller", required = false)
final boolean controller); @RequestMapping(value = "/{switchId}") @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_SWITCHES }) @ResponseBody SwitchInfo getSwitchDetail(@PathVariable final String switchId,
@RequestParam(value = "controller", required = false)
final boolean controller); @RequestMapping(value = "/name/{switchId}", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_SWITCH_UPDATE_NAME}) @ResponseBody SwitchInfo saveOrUpdateSwitchName(@PathVariable final String switchId,
@RequestBody final String switchName); @RequestMapping(value = "/links", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_ISL }) @ResponseBody List<IslLinkInfo> getLinksDetail(@RequestParam(value = "src_switch",
required = false) final String srcSwitch, @RequestParam(value = "src_port",
required = false) final String srcPort, @RequestParam(value = "dst_switch",
required = false) final String dstSwitch, @RequestParam(value = "dst_port",
required = false) final String dstPort); @RequestMapping(value = "/links", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.ISL_DELETE_LINK }) @ResponseBody List<IslLinkInfo> deleteIsl(@RequestBody final LinkParametersDto linkParametersDto); @RequestMapping(path = "/links/under-maintenance", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.ISL_UPDATE_MAINTENANCE}) @ResponseBody List<IslLinkInfo> updateLinkUnderMaintenance(
@RequestBody final LinkUnderMaintenanceDto linkUnderMaintenanceDto); @RequestMapping(path = "/link/props", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody LinkProps getLinkProps(
@RequestParam(value = "src_switch", required = true) final String srcSwitch,
@RequestParam(value = "src_port", required = true) final String srcPort, @RequestParam(
value = "dst_switch", required = true) final String dstSwitch, @RequestParam(
value = "dst_port", required = true) final String dstPort); @RequestMapping(path = "/link/bandwidth", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.ISL_UPDATE_BANDWIDTH}) @ResponseBody LinkMaxBandwidth updateMaxBandwidth(
@RequestParam(value = "src_switch", required = true) final String srcSwitch,
@RequestParam(value = "src_port", required = true) final String srcPort, @RequestParam(
value = "dst_switch", required = true) final String dstSwitch, @RequestParam(
value = "dst_port", required = true) final String dstPort,
@RequestBody LinkMaxBandwidth linkMaxBandwidth); @RequestMapping(path = "/link/enable-bfd", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.ISL_UPDATE_BFD_FLAG}) @ResponseBody List<IslLinkInfo> updateEnableBfdFlag(@RequestBody LinkParametersDto linkParametersDto); @RequestMapping(path = "/link/props", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @ResponseBody String updateLinkProps(@RequestBody final List<LinkProps> keys); @RequestMapping(path = "/{switchId}/rules", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_PERMISSION_RULES}) @ResponseBody String getSwitchRules(@PathVariable final String switchId); @RequestMapping(path = "/{switchId}/{port}/config", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_PORT_CONFIG}) @ResponseBody ConfiguredPort configureSwitchPort(
@RequestBody final PortConfiguration configuration,
@PathVariable final String switchId, @PathVariable final String port); @RequestMapping(path = "/{switchId}/flows", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody ResponseEntity<List<?>> getPortFlows(@PathVariable final String switchId,
@RequestParam(value = "port", required = false) final String port,
@RequestParam(value = "inventory", required = false) final boolean inventory); @RequestMapping(value = "/links/flows", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody List<FlowInfo> getIslFlows(@RequestParam(name = "src_switch",
required = true) final String srcSwitch, @RequestParam(name = "src_port",
required = true) final String srcPort, @RequestParam(name = "dst_switch",
required = true) final String dstSwitch, @RequestParam(name = "dst_port",
required = true) final String dstPort); @RequestMapping(value = "/meters/{switchId}") @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_SWITCH_METERS}) @ResponseBody SwitchMeter getSwitchMeters(@PathVariable final String switchId); @RequestMapping(value = "/under-maintenance/{switchId}", method = RequestMethod.POST) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_SWITCH_MAINTENANCE}) @ResponseBody SwitchInfo updateSwitchMaintenanceStatus(
@PathVariable("switchId") final String switchId,
@RequestBody final SwitchInfo switchInfo); @RequestMapping(value = "/{switchId}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.SW_SWITCH_DELETE }) @ResponseBody SwitchInfo deleteSwitch(@PathVariable final String switchId,
@RequestParam(name = "force", required = false) boolean force); @RequestMapping(value = "/{switchId}/ports/{port}/properties", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.SW_UPDATE_PORT_PROPERTIES }) @ResponseBody SwitchProperty updateSwitchPortProperty(@PathVariable final String switchId,
@PathVariable final String port, @RequestBody SwitchProperty switchProperty); @RequestMapping(value = "/{switchId}/ports/{port}/properties", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody SwitchProperty getSwitchPortProperty(@PathVariable final String switchId,
@PathVariable final String port); }
|
@Test public void testGetAllSwitchFlows() { ResponseEntity<List<?>> responseList = new ResponseEntity<List<?>>(HttpStatus.OK); try { when(serviceSwitch.getPortFlows(TestSwitchMock.SWITCH_ID, TestSwitchMock.PORT, TestFlowMock.CONTROLLER_FLAG)).thenReturn(responseList); mockMvc.perform(get("/api/switch/{switchId}/flows", TestSwitchMock.SWITCH_ID) .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); assertTrue(true); } catch (Exception e) { assertTrue(false); } }
|
SwitchController { @RequestMapping(value = "/{switchId}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.SW_SWITCH_DELETE }) public @ResponseBody SwitchInfo deleteSwitch(@PathVariable final String switchId, @RequestParam(name = "force", required = false) boolean force) { activityLogger.log(ActivityType.DELETE_SWITCH, switchId); return serviceSwitch.deleteSwitch(switchId, force); } @RequestMapping(value = "/list") @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_SWITCHES }) @ResponseBody List<SwitchInfo> getSwitchesDetail(
@RequestParam(value = "storeConfigurationStatus", required = false)
final boolean storeConfigurationStatus,
@RequestParam(value = "controller", required = false)
final boolean controller); @RequestMapping(value = "/{switchId}") @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_SWITCHES }) @ResponseBody SwitchInfo getSwitchDetail(@PathVariable final String switchId,
@RequestParam(value = "controller", required = false)
final boolean controller); @RequestMapping(value = "/name/{switchId}", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_SWITCH_UPDATE_NAME}) @ResponseBody SwitchInfo saveOrUpdateSwitchName(@PathVariable final String switchId,
@RequestBody final String switchName); @RequestMapping(value = "/links", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_ISL }) @ResponseBody List<IslLinkInfo> getLinksDetail(@RequestParam(value = "src_switch",
required = false) final String srcSwitch, @RequestParam(value = "src_port",
required = false) final String srcPort, @RequestParam(value = "dst_switch",
required = false) final String dstSwitch, @RequestParam(value = "dst_port",
required = false) final String dstPort); @RequestMapping(value = "/links", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.ISL_DELETE_LINK }) @ResponseBody List<IslLinkInfo> deleteIsl(@RequestBody final LinkParametersDto linkParametersDto); @RequestMapping(path = "/links/under-maintenance", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.ISL_UPDATE_MAINTENANCE}) @ResponseBody List<IslLinkInfo> updateLinkUnderMaintenance(
@RequestBody final LinkUnderMaintenanceDto linkUnderMaintenanceDto); @RequestMapping(path = "/link/props", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody LinkProps getLinkProps(
@RequestParam(value = "src_switch", required = true) final String srcSwitch,
@RequestParam(value = "src_port", required = true) final String srcPort, @RequestParam(
value = "dst_switch", required = true) final String dstSwitch, @RequestParam(
value = "dst_port", required = true) final String dstPort); @RequestMapping(path = "/link/bandwidth", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.ISL_UPDATE_BANDWIDTH}) @ResponseBody LinkMaxBandwidth updateMaxBandwidth(
@RequestParam(value = "src_switch", required = true) final String srcSwitch,
@RequestParam(value = "src_port", required = true) final String srcPort, @RequestParam(
value = "dst_switch", required = true) final String dstSwitch, @RequestParam(
value = "dst_port", required = true) final String dstPort,
@RequestBody LinkMaxBandwidth linkMaxBandwidth); @RequestMapping(path = "/link/enable-bfd", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.ISL_UPDATE_BFD_FLAG}) @ResponseBody List<IslLinkInfo> updateEnableBfdFlag(@RequestBody LinkParametersDto linkParametersDto); @RequestMapping(path = "/link/props", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @ResponseBody String updateLinkProps(@RequestBody final List<LinkProps> keys); @RequestMapping(path = "/{switchId}/rules", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_PERMISSION_RULES}) @ResponseBody String getSwitchRules(@PathVariable final String switchId); @RequestMapping(path = "/{switchId}/{port}/config", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_PORT_CONFIG}) @ResponseBody ConfiguredPort configureSwitchPort(
@RequestBody final PortConfiguration configuration,
@PathVariable final String switchId, @PathVariable final String port); @RequestMapping(path = "/{switchId}/flows", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody ResponseEntity<List<?>> getPortFlows(@PathVariable final String switchId,
@RequestParam(value = "port", required = false) final String port,
@RequestParam(value = "inventory", required = false) final boolean inventory); @RequestMapping(value = "/links/flows", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody List<FlowInfo> getIslFlows(@RequestParam(name = "src_switch",
required = true) final String srcSwitch, @RequestParam(name = "src_port",
required = true) final String srcPort, @RequestParam(name = "dst_switch",
required = true) final String dstSwitch, @RequestParam(name = "dst_port",
required = true) final String dstPort); @RequestMapping(value = "/meters/{switchId}") @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_SWITCH_METERS}) @ResponseBody SwitchMeter getSwitchMeters(@PathVariable final String switchId); @RequestMapping(value = "/under-maintenance/{switchId}", method = RequestMethod.POST) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_SWITCH_MAINTENANCE}) @ResponseBody SwitchInfo updateSwitchMaintenanceStatus(
@PathVariable("switchId") final String switchId,
@RequestBody final SwitchInfo switchInfo); @RequestMapping(value = "/{switchId}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.SW_SWITCH_DELETE }) @ResponseBody SwitchInfo deleteSwitch(@PathVariable final String switchId,
@RequestParam(name = "force", required = false) boolean force); @RequestMapping(value = "/{switchId}/ports/{port}/properties", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.SW_UPDATE_PORT_PROPERTIES }) @ResponseBody SwitchProperty updateSwitchPortProperty(@PathVariable final String switchId,
@PathVariable final String port, @RequestBody SwitchProperty switchProperty); @RequestMapping(value = "/{switchId}/ports/{port}/properties", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody SwitchProperty getSwitchPortProperty(@PathVariable final String switchId,
@PathVariable final String port); }
|
@Test public void testDeleteSwitch() { SwitchInfo switcheInfo = new SwitchInfo(); try { when(serviceSwitch.deleteSwitch(TestSwitchMock.SWITCH_ID, false)).thenReturn(switcheInfo); mockMvc.perform(delete("/api/switch/{switchId}", TestSwitchMock.SWITCH_ID, true) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); assertTrue(true); } catch (Exception e) { System.out.println("exception: " + e.getMessage()); assertTrue(false); } }
|
SwitchController { @RequestMapping(value = "/links", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.ISL_DELETE_LINK }) public @ResponseBody List<IslLinkInfo> deleteIsl(@RequestBody final LinkParametersDto linkParametersDto) { Long userId = null; if (serverContext.getRequestContext() != null) { userId = serverContext.getRequestContext().getUserId(); } activityLogger.log(ActivityType.DELETE_ISL, linkParametersDto.toString()); return serviceSwitch.deleteLink(linkParametersDto, userId); } @RequestMapping(value = "/list") @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_SWITCHES }) @ResponseBody List<SwitchInfo> getSwitchesDetail(
@RequestParam(value = "storeConfigurationStatus", required = false)
final boolean storeConfigurationStatus,
@RequestParam(value = "controller", required = false)
final boolean controller); @RequestMapping(value = "/{switchId}") @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_SWITCHES }) @ResponseBody SwitchInfo getSwitchDetail(@PathVariable final String switchId,
@RequestParam(value = "controller", required = false)
final boolean controller); @RequestMapping(value = "/name/{switchId}", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_SWITCH_UPDATE_NAME}) @ResponseBody SwitchInfo saveOrUpdateSwitchName(@PathVariable final String switchId,
@RequestBody final String switchName); @RequestMapping(value = "/links", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_ISL }) @ResponseBody List<IslLinkInfo> getLinksDetail(@RequestParam(value = "src_switch",
required = false) final String srcSwitch, @RequestParam(value = "src_port",
required = false) final String srcPort, @RequestParam(value = "dst_switch",
required = false) final String dstSwitch, @RequestParam(value = "dst_port",
required = false) final String dstPort); @RequestMapping(value = "/links", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.ISL_DELETE_LINK }) @ResponseBody List<IslLinkInfo> deleteIsl(@RequestBody final LinkParametersDto linkParametersDto); @RequestMapping(path = "/links/under-maintenance", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.ISL_UPDATE_MAINTENANCE}) @ResponseBody List<IslLinkInfo> updateLinkUnderMaintenance(
@RequestBody final LinkUnderMaintenanceDto linkUnderMaintenanceDto); @RequestMapping(path = "/link/props", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody LinkProps getLinkProps(
@RequestParam(value = "src_switch", required = true) final String srcSwitch,
@RequestParam(value = "src_port", required = true) final String srcPort, @RequestParam(
value = "dst_switch", required = true) final String dstSwitch, @RequestParam(
value = "dst_port", required = true) final String dstPort); @RequestMapping(path = "/link/bandwidth", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.ISL_UPDATE_BANDWIDTH}) @ResponseBody LinkMaxBandwidth updateMaxBandwidth(
@RequestParam(value = "src_switch", required = true) final String srcSwitch,
@RequestParam(value = "src_port", required = true) final String srcPort, @RequestParam(
value = "dst_switch", required = true) final String dstSwitch, @RequestParam(
value = "dst_port", required = true) final String dstPort,
@RequestBody LinkMaxBandwidth linkMaxBandwidth); @RequestMapping(path = "/link/enable-bfd", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.ISL_UPDATE_BFD_FLAG}) @ResponseBody List<IslLinkInfo> updateEnableBfdFlag(@RequestBody LinkParametersDto linkParametersDto); @RequestMapping(path = "/link/props", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @ResponseBody String updateLinkProps(@RequestBody final List<LinkProps> keys); @RequestMapping(path = "/{switchId}/rules", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_PERMISSION_RULES}) @ResponseBody String getSwitchRules(@PathVariable final String switchId); @RequestMapping(path = "/{switchId}/{port}/config", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_PORT_CONFIG}) @ResponseBody ConfiguredPort configureSwitchPort(
@RequestBody final PortConfiguration configuration,
@PathVariable final String switchId, @PathVariable final String port); @RequestMapping(path = "/{switchId}/flows", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody ResponseEntity<List<?>> getPortFlows(@PathVariable final String switchId,
@RequestParam(value = "port", required = false) final String port,
@RequestParam(value = "inventory", required = false) final boolean inventory); @RequestMapping(value = "/links/flows", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody List<FlowInfo> getIslFlows(@RequestParam(name = "src_switch",
required = true) final String srcSwitch, @RequestParam(name = "src_port",
required = true) final String srcPort, @RequestParam(name = "dst_switch",
required = true) final String dstSwitch, @RequestParam(name = "dst_port",
required = true) final String dstPort); @RequestMapping(value = "/meters/{switchId}") @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_SWITCH_METERS}) @ResponseBody SwitchMeter getSwitchMeters(@PathVariable final String switchId); @RequestMapping(value = "/under-maintenance/{switchId}", method = RequestMethod.POST) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_SWITCH_MAINTENANCE}) @ResponseBody SwitchInfo updateSwitchMaintenanceStatus(
@PathVariable("switchId") final String switchId,
@RequestBody final SwitchInfo switchInfo); @RequestMapping(value = "/{switchId}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.SW_SWITCH_DELETE }) @ResponseBody SwitchInfo deleteSwitch(@PathVariable final String switchId,
@RequestParam(name = "force", required = false) boolean force); @RequestMapping(value = "/{switchId}/ports/{port}/properties", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.SW_UPDATE_PORT_PROPERTIES }) @ResponseBody SwitchProperty updateSwitchPortProperty(@PathVariable final String switchId,
@PathVariable final String port, @RequestBody SwitchProperty switchProperty); @RequestMapping(value = "/{switchId}/ports/{port}/properties", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody SwitchProperty getSwitchPortProperty(@PathVariable final String switchId,
@PathVariable final String port); }
|
@Test public void testDeleteIsl() throws Exception { LinkParametersDto linkParametersDto = new LinkParametersDto(); linkParametersDto.setSrcPort(Integer.valueOf(TestIslMock.SRC_PORT)); linkParametersDto.setSrcSwitch(TestIslMock.SRC_SWITCH); linkParametersDto.setDstPort(Integer.valueOf(TestIslMock.DST_PORT)); linkParametersDto.setDstSwitch(TestIslMock.DST_SWITCH); List<IslLinkInfo> islLinkInfo = new ArrayList<IslLinkInfo>(); String inputJson = mapToJson(linkParametersDto); when(serviceSwitch.deleteLink(linkParametersDto, TestIslMock.USER_ID)).thenReturn(islLinkInfo); MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders .delete("/api/switch/links") .content(inputJson) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); }
|
SwitchController { @RequestMapping(value = "/{switchId}/ports/{port}/properties", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.SW_UPDATE_PORT_PROPERTIES }) public @ResponseBody SwitchProperty updateSwitchPortProperty(@PathVariable final String switchId, @PathVariable final String port, @RequestBody SwitchProperty switchProperty) { activityLogger.log(ActivityType.UPDATE_SW_PORT_PROPERTIES, switchId); return serviceSwitch.updateSwitchPortProperty(switchId, port, switchProperty); } @RequestMapping(value = "/list") @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_SWITCHES }) @ResponseBody List<SwitchInfo> getSwitchesDetail(
@RequestParam(value = "storeConfigurationStatus", required = false)
final boolean storeConfigurationStatus,
@RequestParam(value = "controller", required = false)
final boolean controller); @RequestMapping(value = "/{switchId}") @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_SWITCHES }) @ResponseBody SwitchInfo getSwitchDetail(@PathVariable final String switchId,
@RequestParam(value = "controller", required = false)
final boolean controller); @RequestMapping(value = "/name/{switchId}", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_SWITCH_UPDATE_NAME}) @ResponseBody SwitchInfo saveOrUpdateSwitchName(@PathVariable final String switchId,
@RequestBody final String switchName); @RequestMapping(value = "/links", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_ISL }) @ResponseBody List<IslLinkInfo> getLinksDetail(@RequestParam(value = "src_switch",
required = false) final String srcSwitch, @RequestParam(value = "src_port",
required = false) final String srcPort, @RequestParam(value = "dst_switch",
required = false) final String dstSwitch, @RequestParam(value = "dst_port",
required = false) final String dstPort); @RequestMapping(value = "/links", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.ISL_DELETE_LINK }) @ResponseBody List<IslLinkInfo> deleteIsl(@RequestBody final LinkParametersDto linkParametersDto); @RequestMapping(path = "/links/under-maintenance", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.ISL_UPDATE_MAINTENANCE}) @ResponseBody List<IslLinkInfo> updateLinkUnderMaintenance(
@RequestBody final LinkUnderMaintenanceDto linkUnderMaintenanceDto); @RequestMapping(path = "/link/props", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody LinkProps getLinkProps(
@RequestParam(value = "src_switch", required = true) final String srcSwitch,
@RequestParam(value = "src_port", required = true) final String srcPort, @RequestParam(
value = "dst_switch", required = true) final String dstSwitch, @RequestParam(
value = "dst_port", required = true) final String dstPort); @RequestMapping(path = "/link/bandwidth", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.ISL_UPDATE_BANDWIDTH}) @ResponseBody LinkMaxBandwidth updateMaxBandwidth(
@RequestParam(value = "src_switch", required = true) final String srcSwitch,
@RequestParam(value = "src_port", required = true) final String srcPort, @RequestParam(
value = "dst_switch", required = true) final String dstSwitch, @RequestParam(
value = "dst_port", required = true) final String dstPort,
@RequestBody LinkMaxBandwidth linkMaxBandwidth); @RequestMapping(path = "/link/enable-bfd", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.ISL_UPDATE_BFD_FLAG}) @ResponseBody List<IslLinkInfo> updateEnableBfdFlag(@RequestBody LinkParametersDto linkParametersDto); @RequestMapping(path = "/link/props", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @ResponseBody String updateLinkProps(@RequestBody final List<LinkProps> keys); @RequestMapping(path = "/{switchId}/rules", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_PERMISSION_RULES}) @ResponseBody String getSwitchRules(@PathVariable final String switchId); @RequestMapping(path = "/{switchId}/{port}/config", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_PORT_CONFIG}) @ResponseBody ConfiguredPort configureSwitchPort(
@RequestBody final PortConfiguration configuration,
@PathVariable final String switchId, @PathVariable final String port); @RequestMapping(path = "/{switchId}/flows", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody ResponseEntity<List<?>> getPortFlows(@PathVariable final String switchId,
@RequestParam(value = "port", required = false) final String port,
@RequestParam(value = "inventory", required = false) final boolean inventory); @RequestMapping(value = "/links/flows", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody List<FlowInfo> getIslFlows(@RequestParam(name = "src_switch",
required = true) final String srcSwitch, @RequestParam(name = "src_port",
required = true) final String srcPort, @RequestParam(name = "dst_switch",
required = true) final String dstSwitch, @RequestParam(name = "dst_port",
required = true) final String dstPort); @RequestMapping(value = "/meters/{switchId}") @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_SWITCH_METERS}) @ResponseBody SwitchMeter getSwitchMeters(@PathVariable final String switchId); @RequestMapping(value = "/under-maintenance/{switchId}", method = RequestMethod.POST) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_SWITCH_MAINTENANCE}) @ResponseBody SwitchInfo updateSwitchMaintenanceStatus(
@PathVariable("switchId") final String switchId,
@RequestBody final SwitchInfo switchInfo); @RequestMapping(value = "/{switchId}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.SW_SWITCH_DELETE }) @ResponseBody SwitchInfo deleteSwitch(@PathVariable final String switchId,
@RequestParam(name = "force", required = false) boolean force); @RequestMapping(value = "/{switchId}/ports/{port}/properties", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.SW_UPDATE_PORT_PROPERTIES }) @ResponseBody SwitchProperty updateSwitchPortProperty(@PathVariable final String switchId,
@PathVariable final String port, @RequestBody SwitchProperty switchProperty); @RequestMapping(value = "/{switchId}/ports/{port}/properties", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody SwitchProperty getSwitchPortProperty(@PathVariable final String switchId,
@PathVariable final String port); }
|
@Test public void testUpdateSwitchPortProperty() throws Exception { try { SwitchProperty switchProperty = new SwitchProperty(); switchProperty.setDiscoveryEnabled(true); String inputJson = mapToJson(switchProperty); MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders .put("/api/switch/{switchId}/ports/{port}/properties", TestSwitchMock.SWITCH_ID, TestSwitchMock.PORT) .content(inputJson) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); } catch (Exception e) { System.out.println("Exception is: " + e); } }
|
SwitchController { @RequestMapping(value = "/{switchId}/ports/{port}/properties", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) public @ResponseBody SwitchProperty getSwitchPortProperty(@PathVariable final String switchId, @PathVariable final String port) { return serviceSwitch.getSwitchPortProperty(switchId, port); } @RequestMapping(value = "/list") @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_SWITCHES }) @ResponseBody List<SwitchInfo> getSwitchesDetail(
@RequestParam(value = "storeConfigurationStatus", required = false)
final boolean storeConfigurationStatus,
@RequestParam(value = "controller", required = false)
final boolean controller); @RequestMapping(value = "/{switchId}") @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_SWITCHES }) @ResponseBody SwitchInfo getSwitchDetail(@PathVariable final String switchId,
@RequestParam(value = "controller", required = false)
final boolean controller); @RequestMapping(value = "/name/{switchId}", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_SWITCH_UPDATE_NAME}) @ResponseBody SwitchInfo saveOrUpdateSwitchName(@PathVariable final String switchId,
@RequestBody final String switchName); @RequestMapping(value = "/links", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_ISL }) @ResponseBody List<IslLinkInfo> getLinksDetail(@RequestParam(value = "src_switch",
required = false) final String srcSwitch, @RequestParam(value = "src_port",
required = false) final String srcPort, @RequestParam(value = "dst_switch",
required = false) final String dstSwitch, @RequestParam(value = "dst_port",
required = false) final String dstPort); @RequestMapping(value = "/links", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.ISL_DELETE_LINK }) @ResponseBody List<IslLinkInfo> deleteIsl(@RequestBody final LinkParametersDto linkParametersDto); @RequestMapping(path = "/links/under-maintenance", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.ISL_UPDATE_MAINTENANCE}) @ResponseBody List<IslLinkInfo> updateLinkUnderMaintenance(
@RequestBody final LinkUnderMaintenanceDto linkUnderMaintenanceDto); @RequestMapping(path = "/link/props", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody LinkProps getLinkProps(
@RequestParam(value = "src_switch", required = true) final String srcSwitch,
@RequestParam(value = "src_port", required = true) final String srcPort, @RequestParam(
value = "dst_switch", required = true) final String dstSwitch, @RequestParam(
value = "dst_port", required = true) final String dstPort); @RequestMapping(path = "/link/bandwidth", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.ISL_UPDATE_BANDWIDTH}) @ResponseBody LinkMaxBandwidth updateMaxBandwidth(
@RequestParam(value = "src_switch", required = true) final String srcSwitch,
@RequestParam(value = "src_port", required = true) final String srcPort, @RequestParam(
value = "dst_switch", required = true) final String dstSwitch, @RequestParam(
value = "dst_port", required = true) final String dstPort,
@RequestBody LinkMaxBandwidth linkMaxBandwidth); @RequestMapping(path = "/link/enable-bfd", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.ISL_UPDATE_BFD_FLAG}) @ResponseBody List<IslLinkInfo> updateEnableBfdFlag(@RequestBody LinkParametersDto linkParametersDto); @RequestMapping(path = "/link/props", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @ResponseBody String updateLinkProps(@RequestBody final List<LinkProps> keys); @RequestMapping(path = "/{switchId}/rules", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_PERMISSION_RULES}) @ResponseBody String getSwitchRules(@PathVariable final String switchId); @RequestMapping(path = "/{switchId}/{port}/config", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_PORT_CONFIG}) @ResponseBody ConfiguredPort configureSwitchPort(
@RequestBody final PortConfiguration configuration,
@PathVariable final String switchId, @PathVariable final String port); @RequestMapping(path = "/{switchId}/flows", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody ResponseEntity<List<?>> getPortFlows(@PathVariable final String switchId,
@RequestParam(value = "port", required = false) final String port,
@RequestParam(value = "inventory", required = false) final boolean inventory); @RequestMapping(value = "/links/flows", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody List<FlowInfo> getIslFlows(@RequestParam(name = "src_switch",
required = true) final String srcSwitch, @RequestParam(name = "src_port",
required = true) final String srcPort, @RequestParam(name = "dst_switch",
required = true) final String dstSwitch, @RequestParam(name = "dst_port",
required = true) final String dstPort); @RequestMapping(value = "/meters/{switchId}") @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_SWITCH_METERS}) @ResponseBody SwitchMeter getSwitchMeters(@PathVariable final String switchId); @RequestMapping(value = "/under-maintenance/{switchId}", method = RequestMethod.POST) @ResponseStatus(HttpStatus.OK) @Permissions(values = {IConstants.Permission.SW_SWITCH_MAINTENANCE}) @ResponseBody SwitchInfo updateSwitchMaintenanceStatus(
@PathVariable("switchId") final String switchId,
@RequestBody final SwitchInfo switchInfo); @RequestMapping(value = "/{switchId}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.SW_SWITCH_DELETE }) @ResponseBody SwitchInfo deleteSwitch(@PathVariable final String switchId,
@RequestParam(name = "force", required = false) boolean force); @RequestMapping(value = "/{switchId}/ports/{port}/properties", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.SW_UPDATE_PORT_PROPERTIES }) @ResponseBody SwitchProperty updateSwitchPortProperty(@PathVariable final String switchId,
@PathVariable final String port, @RequestBody SwitchProperty switchProperty); @RequestMapping(value = "/{switchId}/ports/{port}/properties", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody SwitchProperty getSwitchPortProperty(@PathVariable final String switchId,
@PathVariable final String port); }
|
@Test public void testGetSwitchPortProperties() { SwitchProperty switchProperty = new SwitchProperty(); try { when(serviceSwitch.getSwitchPortProperty(TestSwitchMock.SWITCH_ID, TestSwitchMock.PORT)) .thenReturn(switchProperty); mockMvc.perform(get("/api/switch/{switchId}/ports/{port}/properties", TestSwitchMock.SWITCH_ID, TestSwitchMock.SWITCH_PORT).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); assertTrue(true); } catch (Exception e) { assertTrue(false); } }
|
StatsController { @RequestMapping(value = "flowid/{flowid}/{startDate}/{endDate}/{downsample}/{metric}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_FLOWS }) @ResponseBody public String getFlowStats(@PathVariable String flowid, @PathVariable String startDate, @PathVariable String endDate, @PathVariable String downsample, @PathVariable String metric) throws Exception { LOGGER.info("Get stat for flow"); return statsService.getFlowStats(startDate, endDate, downsample, flowid, metric); } @RequestMapping(value = "/metrics") @ResponseStatus(HttpStatus.OK) @ResponseBody List<String> getMetricDetail(); @RequestMapping(value = "isl/{srcSwitch}/{srcPort}/{dstSwitch}/{dstPort}/{startDate}/{endDate}/{downsample}/{metric}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_ISL }) @ResponseBody String getIslStats(@PathVariable String srcSwitch, @PathVariable String srcPort,
@PathVariable String dstSwitch, @PathVariable String dstPort, @PathVariable String startDate,
@PathVariable String endDate, @PathVariable String downsample, @PathVariable String metric); @RequestMapping(value = "switchid/{switchid}/port/{port}/{startDate}/{endDate}/{downsample}/{metric}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_SWITCHES }) @ResponseBody String getPortStats(@PathVariable String switchid, @PathVariable String port,
@PathVariable String startDate, @PathVariable String endDate, @PathVariable String downsample,
@PathVariable String metric); @RequestMapping(value = "flowid/{flowid}/{startDate}/{endDate}/{downsample}/{metric}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_FLOWS }) @ResponseBody String getFlowStats(@PathVariable String flowid, @PathVariable String startDate,
@PathVariable String endDate, @PathVariable String downsample, @PathVariable String metric); @RequestMapping(value = "isl/losspackets/{srcSwitch}/{srcPort}/{dstSwitch}/{dstPort}/{startDate}/{endDate}/{downsample}/{metric}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_ISL }) @ResponseBody String getIslLossPacketStats(@PathVariable String srcSwitch, @PathVariable String srcPort,
@PathVariable String dstSwitch, @PathVariable String dstPort, @PathVariable String startDate,
@PathVariable String endDate, @PathVariable String downsample, @PathVariable String metric); @RequestMapping(value = "flow/losspackets/{flowid}/{startDate}/{endDate}/{downsample}/{direction}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_FLOWS }) @ResponseBody String getFlowLossPacketStats(@PathVariable String flowid, @PathVariable String startDate,
@PathVariable String endDate, @PathVariable String downsample, @PathVariable String direction); @RequestMapping(value = "flowpath", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_FLOWS }) @ResponseBody String getFlowPathStat(@RequestBody FlowPathStats flowPathStats); @RequestMapping(value = "switchports/{switchid}/{startDate}/{endDate}/{downsample}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_SWITCHES }) @ResponseBody List<PortInfo> getSwitchPortsStats(@PathVariable String switchid,
@PathVariable String startDate, @PathVariable String endDate, @PathVariable String downsample); @RequestMapping(value = "meter/{flowid}/{startDate}/{endDate}/{downsample}/{metric}/{direction}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) @Permissions(values = { IConstants.Permission.MENU_FLOWS }) @ResponseBody String getMeterStats(@PathVariable String flowid, @PathVariable String startDate,
@PathVariable String endDate, @PathVariable String downsample,
@PathVariable String metric, @PathVariable String direction); }
|
@Test public void testGetFlowStats() throws Exception { try { mockMvc.perform( get("/api/stats/flowid/{flowId}/{startDate}/{endDate}/{downsample}/{metric}", TestMockStats.FLOW_ID, TestMockStats.START_DATE, TestMockStats.END_DATE, TestMockStats.DOWNSAMPLE, TestMockStats.METRIC_BITS, TestMockStats.DIRECTION_FORWARD) .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); assertTrue(true); } catch (Exception ex) { assertTrue(false); } }
|
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(); }
|
@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); }
|
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(); }
|
@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()); }
|
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(); }
|
@Test public void removeWatch() { }
|
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(); }
|
@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)); }
|
WatcherService { public void discovery(SwitchId switchId, int portNo, SwitchId endSwitchId, int endPortNo, long packetNo, long currentTime) { Packet packet = Packet.of(switchId, portNo, packetNo); confirmations.remove(packet); carrier.discovered(switchId, portNo, endSwitchId, endPortNo, currentTime); } 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(); }
|
@Test public void discovery() { 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.discovery(new SwitchId(1), 1, new SwitchId(2), 1, 0, 4); w.discovery(new SwitchId(2), 1, new SwitchId(1), 1, 2, 4); w.tick(100); assertThat(w.getConfirmations().size(), is(0)); verify(carrier).discovered(eq(new SwitchId(1)), eq(1), eq(new SwitchId(2)), eq(1), anyLong()); verify(carrier).discovered(eq(new SwitchId(2)), eq(1), eq(new SwitchId(1)), eq(1), anyLong()); verify(carrier, times(2)).discovered(any(SwitchId.class), anyInt(), any(SwitchId.class), anyInt(), anyLong()); assertThat(w.getTimeouts().size(), is(0)); }
|
DecisionMakerService { void discovered(SwitchId switchId, int portNo, SwitchId endSwitchId, int endPortNo, long currentTime) { carrier.discovered(switchId, portNo, endSwitchId, endPortNo, currentTime); lastDiscovery.put(Endpoint.of(switchId, portNo), currentTime); } DecisionMakerService(IDecisionMakerCarrier carrier, int failTimeout, int awaitTime); HashMap<Endpoint, Long> getLastDiscovery(); }
|
@Test public void discovered() { DecisionMakerService w = new DecisionMakerService(carrier, 10, 5); w.discovered(new SwitchId(1), 10, new SwitchId(2), 20, 1L); w.discovered(new SwitchId(2), 20, new SwitchId(3), 30, 2L); verify(carrier).discovered(eq(new SwitchId(1)), eq(10), eq(new SwitchId(2)), eq(20), anyLong()); verify(carrier).discovered(eq(new SwitchId(2)), eq(20), eq(new SwitchId(3)), eq(30), anyLong()); }
|
DecisionMakerService { void failed(SwitchId switchId, int portNo, long currentTime) { Endpoint endpoint = Endpoint.of(switchId, portNo); if (!lastDiscovery.containsKey(endpoint)) { lastDiscovery.put(endpoint, currentTime - awaitTime); } long timeWindow = lastDiscovery.get(endpoint) + failTimeout; if (currentTime >= timeWindow) { carrier.failed(switchId, portNo, currentTime); } } DecisionMakerService(IDecisionMakerCarrier carrier, int failTimeout, int awaitTime); HashMap<Endpoint, Long> getLastDiscovery(); }
|
@Test public void failed() { DecisionMakerService w = new DecisionMakerService(carrier, 10, 5); w.failed(new SwitchId(1), 10, 0); w.failed(new SwitchId(1), 10, 1); w.failed(new SwitchId(1), 10, 11); w.failed(new SwitchId(1), 10, 12); verify(carrier, times(2)).failed(eq(new SwitchId(1)), eq(10), anyLong()); w.discovered(new SwitchId(1), 10, new SwitchId(2), 20, 20); verify(carrier).discovered(new SwitchId(1), 10, new SwitchId(2), 20, 20); reset(carrier); w.failed(new SwitchId(1), 10, 21); w.failed(new SwitchId(1), 10, 23); w.failed(new SwitchId(1), 10, 24); verify(carrier, never()).failed(any(SwitchId.class), anyInt(), anyInt()); w.failed(new SwitchId(1), 10, 31); verify(carrier).failed(new SwitchId(1), 10, 31); }
|
SessionService implements IService, IInputTranslator { public Session open(IOFSwitch sw) { return open(new MessageContext(), sw); } Session open(IOFSwitch sw); Session open(MessageContext context, IOFSwitch sw); @Override void setup(FloodlightModuleContext moduleContext); @Override Command makeCommand(CommandContext context, OfInput input); }
|
@Test public void positive() throws Exception { IOFSwitch sw = createMock(IOFSwitch.class); setupSwitchMock(sw, dpId); swWriteAlwaysSuccess(sw); doneWithSetUp(sw); CompletableFuture<Optional<OFMessage>> future; OFPacketOut pktOut = makePacketOut(sw.getOFFactory(), 1); try (Session session = subject.open(context, sw)) { future = session.write(pktOut); } Assert.assertFalse(future.isDone()); List<OFMessage> swActualWrite = swWriteMessages.getValues(); Assert.assertEquals(2, swActualWrite.size()); Assert.assertEquals(pktOut, swActualWrite.get(0)); Assert.assertEquals(OFType.BARRIER_REQUEST, swActualWrite.get(1).getType()); completeSessions(sw); Assert.assertTrue(future.isDone()); Optional<OFMessage> response = future.get(); Assert.assertFalse(response.isPresent()); }
@Test public void switchWriteError() throws Throwable { IOFSwitch sw = createMock(IOFSwitch.class); setupSwitchMock(sw, dpId); swWriteSecondFail(sw); doneWithSetUp(sw); OFFactory ofFactory = sw.getOFFactory(); CompletableFuture<Optional<OFMessage>> future = null; try (Session session = subject.open(context, sw)) { session.write(makePacketOut(ofFactory, 1)); future = session.write(makePacketOut(ofFactory, 2)); } try { future.get(1, TimeUnit.SECONDS); Assert.fail(); } catch (ExecutionException e) { Assert.assertNotNull(e.getCause()); Assert.assertTrue(e.getCause() instanceof SwitchWriteException); } }
@Test public void sessionBarrierWriteError() throws Exception { IOFSwitch sw = createMock(IOFSwitch.class); setupSwitchMock(sw, dpId); swWriteSecondFail(sw); doneWithSetUp(sw); CompletableFuture<Optional<OFMessage>> future = null; try (Session session = subject.open(context, sw)) { future = session.write(makePacketOut(sw.getOFFactory(), 1)); } try { future.get(1, TimeUnit.SECONDS); Assert.fail(); } catch (ExecutionException e) { Assert.assertNotNull(e.getCause()); Assert.assertTrue(e.getCause() instanceof SessionCloseException); } }
|
ConnectedDevicesService implements IService, IInputTranslator { @VisibleForTesting LldpPacketData deserializeLldp(Ethernet eth, SwitchId switchId, long cookie) { try { List<Integer> vlans = new ArrayList<>(); IPacket payload = EthernetPacketToolbox.extractPayload(eth, vlans); if (payload instanceof LLDP) { LldpPacket lldpPacket = new LldpPacket((LLDP) payload); return new LldpPacketData(lldpPacket, vlans); } } catch (Exception exception) { logger.info("Could not deserialize LLDP packet {} on switch {}. Cookie {}. Deserialization failure: {}", eth, switchId, Cookie.toString(cookie), exception.getMessage(), exception); return null; } logger.info("Got invalid lldp packet: {} on switch {}. Cookie {}", eth, switchId, cookie); return null; } @Override Command makeCommand(CommandContext context, OfInput input); @Override void setup(FloodlightModuleContext context); }
|
@Test public void deserializeLldpTest() { Ethernet ethernet = buildEthernet(srcAndDstMacAddresses, ethTypeToByteArray(EthType.LLDP), LldpPacketTest.packet); LldpPacketData data = service.deserializeLldp(ethernet, null, 0); assertNotNull(data); assertTrue(data.getVlans().isEmpty()); assertEquals(LldpPacketTest.buildLldpPacket(LldpPacketTest.packet), data.getLldpPacket()); }
@Test public void deserializeLldpWithVlanTest() { short vlan = 1234; Ethernet ethernet = buildEthernet(srcAndDstMacAddresses, ethTypeToByteArray(EthType.VLAN_FRAME), shortToByteArray(vlan), ethTypeToByteArray(EthType.LLDP), LldpPacketTest.packet); LldpPacketData data = service.deserializeLldp(ethernet, null, 0); assertNotNull(data); assertEquals(1, data.getVlans().size()); assertEquals(Integer.valueOf(vlan), data.getVlans().get(0)); assertEquals(LldpPacketTest.buildLldpPacket(LldpPacketTest.packet), data.getLldpPacket()); }
@Test public void deserializeLldpWithTwoVlanTest() { short innerVlan = 1234; short outerVlan = 2345; Ethernet ethernet = buildEthernet(srcAndDstMacAddresses, ethTypeToByteArray(EthType.VLAN_FRAME), shortToByteArray(outerVlan), ethTypeToByteArray(EthType.VLAN_FRAME), shortToByteArray(innerVlan), ethTypeToByteArray(EthType.LLDP), LldpPacketTest.packet); LldpPacketData data = service.deserializeLldp(ethernet, null, 0); assertNotNull(data); assertEquals(2, data.getVlans().size()); assertEquals(Integer.valueOf(outerVlan), data.getVlans().get(0)); assertEquals(Integer.valueOf(innerVlan), data.getVlans().get(1)); assertEquals(LldpPacketTest.buildLldpPacket(LldpPacketTest.packet), data.getLldpPacket()); }
@Test public void deserializeLldpWithQinQVlansTest() { short vlan1 = 1234; short vlan2 = 2345; short vlan3 = 4000; Ethernet ethernet = buildEthernet(srcAndDstMacAddresses, ethTypeToByteArray(EthType.Q_IN_Q), shortToByteArray(vlan1), ethTypeToByteArray(EthType.BRIDGING), shortToByteArray(vlan2), ethTypeToByteArray(EthType.VLAN_FRAME), shortToByteArray(vlan3), ethTypeToByteArray(EthType.LLDP), LldpPacketTest.packet); LldpPacketData data = service.deserializeLldp(ethernet, null, 0); assertNotNull(data); assertEquals(3, data.getVlans().size()); assertEquals(Integer.valueOf(vlan1), data.getVlans().get(0)); assertEquals(Integer.valueOf(vlan2), data.getVlans().get(1)); assertEquals(Integer.valueOf(vlan3), data.getVlans().get(2)); assertEquals(LldpPacketTest.buildLldpPacket(LldpPacketTest.packet), data.getLldpPacket()); }
|
ConnectedDevicesService implements IService, IInputTranslator { @VisibleForTesting ArpPacketData deserializeArp(Ethernet eth, SwitchId switchId, long cookie) { try { List<Integer> vlans = new ArrayList<>(); IPacket payload = EthernetPacketToolbox.extractPayload(eth, vlans); if (payload instanceof ARP) { return new ArpPacketData((ARP) payload, vlans); } } catch (Exception exception) { logger.info("Could not deserialize ARP packet {} on switch {}. Cookie {}. Deserialization failure: {}", eth, switchId, Cookie.toString(cookie), exception.getMessage(), exception); return null; } logger.info("Got invalid ARP packet: {} on switch {}. Cookie {}", eth, switchId, cookie); return null; } @Override Command makeCommand(CommandContext context, OfInput input); @Override void setup(FloodlightModuleContext context); }
|
@Test public void deserializeArpTest() throws PacketParsingException { Ethernet ethernet = buildEthernet(srcAndDstMacAddresses, ethTypeToByteArray(EthType.ARP), arpPacket); ArpPacketData data = service.deserializeArp(ethernet, null, 0); assertNotNull(data); assertTrue(data.getVlans().isEmpty()); assertEquals(buildArpPacket(arpPacket), data.getArp()); }
@Test public void deserializeArpWithVlanTest() throws PacketParsingException { short vlan = 1234; Ethernet ethernet = buildEthernet(srcAndDstMacAddresses, ethTypeToByteArray(EthType.VLAN_FRAME), shortToByteArray(vlan), ethTypeToByteArray(EthType.ARP), arpPacket); ArpPacketData data = service.deserializeArp(ethernet, null, 0); assertNotNull(data); assertEquals(1, data.getVlans().size()); assertEquals(Integer.valueOf(vlan), data.getVlans().get(0)); assertEquals(buildArpPacket(arpPacket), data.getArp()); }
@Test public void deserializeArpWithTwoVlanTest() throws PacketParsingException { short innerVlan = 1234; short outerVlan = 2345; Ethernet ethernet = buildEthernet(srcAndDstMacAddresses, ethTypeToByteArray(EthType.VLAN_FRAME), shortToByteArray(outerVlan), ethTypeToByteArray(EthType.VLAN_FRAME), shortToByteArray(innerVlan), ethTypeToByteArray(EthType.ARP), arpPacket); ArpPacketData data = service.deserializeArp(ethernet, null, 0); assertNotNull(data); assertEquals(2, data.getVlans().size()); assertEquals(Integer.valueOf(outerVlan), data.getVlans().get(0)); assertEquals(Integer.valueOf(innerVlan), data.getVlans().get(1)); assertEquals(buildArpPacket(arpPacket), data.getArp()); }
@Test public void deserializeArpWithQinQVlansTest() throws PacketParsingException { short vlan1 = 1234; short vlan2 = 2345; short vlan3 = 4000; Ethernet ethernet = buildEthernet(srcAndDstMacAddresses, ethTypeToByteArray(EthType.Q_IN_Q), shortToByteArray(vlan1), ethTypeToByteArray(EthType.BRIDGING), shortToByteArray(vlan2), ethTypeToByteArray(EthType.VLAN_FRAME), shortToByteArray(vlan3), ethTypeToByteArray(EthType.ARP), arpPacket); ArpPacketData data = service.deserializeArp(ethernet, null, 0); assertNotNull(data); assertEquals(3, data.getVlans().size()); assertEquals(Integer.valueOf(vlan1), data.getVlans().get(0)); assertEquals(Integer.valueOf(vlan2), data.getVlans().get(1)); assertEquals(Integer.valueOf(vlan3), data.getVlans().get(2)); assertEquals(buildArpPacket(arpPacket), data.getArp()); }
|
FloodlightModuleConfigurationProvider extends ValidatingConfigurationProvider { public static FloodlightModuleConfigurationProvider of(FloodlightModuleContext moduleContext, IFloodlightModule module) { Map<String, String> configData = moduleContext.getConfigParams(module); FloodlightModuleConfigurationProvider provider = new FloodlightModuleConfigurationProvider(configData); dumpConfigData(module.getClass(), configData); return provider; } protected FloodlightModuleConfigurationProvider(Map<String, String> configData); static FloodlightModuleConfigurationProvider of(FloodlightModuleContext moduleContext,
IFloodlightModule module); static FloodlightModuleConfigurationProvider of(FloodlightModuleContext moduleContext,
Class<? extends IFloodlightModule> module); }
|
@Test public void shouldCreateConfigFromContextParameters() { FloodlightModuleContext context = new FloodlightModuleContext(); IFloodlightModule module = niceMock(IFloodlightModule.class); context.addConfigParam(module, "bootstrap-servers", TEST_BOOTSTRAP_SERVERS); FloodlightModuleConfigurationProvider provider = FloodlightModuleConfigurationProvider.of(context, module); KafkaChannelConfig kafkaConfig = provider.getConfiguration(KafkaChannelConfig.class); assertEquals(TEST_BOOTSTRAP_SERVERS, kafkaConfig.getBootstrapServers()); }
@Test public void shouldCreateEnvConfigFromContextParameters() { FloodlightModuleContext context = new FloodlightModuleContext(); IFloodlightModule module = niceMock(IFloodlightModule.class); context.addConfigParam(module, "environment-naming-prefix", TEST_PREFIX); FloodlightModuleConfigurationProvider provider = FloodlightModuleConfigurationProvider.of(context, module); EnvironmentFloodlightConfig environmentConfig = provider.getConfiguration(EnvironmentFloodlightConfig.class); assertEquals(TEST_PREFIX, environmentConfig.getNamingPrefix()); }
@Test public void shouldCreateConfigWithEnvPrefix() { FloodlightModuleContext context = new FloodlightModuleContext(); IFloodlightModule module = niceMock(IFloodlightModule.class); context.addConfigParam(module, "environment-naming-prefix", TEST_PREFIX); FloodlightModuleConfigurationProvider provider = FloodlightModuleConfigurationProvider.of(context, module); KafkaChannelConfig kafkaConsumerConfig = provider.getConfiguration(KafkaChannelConfig.class); assertEquals(TEST_PREFIX + "_floodlight", kafkaConsumerConfig.getGroupId()); }
|
PingResponseCommand extends PingCommand { @Override public Command call() { log.debug("{} - {}", getClass().getCanonicalName(), input); byte[] payload = unwrap(); if (payload == null) { return null; } log.info("Receive flow ping packet from switch {} OF-xid:{}", input.getDpId(), input.getMessage().getXid()); try { PingData pingData = decode(payload); getContext().setCorrelationId(pingData.getPingId().toString()); process(pingData); } catch (CorruptedNetworkDataException e) { logPing.error(String.format("dpid:%s %s", input.getDpId(), e)); } return null; } PingResponseCommand(CommandContext context, OfInput input); @Override Command call(); }
|
@Test public void success() throws Exception { final PingService realPingService = new PingService(); moduleContext.addService(PingService.class, realPingService); final ISwitchManager realSwitchManager = new SwitchManager(); moduleContext.addService(ISwitchManager.class, realSwitchManager); InputService inputService = createMock(InputService.class); moduleContext.addService(InputService.class, inputService); inputService.addTranslator(eq(OFType.PACKET_IN), anyObject()); replayAll(); final DatapathId dpIdBeta = DatapathId.of(0x0000fffe000002L); final Ping ping = new Ping(new NetworkEndpoint(new SwitchId(dpIdBeta.getLong()), 8), new NetworkEndpoint(new SwitchId(dpId.getLong()), 9), new FlowTransitEncapsulation(2, FlowEncapsulationType.TRANSIT_VLAN), 3); final PingData payload = PingData.of(ping); moduleContext.addConfigParam(new PathVerificationService(), "hmac256-secret", "secret"); realPingService.setup(moduleContext); byte[] signedPayload = realPingService.getSignature().sign(payload); byte[] wireData = realPingService.wrapData(ping, signedPayload).serialize(); OFFactory ofFactory = new OFFactoryVer13(); OFPacketIn message = ofFactory.buildPacketIn() .setReason(OFPacketInReason.ACTION).setXid(1L) .setCookie(PingService.OF_CATCH_RULE_COOKIE) .setData(wireData) .build(); FloodlightContext metadata = new FloodlightContext(); IPacket decodedEthernet = new Ethernet().deserialize(wireData, 0, wireData.length); Assert.assertTrue(decodedEthernet instanceof Ethernet); IFloodlightProviderService.bcStore.put( metadata, IFloodlightProviderService.CONTEXT_PI_PAYLOAD, (Ethernet) decodedEthernet); OfInput input = new OfInput(iofSwitch, message, metadata); final PingResponseCommand command = makeCommand(input); command.call(); final List<Message> replies = kafkaMessageCatcher.getValues(); Assert.assertEquals(1, replies.size()); InfoMessage response = (InfoMessage) replies.get(0); PingResponse pingResponse = (PingResponse) response.getData(); Assert.assertNull(pingResponse.getError()); Assert.assertNotNull(pingResponse.getMeters()); Assert.assertEquals(payload.getPingId(), pingResponse.getPingId()); }
|
IngressFlowModFactory { public OFFlowMod makeOuterVlanMatchSharedMessage() { FlowEndpoint endpoint = command.getEndpoint(); FlowSharedSegmentCookie cookie = FlowSharedSegmentCookie.builder(SharedSegmentType.QINQ_OUTER_VLAN) .portNumber(endpoint.getPortNumber()) .vlanId(endpoint.getOuterVlanId()) .build(); return flowModBuilderFactory.makeBuilder(of, TableId.of(SwitchManager.PRE_INGRESS_TABLE_ID)) .setCookie(U64.of(cookie.getValue())) .setMatch(of.buildMatch() .setExact(MatchField.IN_PORT, OFPort.of(endpoint.getPortNumber())) .setExact(MatchField.VLAN_VID, OFVlanVidMatch.ofVlan(endpoint.getOuterVlanId())) .build()) .setInstructions(makeOuterVlanMatchInstructions()) .build(); } IngressFlowModFactory(
OfFlowModBuilderFactory flowModBuilderFactory, IngressFlowSegmentBase command, IOFSwitch sw,
Set<SwitchFeature> features); OFFlowMod makeOuterOnlyVlanForwardMessage(MeterId effectiveMeterId); OFFlowMod makeSingleVlanForwardMessage(MeterId effectiveMeterId); OFFlowMod makeDoubleVlanForwardMessage(MeterId effectiveMeterId); OFFlowMod makeDefaultPortForwardMessage(MeterId effectiveMeterId); OFFlowMod makeOuterVlanMatchSharedMessage(); OFFlowMod makeOuterOnlyVlanServer42IngressFlowMessage(int server42UpdPortOffset); OFFlowMod makeDefaultPortServer42IngressFlowMessage(int server42UpdPortOffset); OFFlowMod makeCustomerPortSharedCatchMessage(); OFFlowMod makeLldpInputCustomerFlowMessage(); OFFlowMod makeArpInputCustomerFlowMessage(); Optional<OFFlowMod> makeServer42InputFlowMessage(int server42UpdPortOffset); }
|
@Test public void makeOuterVlanMatchSharedMessage() { final IngressFlowModFactory factory = makeFactory(); final IngressFlowSegmentBase command = factory.getCommand(); final FlowEndpoint endpoint = command.getEndpoint(); RoutingMetadata metadata = RoutingMetadata.builder() .outerVlanId(endpoint.getOuterVlanId()) .build(Collections.emptySet()); OFFlowAdd expected = of.buildFlowAdd() .setTableId(getTargetPreIngressTableId()) .setPriority(FlowSegmentCommand.FLOW_PRIORITY) .setCookie(U64.of( FlowSharedSegmentCookie.builder(SharedSegmentType.QINQ_OUTER_VLAN) .portNumber(endpoint.getPortNumber()) .vlanId(endpoint.getOuterVlanId()) .build().getValue())) .setMatch(OfAdapter.INSTANCE.matchVlanId(of, of.buildMatch(), endpoint.getOuterVlanId()) .setExact(MatchField.IN_PORT, OFPort.of(endpoint.getPortNumber())) .build()) .setInstructions(ImmutableList.of( of.instructions().applyActions(Collections.singletonList(of.actions().popVlan())), of.instructions().writeMetadata(metadata.getValue(), metadata.getMask()), of.instructions().gotoTable(TableId.of(SwitchManager.INGRESS_TABLE_ID)))) .build(); verifyOfMessageEquals(expected, factory.makeOuterVlanMatchSharedMessage()); }
|
IngressFlowModFactory { public OFFlowMod makeCustomerPortSharedCatchMessage() { FlowEndpoint endpoint = command.getEndpoint(); return flowModBuilderFactory.makeBuilder(of, TableId.of(SwitchManager.INPUT_TABLE_ID)) .setPriority(SwitchManager.INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE) .setCookie(U64.of(Cookie.encodeIngressRulePassThrough(endpoint.getPortNumber()))) .setMatch(of.buildMatch() .setExact(MatchField.IN_PORT, OFPort.of(endpoint.getPortNumber())) .build()) .setInstructions(makeCustomerPortSharedCatchInstructions()) .build(); } IngressFlowModFactory(
OfFlowModBuilderFactory flowModBuilderFactory, IngressFlowSegmentBase command, IOFSwitch sw,
Set<SwitchFeature> features); OFFlowMod makeOuterOnlyVlanForwardMessage(MeterId effectiveMeterId); OFFlowMod makeSingleVlanForwardMessage(MeterId effectiveMeterId); OFFlowMod makeDoubleVlanForwardMessage(MeterId effectiveMeterId); OFFlowMod makeDefaultPortForwardMessage(MeterId effectiveMeterId); OFFlowMod makeOuterVlanMatchSharedMessage(); OFFlowMod makeOuterOnlyVlanServer42IngressFlowMessage(int server42UpdPortOffset); OFFlowMod makeDefaultPortServer42IngressFlowMessage(int server42UpdPortOffset); OFFlowMod makeCustomerPortSharedCatchMessage(); OFFlowMod makeLldpInputCustomerFlowMessage(); OFFlowMod makeArpInputCustomerFlowMessage(); Optional<OFFlowMod> makeServer42InputFlowMessage(int server42UpdPortOffset); }
|
@Test public void makeCustomerPortSharedCatchInstallMessage() { IngressFlowModFactory factory = makeFactory(); FlowEndpoint endpoint = factory.getCommand().getEndpoint(); OFFlowMod expected = of.buildFlowAdd() .setTableId(TableId.of(SwitchManager.INPUT_TABLE_ID)) .setPriority(SwitchManager.INGRESS_CUSTOMER_PORT_RULE_PRIORITY_MULTITABLE) .setCookie(U64.of(Cookie.encodeIngressRulePassThrough(endpoint.getPortNumber()))) .setMatch(of.buildMatch().setExact(MatchField.IN_PORT, OFPort.of(endpoint.getPortNumber())).build()) .setInstructions(Collections.singletonList(of.instructions().gotoTable( TableId.of(SwitchManager.PRE_INGRESS_TABLE_ID)))) .build(); verifyOfMessageEquals(expected, factory.makeCustomerPortSharedCatchMessage()); }
|
EthernetPacketToolbox { public static IPacket extractPayload(Ethernet packet, List<Integer> vlanStack) { short rootVlan = packet.getVlanID(); if (0 < rootVlan) { vlanStack.add((int) rootVlan); } IPacket payload = packet.getPayload(); while (payload instanceof VlanTag) { short vlanId = ((VlanTag) payload).getVlanId(); vlanStack.add((int) vlanId); payload = payload.getPayload(); } return payload; } private EthernetPacketToolbox(); static IPacket injectVlan(IPacket payload, int vlanId, EthType type); static IPacket extractPayload(Ethernet packet, List<Integer> vlanStack); }
|
@Test public void extractEthernetPayloadTest() { short vlan1 = 1234; short vlan2 = 2345; short vlan3 = 4000; byte[] originPayload = new byte[]{0x55, (byte) 0xAA}; Ethernet ethernet = buildEthernet( new byte[]{ 0x01, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x01, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B }, ethTypeToByteArray(EthType.Q_IN_Q), shortToByteArray(vlan1), ethTypeToByteArray(EthType.BRIDGING), shortToByteArray(vlan2), ethTypeToByteArray(EthType.VLAN_FRAME), shortToByteArray(vlan3), ethTypeToByteArray(EthType.IPv4), originPayload); List<Integer> vlans = new ArrayList<>(); IPacket payload = EthernetPacketToolbox.extractPayload(ethernet, vlans); assertEquals(3, vlans.size()); assertEquals(Integer.valueOf(vlan1), vlans.get(0)); assertEquals(Integer.valueOf(vlan2), vlans.get(1)); assertEquals(Integer.valueOf(vlan3), vlans.get(2)); assertArrayEquals(originPayload, payload.serialize()); }
|
OfFlowPresenceVerifier { public List<OFFlowMod> getMissing() { return expectedOfFlows.values().stream() .flatMap(Collection::stream) .collect(Collectors.toList()); } OfFlowPresenceVerifier(
IOfFlowDumpProducer dumpProducer, List<OFFlowMod> expectedFlows, Set<SwitchFeature> switchFeatures); List<OFFlowMod> getMissing(); }
|
@Test public void inaccurateSetFieldVlanVidActionNegative() { OfFlowPresenceVerifier presenceVerifier = testInaccurateSetFieldVlanVidAction(Collections.emptySet()); Assert.assertFalse(presenceVerifier.getMissing().isEmpty()); }
@Test public void inaccurateSetFieldVlanVidActionPositive() { OfFlowPresenceVerifier presenceVerifier = testInaccurateSetFieldVlanVidAction(Collections.singleton( SwitchFeature.INACCURATE_SET_VLAN_VID_ACTION)); Assert.assertTrue(presenceVerifier.getMissing().isEmpty()); }
|
CorrelationContext { public static String getId() { return Optional.ofNullable(ID.get()).orElse(DEFAULT_CORRELATION_ID); } private CorrelationContext(); static String getId(); static CorrelationContextClosable create(String correlationId); }
|
@Ignore("Fix applying aspects to test classes") @Test @NewCorrelationContextRequired public void shouldInitializeCorrelationId() { String correlationId = CorrelationContext.getId(); assertNotEquals(DEFAULT_CORRELATION_ID, correlationId); }
|
NoviflowSpecificFeature extends AbstractFeature { static boolean isNoviSwitch(IOFSwitch sw) { if (sw == null || sw.getSwitchDescription() == null) { return false; } String manufacturer = getManufacturer(sw); if (E_SWITCH_MANUFACTURER_DESCRIPTION.equalsIgnoreCase(manufacturer)) { return true; } SwitchDescription description = sw.getSwitchDescription(); if (E_SWITCH_HARDWARE_DESCRIPTION_REGEX.matcher( Optional.ofNullable(description.getHardwareDescription()).orElse("")).matches()) { return true; } return manufacturer.toLowerCase().contains(NOVIFLOW_MANUFACTURER_SUFFIX); } static final String NOVIFLOW_MANUFACTURER_SUFFIX; }
|
@Test public void testIsNoviSwitch() { assertTrue(isNoviSwitch(makeSwitchMock("NoviFlow Inc", "NW400.4.0", "NS21100"))); assertTrue(isNoviSwitch(makeSwitchMock("NoviFlow Inc", "NW500.2.0_dev", "NS21100"))); assertTrue(isNoviSwitch(makeSwitchMock("NoviFlow Inc", "NW500.0.1", "WB5164-E"))); assertTrue(isNoviSwitch(makeSwitchMock("NoviFlow Inc", "NW500.0.1", "SM5000-SM"))); assertTrue(isNoviSwitch(makeSwitchMock("E", "NW400.4.0", "WB5164"))); assertFalse(isNoviSwitch(makeSwitchMock("Common Inc", "Soft123", "Hard123"))); assertFalse(isNoviSwitch(makeSwitchMock("Nicira, Inc.", "Soft123", "Hard123"))); assertFalse(isNoviSwitch(makeSwitchMock("2004-2016 Centec Networks Inc", "2.8.16.21", "48T"))); assertFalse(isNoviSwitch(makeSwitchMock("Sonus Networks Inc, 4 Technology Park Dr, Westford, MA 01886, USA", "8.1.0.14", "VX3048"))); }
|
NoviflowSpecificFeature extends AbstractFeature { static boolean isWbSeries(IOFSwitch sw) { if (! isNoviSwitch(sw)) { return false; } if (E_SWITCH_MANUFACTURER_DESCRIPTION.equalsIgnoreCase(getManufacturer(sw))) { return true; } Optional<SwitchDescription> description = Optional.ofNullable(sw.getSwitchDescription()); return E_SWITCH_HARDWARE_DESCRIPTION_REGEX.matcher( description .map(SwitchDescription::getHardwareDescription) .orElse("")).matches(); } static final String NOVIFLOW_MANUFACTURER_SUFFIX; }
|
@Test public void testIsWbSeries() { assertTrue(isWbSeries(makeSwitchMock("NoviFlow Inc", "NW500.0.1", "WB5164-E"))); assertTrue(isWbSeries(makeSwitchMock("E", "NW400.4.0", "WB5164"))); assertFalse(isWbSeries(makeSwitchMock("NoviFlow Inc", "NW400.4.0", "NS21100"))); assertFalse(isWbSeries(makeSwitchMock("NoviFlow Inc", "NW500.2.0_dev", "NS21100"))); assertFalse(isWbSeries(makeSwitchMock("NoviFlow Inc", "NW500.0.1", "SM5000-SM"))); assertFalse(isWbSeries(makeSwitchMock("Common Inc", "Soft123", "Hard123"))); assertFalse(isWbSeries(makeSwitchMock("Nicira, Inc.", "Soft123", "Hard123"))); assertFalse(isWbSeries(makeSwitchMock("2004-2016 Centec Networks Inc", "2.8.16.21", "48T"))); assertFalse(isWbSeries(makeSwitchMock("Sonus Networks Inc, 4 Technology Park Dr, Westford, MA 01886, USA", "8.1.0.14", "VX3048"))); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.