target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void addWatch() { NetworkWatcherService w = makeService(); w.addWatch(Endpoint.of(new SwitchId(1), 1), 1); w.addWatch(Endpoint.of(new SwitchId(1), 2), 1); w.addWatch(Endpoint.of(new SwitchId(2), 1), 2); w.addWatch(Endpoint.of(new SwitchId(2), 1), 2); w.addWatch(Endpoint.of(new SwitchId(2), 2), 3); assertThat(w.getConfirmedPackets().size(), is(0)); assertThat(w.getTimeouts().size(), is(3)); verify(carrier, times(5)).sendDiscovery(any(DiscoverIslCommandData.class)); }
|
public void addWatch(Endpoint endpoint) { addWatch(endpoint, now()); }
|
NetworkWatcherService { public void addWatch(Endpoint endpoint) { addWatch(endpoint, now()); } }
|
NetworkWatcherService { public void addWatch(Endpoint endpoint) { addWatch(endpoint, now()); } NetworkWatcherService(
IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); @VisibleForTesting NetworkWatcherService(
Clock clock, IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime,
Integer taskId); }
|
NetworkWatcherService { public void addWatch(Endpoint endpoint) { addWatch(endpoint, now()); } NetworkWatcherService(
IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); @VisibleForTesting NetworkWatcherService(
Clock clock, IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime,
Integer taskId); void addWatch(Endpoint endpoint); void removeWatch(Endpoint endpoint); void tick(); void confirmation(Endpoint endpoint, long packetNo); void discovery(IslInfoData discoveryEvent); void roundTripDiscovery(Endpoint endpoint, long packetId); }
|
NetworkWatcherService { public void addWatch(Endpoint endpoint) { addWatch(endpoint, now()); } NetworkWatcherService(
IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); @VisibleForTesting NetworkWatcherService(
Clock clock, IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime,
Integer taskId); void addWatch(Endpoint endpoint); void removeWatch(Endpoint endpoint); void tick(); void confirmation(Endpoint endpoint, long packetNo); void discovery(IslInfoData discoveryEvent); void roundTripDiscovery(Endpoint endpoint, long packetId); }
|
@Test public void removeWatch() { NetworkWatcherService w = makeService(); w.addWatch(Endpoint.of(new SwitchId(1), 1), 1); w.addWatch(Endpoint.of(new SwitchId(1), 2), 2); w.addWatch(Endpoint.of(new SwitchId(2), 1), 3); w.addWatch(Endpoint.of(new SwitchId(2), 2), 4); w.addWatch(Endpoint.of(new SwitchId(3), 1), 5); verify(carrier, times(5)).sendDiscovery(any(DiscoverIslCommandData.class)); w.confirmation(Endpoint.of(new SwitchId(1), 2), 1); w.confirmation(Endpoint.of(new SwitchId(2), 1), 2); assertThat(w.getConfirmedPackets().size(), is(2)); assertThat(w.getTimeouts().size(), is(5)); assertThat(w.getDiscoveryPackets().size(), is(3)); w.removeWatch(Endpoint.of(new SwitchId(1), 2)); w.removeWatch(Endpoint.of(new SwitchId(2), 2)); verify(carrier).clearDiscovery(Endpoint.of(new SwitchId(1), 2)); verify(carrier).clearDiscovery(Endpoint.of(new SwitchId(2), 2)); assertThat(w.getConfirmedPackets().size(), is(1)); assertThat(w.getDiscoveryPackets().size(), is(2)); w.tick(100); assertThat(w.getTimeouts().size(), is(0)); }
|
public void removeWatch(Endpoint endpoint) { log.debug("Watcher service receive REMOVE-watch request for {}", endpoint); carrier.clearDiscovery(endpoint); discoveryPackets.removeIf(packet -> packet.endpoint.equals(endpoint)); roundTripPackets.removeIf(packet -> packet.endpoint.equals(endpoint)); confirmedPackets.removeIf(packet -> packet.endpoint.equals(endpoint)); lastSeenRoundTrip.remove(endpoint); }
|
NetworkWatcherService { public void removeWatch(Endpoint endpoint) { log.debug("Watcher service receive REMOVE-watch request for {}", endpoint); carrier.clearDiscovery(endpoint); discoveryPackets.removeIf(packet -> packet.endpoint.equals(endpoint)); roundTripPackets.removeIf(packet -> packet.endpoint.equals(endpoint)); confirmedPackets.removeIf(packet -> packet.endpoint.equals(endpoint)); lastSeenRoundTrip.remove(endpoint); } }
|
NetworkWatcherService { public void removeWatch(Endpoint endpoint) { log.debug("Watcher service receive REMOVE-watch request for {}", endpoint); carrier.clearDiscovery(endpoint); discoveryPackets.removeIf(packet -> packet.endpoint.equals(endpoint)); roundTripPackets.removeIf(packet -> packet.endpoint.equals(endpoint)); confirmedPackets.removeIf(packet -> packet.endpoint.equals(endpoint)); lastSeenRoundTrip.remove(endpoint); } NetworkWatcherService(
IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); @VisibleForTesting NetworkWatcherService(
Clock clock, IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime,
Integer taskId); }
|
NetworkWatcherService { public void removeWatch(Endpoint endpoint) { log.debug("Watcher service receive REMOVE-watch request for {}", endpoint); carrier.clearDiscovery(endpoint); discoveryPackets.removeIf(packet -> packet.endpoint.equals(endpoint)); roundTripPackets.removeIf(packet -> packet.endpoint.equals(endpoint)); confirmedPackets.removeIf(packet -> packet.endpoint.equals(endpoint)); lastSeenRoundTrip.remove(endpoint); } NetworkWatcherService(
IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); @VisibleForTesting NetworkWatcherService(
Clock clock, IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime,
Integer taskId); void addWatch(Endpoint endpoint); void removeWatch(Endpoint endpoint); void tick(); void confirmation(Endpoint endpoint, long packetNo); void discovery(IslInfoData discoveryEvent); void roundTripDiscovery(Endpoint endpoint, long packetId); }
|
NetworkWatcherService { public void removeWatch(Endpoint endpoint) { log.debug("Watcher service receive REMOVE-watch request for {}", endpoint); carrier.clearDiscovery(endpoint); discoveryPackets.removeIf(packet -> packet.endpoint.equals(endpoint)); roundTripPackets.removeIf(packet -> packet.endpoint.equals(endpoint)); confirmedPackets.removeIf(packet -> packet.endpoint.equals(endpoint)); lastSeenRoundTrip.remove(endpoint); } NetworkWatcherService(
IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); @VisibleForTesting NetworkWatcherService(
Clock clock, IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime,
Integer taskId); void addWatch(Endpoint endpoint); void removeWatch(Endpoint endpoint); void tick(); void confirmation(Endpoint endpoint, long packetNo); void discovery(IslInfoData discoveryEvent); void roundTripDiscovery(Endpoint endpoint, long packetId); }
|
@Test public void tick() { NetworkWatcherService w = makeService(); w.addWatch(Endpoint.of(new SwitchId(1), 1), 1); w.addWatch(Endpoint.of(new SwitchId(1), 2), 1); w.addWatch(Endpoint.of(new SwitchId(2), 1), 2); w.addWatch(Endpoint.of(new SwitchId(2), 1), 2); w.addWatch(Endpoint.of(new SwitchId(2), 2), 3); assertThat(w.getConfirmedPackets().size(), is(0)); assertThat(w.getTimeouts().size(), is(3)); verify(carrier, times(5)).sendDiscovery(any(DiscoverIslCommandData.class)); w.confirmation(Endpoint.of(new SwitchId(1), 1), 0); w.confirmation(Endpoint.of(new SwitchId(2), 1), 2); assertThat(w.getConfirmedPackets().size(), is(2)); w.tick(100); assertThat(w.getConfirmedPackets().size(), is(0)); verify(carrier).discoveryFailed(eq(Endpoint.of(new SwitchId(1), 1)), eq(0L), anyLong()); verify(carrier).discoveryFailed(eq(Endpoint.of(new SwitchId(2), 1)), eq(2L), anyLong()); verify(carrier, times(2)).discoveryFailed(any(Endpoint.class), anyLong(), anyLong()); assertThat(w.getTimeouts().size(), is(0)); }
|
public void tick() { tick(now()); }
|
NetworkWatcherService { public void tick() { tick(now()); } }
|
NetworkWatcherService { public void tick() { tick(now()); } NetworkWatcherService(
IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); @VisibleForTesting NetworkWatcherService(
Clock clock, IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime,
Integer taskId); }
|
NetworkWatcherService { public void tick() { tick(now()); } NetworkWatcherService(
IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); @VisibleForTesting NetworkWatcherService(
Clock clock, IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime,
Integer taskId); void addWatch(Endpoint endpoint); void removeWatch(Endpoint endpoint); void tick(); void confirmation(Endpoint endpoint, long packetNo); void discovery(IslInfoData discoveryEvent); void roundTripDiscovery(Endpoint endpoint, long packetId); }
|
NetworkWatcherService { public void tick() { tick(now()); } NetworkWatcherService(
IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); @VisibleForTesting NetworkWatcherService(
Clock clock, IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime,
Integer taskId); void addWatch(Endpoint endpoint); void removeWatch(Endpoint endpoint); void tick(); void confirmation(Endpoint endpoint, long packetNo); void discovery(IslInfoData discoveryEvent); void roundTripDiscovery(Endpoint endpoint, long packetId); }
|
@Test public void discovery() { NetworkWatcherService w = makeService(); w.addWatch(Endpoint.of(new SwitchId(1), 1), 1); w.addWatch(Endpoint.of(new SwitchId(1), 2), 1); w.addWatch(Endpoint.of(new SwitchId(2), 1), 2); w.addWatch(Endpoint.of(new SwitchId(2), 1), 2); w.addWatch(Endpoint.of(new SwitchId(2), 2), 3); assertThat(w.getConfirmedPackets().size(), is(0)); assertThat(w.getTimeouts().size(), is(3)); verify(carrier, times(5)).sendDiscovery(any(DiscoverIslCommandData.class)); w.confirmation(Endpoint.of(new SwitchId(1), 1), 0); w.confirmation(Endpoint.of(new SwitchId(2), 1), 2); assertThat(w.getConfirmedPackets().size(), is(2)); PathNode source = new PathNode(new SwitchId(1), 1, 0); PathNode destination = new PathNode(new SwitchId(2), 1, 0); IslInfoData islAlphaBeta = IslInfoData.builder().source(source).destination(destination).packetId(0L).build(); IslInfoData islBetaAlpha = IslInfoData.builder().source(destination).destination(source).packetId(2L).build(); w.discovery(islAlphaBeta); w.discovery(islBetaAlpha); w.tick(100); assertThat(w.getConfirmedPackets().size(), is(0)); verify(carrier).discoveryReceived(eq(new Endpoint(islAlphaBeta.getSource())), eq(0L), eq(islAlphaBeta), anyLong()); verify(carrier).discoveryReceived(eq(new Endpoint(islBetaAlpha.getSource())), eq(2L), eq(islBetaAlpha), anyLong()); verify(carrier, times(2)).discoveryReceived(any(Endpoint.class), anyLong(), any(IslInfoData.class), anyLong()); assertThat(w.getTimeouts().size(), is(0)); }
|
public void discovery(IslInfoData discoveryEvent) { Endpoint source = new Endpoint(discoveryEvent.getSource()); Long packetId = discoveryEvent.getPacketId(); if (packetId == null) { log.error("Got corrupted discovery packet into {} - packetId field is empty", source); } else { discovery(discoveryEvent, Packet.of(source, packetId)); } }
|
NetworkWatcherService { public void discovery(IslInfoData discoveryEvent) { Endpoint source = new Endpoint(discoveryEvent.getSource()); Long packetId = discoveryEvent.getPacketId(); if (packetId == null) { log.error("Got corrupted discovery packet into {} - packetId field is empty", source); } else { discovery(discoveryEvent, Packet.of(source, packetId)); } } }
|
NetworkWatcherService { public void discovery(IslInfoData discoveryEvent) { Endpoint source = new Endpoint(discoveryEvent.getSource()); Long packetId = discoveryEvent.getPacketId(); if (packetId == null) { log.error("Got corrupted discovery packet into {} - packetId field is empty", source); } else { discovery(discoveryEvent, Packet.of(source, packetId)); } } NetworkWatcherService(
IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); @VisibleForTesting NetworkWatcherService(
Clock clock, IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime,
Integer taskId); }
|
NetworkWatcherService { public void discovery(IslInfoData discoveryEvent) { Endpoint source = new Endpoint(discoveryEvent.getSource()); Long packetId = discoveryEvent.getPacketId(); if (packetId == null) { log.error("Got corrupted discovery packet into {} - packetId field is empty", source); } else { discovery(discoveryEvent, Packet.of(source, packetId)); } } NetworkWatcherService(
IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); @VisibleForTesting NetworkWatcherService(
Clock clock, IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime,
Integer taskId); void addWatch(Endpoint endpoint); void removeWatch(Endpoint endpoint); void tick(); void confirmation(Endpoint endpoint, long packetNo); void discovery(IslInfoData discoveryEvent); void roundTripDiscovery(Endpoint endpoint, long packetId); }
|
NetworkWatcherService { public void discovery(IslInfoData discoveryEvent) { Endpoint source = new Endpoint(discoveryEvent.getSource()); Long packetId = discoveryEvent.getPacketId(); if (packetId == null) { log.error("Got corrupted discovery packet into {} - packetId field is empty", source); } else { discovery(discoveryEvent, Packet.of(source, packetId)); } } NetworkWatcherService(
IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime, Integer taskId); @VisibleForTesting NetworkWatcherService(
Clock clock, IWatcherCarrier carrier, Duration roundTripNotificationPeriod, long awaitTime,
Integer taskId); void addWatch(Endpoint endpoint); void removeWatch(Endpoint endpoint); void tick(); void confirmation(Endpoint endpoint, long packetNo); void discovery(IslInfoData discoveryEvent); void roundTripDiscovery(Endpoint endpoint, long packetId); }
|
@Test public void discovered() { NetworkDecisionMakerService w = new NetworkDecisionMakerService(carrier, 10, 5); w.discovered(endpointBeta, 1L, islAlphaBeta, 1L); w.discovered(endpointAlpha, 2L, islBetaAlpha, 2L); verify(carrier).linkDiscovered(eq(islAlphaBeta)); verify(carrier).linkDiscovered(eq(islBetaAlpha)); }
|
public void discovered(Endpoint endpoint, long packetId, IslInfoData discoveryEvent) { discovered(endpoint, packetId, discoveryEvent, now()); }
|
NetworkDecisionMakerService { public void discovered(Endpoint endpoint, long packetId, IslInfoData discoveryEvent) { discovered(endpoint, packetId, discoveryEvent, now()); } }
|
NetworkDecisionMakerService { public void discovered(Endpoint endpoint, long packetId, IslInfoData discoveryEvent) { discovered(endpoint, packetId, discoveryEvent, now()); } NetworkDecisionMakerService(IDecisionMakerCarrier carrier, long failTimeout, long awaitTime); }
|
NetworkDecisionMakerService { public void discovered(Endpoint endpoint, long packetId, IslInfoData discoveryEvent) { discovered(endpoint, packetId, discoveryEvent, now()); } NetworkDecisionMakerService(IDecisionMakerCarrier carrier, long failTimeout, long awaitTime); void discovered(Endpoint endpoint, long packetId, IslInfoData discoveryEvent); void failed(Endpoint endpoint, long packetId); void tick(); void clear(Endpoint endpoint); }
|
NetworkDecisionMakerService { public void discovered(Endpoint endpoint, long packetId, IslInfoData discoveryEvent) { discovered(endpoint, packetId, discoveryEvent, now()); } NetworkDecisionMakerService(IDecisionMakerCarrier carrier, long failTimeout, long awaitTime); void discovered(Endpoint endpoint, long packetId, IslInfoData discoveryEvent); void failed(Endpoint endpoint, long packetId); void tick(); void clear(Endpoint endpoint); }
|
@Test public void shouldValidateFlowWithTransitVlanEncapsulationESwitch() throws FlowNotFoundException, SwitchNotFoundException { buildTransitVlanFlow("E"); List<SwitchFlowEntries> flowEntries = getSwitchFlowEntriesWithTransitVlan(); List<SwitchMeterEntries> meterEntries = getSwitchMeterEntriesWithESwitch(); List<FlowValidationResponse> result = service.validateFlow(TEST_FLOW_ID_A, flowEntries, meterEntries); assertEquals(4, result.size()); assertEquals(0, result.get(0).getDiscrepancies().size()); assertEquals(0, result.get(1).getDiscrepancies().size()); assertEquals(0, result.get(2).getDiscrepancies().size()); assertEquals(0, result.get(3).getDiscrepancies().size()); assertEquals(3, (int) result.get(0).getFlowRulesTotal()); assertEquals(3, (int) result.get(1).getFlowRulesTotal()); assertEquals(2, (int) result.get(2).getFlowRulesTotal()); assertEquals(2, (int) result.get(3).getFlowRulesTotal()); assertEquals(10, (int) result.get(0).getSwitchRulesTotal()); assertEquals(10, (int) result.get(1).getSwitchRulesTotal()); assertEquals(10, (int) result.get(2).getSwitchRulesTotal()); assertEquals(10, (int) result.get(3).getSwitchRulesTotal()); }
|
public List<FlowValidationResponse> validateFlow(String flowId, List<SwitchFlowEntries> switchFlowEntries, List<SwitchMeterEntries> switchMeterEntries) throws FlowNotFoundException, SwitchNotFoundException { Map<SwitchId, List<SimpleSwitchRule>> switchRules = new HashMap<>(); int rulesCount = 0; int metersCount = 0; for (SwitchFlowEntries switchRulesEntries : switchFlowEntries) { SwitchMeterEntries switchMeters = switchMeterEntries.stream() .filter(meterEntries -> switchRulesEntries.getSwitchId().equals(meterEntries.getSwitchId())) .findFirst() .orElse(null); List<SimpleSwitchRule> simpleSwitchRules = simpleSwitchRuleConverter .convertSwitchFlowEntriesToSimpleSwitchRules(switchRulesEntries, switchMeters); switchRules.put(switchRulesEntries.getSwitchId(), simpleSwitchRules); rulesCount += Optional.ofNullable(switchRulesEntries.getFlowEntries()) .map(List::size) .orElse(0); metersCount += Optional.ofNullable(switchMeters) .map(SwitchMeterEntries::getMeterEntries) .map(List::size) .orElse(0); } Optional<Flow> foundFlow = flowRepository.findById(flowId); if (!foundFlow.isPresent()) { throw new FlowNotFoundException(flowId); } Flow flow = foundFlow.get(); if (flow.getForwardPath() == null) { throw new InvalidPathException(flowId, "Forward path was not returned."); } if (flow.getReversePath() == null) { throw new InvalidPathException(flowId, "Reverse path was not returned."); } List<FlowValidationResponse> flowValidationResponse = new ArrayList<>(); List<SimpleSwitchRule> forwardRules = getSimpleSwitchRules(flow, flow.getForwardPath(), flow.getReversePath()); flowValidationResponse.add(compare(switchRules, forwardRules, flowId, rulesCount, metersCount)); List<SimpleSwitchRule> reverseRules = getSimpleSwitchRules(flow, flow.getReversePath(), flow.getForwardPath()); flowValidationResponse.add(compare(switchRules, reverseRules, flowId, rulesCount, metersCount)); if (flow.getProtectedForwardPath() != null) { List<SimpleSwitchRule> forwardProtectedRules = getSimpleSwitchRules(flow, flow.getProtectedForwardPath(), flow.getProtectedReversePath()); flowValidationResponse.add(compare(switchRules, forwardProtectedRules, flowId, rulesCount, metersCount)); } if (flow.getProtectedReversePath() != null) { List<SimpleSwitchRule> reverseProtectedRules = getSimpleSwitchRules(flow, flow.getProtectedReversePath(), flow.getProtectedForwardPath()); flowValidationResponse.add(compare(switchRules, reverseProtectedRules, flowId, rulesCount, metersCount)); } return flowValidationResponse; }
|
FlowValidationService { public List<FlowValidationResponse> validateFlow(String flowId, List<SwitchFlowEntries> switchFlowEntries, List<SwitchMeterEntries> switchMeterEntries) throws FlowNotFoundException, SwitchNotFoundException { Map<SwitchId, List<SimpleSwitchRule>> switchRules = new HashMap<>(); int rulesCount = 0; int metersCount = 0; for (SwitchFlowEntries switchRulesEntries : switchFlowEntries) { SwitchMeterEntries switchMeters = switchMeterEntries.stream() .filter(meterEntries -> switchRulesEntries.getSwitchId().equals(meterEntries.getSwitchId())) .findFirst() .orElse(null); List<SimpleSwitchRule> simpleSwitchRules = simpleSwitchRuleConverter .convertSwitchFlowEntriesToSimpleSwitchRules(switchRulesEntries, switchMeters); switchRules.put(switchRulesEntries.getSwitchId(), simpleSwitchRules); rulesCount += Optional.ofNullable(switchRulesEntries.getFlowEntries()) .map(List::size) .orElse(0); metersCount += Optional.ofNullable(switchMeters) .map(SwitchMeterEntries::getMeterEntries) .map(List::size) .orElse(0); } Optional<Flow> foundFlow = flowRepository.findById(flowId); if (!foundFlow.isPresent()) { throw new FlowNotFoundException(flowId); } Flow flow = foundFlow.get(); if (flow.getForwardPath() == null) { throw new InvalidPathException(flowId, "Forward path was not returned."); } if (flow.getReversePath() == null) { throw new InvalidPathException(flowId, "Reverse path was not returned."); } List<FlowValidationResponse> flowValidationResponse = new ArrayList<>(); List<SimpleSwitchRule> forwardRules = getSimpleSwitchRules(flow, flow.getForwardPath(), flow.getReversePath()); flowValidationResponse.add(compare(switchRules, forwardRules, flowId, rulesCount, metersCount)); List<SimpleSwitchRule> reverseRules = getSimpleSwitchRules(flow, flow.getReversePath(), flow.getForwardPath()); flowValidationResponse.add(compare(switchRules, reverseRules, flowId, rulesCount, metersCount)); if (flow.getProtectedForwardPath() != null) { List<SimpleSwitchRule> forwardProtectedRules = getSimpleSwitchRules(flow, flow.getProtectedForwardPath(), flow.getProtectedReversePath()); flowValidationResponse.add(compare(switchRules, forwardProtectedRules, flowId, rulesCount, metersCount)); } if (flow.getProtectedReversePath() != null) { List<SimpleSwitchRule> reverseProtectedRules = getSimpleSwitchRules(flow, flow.getProtectedReversePath(), flow.getProtectedForwardPath()); flowValidationResponse.add(compare(switchRules, reverseProtectedRules, flowId, rulesCount, metersCount)); } return flowValidationResponse; } }
|
FlowValidationService { public List<FlowValidationResponse> validateFlow(String flowId, List<SwitchFlowEntries> switchFlowEntries, List<SwitchMeterEntries> switchMeterEntries) throws FlowNotFoundException, SwitchNotFoundException { Map<SwitchId, List<SimpleSwitchRule>> switchRules = new HashMap<>(); int rulesCount = 0; int metersCount = 0; for (SwitchFlowEntries switchRulesEntries : switchFlowEntries) { SwitchMeterEntries switchMeters = switchMeterEntries.stream() .filter(meterEntries -> switchRulesEntries.getSwitchId().equals(meterEntries.getSwitchId())) .findFirst() .orElse(null); List<SimpleSwitchRule> simpleSwitchRules = simpleSwitchRuleConverter .convertSwitchFlowEntriesToSimpleSwitchRules(switchRulesEntries, switchMeters); switchRules.put(switchRulesEntries.getSwitchId(), simpleSwitchRules); rulesCount += Optional.ofNullable(switchRulesEntries.getFlowEntries()) .map(List::size) .orElse(0); metersCount += Optional.ofNullable(switchMeters) .map(SwitchMeterEntries::getMeterEntries) .map(List::size) .orElse(0); } Optional<Flow> foundFlow = flowRepository.findById(flowId); if (!foundFlow.isPresent()) { throw new FlowNotFoundException(flowId); } Flow flow = foundFlow.get(); if (flow.getForwardPath() == null) { throw new InvalidPathException(flowId, "Forward path was not returned."); } if (flow.getReversePath() == null) { throw new InvalidPathException(flowId, "Reverse path was not returned."); } List<FlowValidationResponse> flowValidationResponse = new ArrayList<>(); List<SimpleSwitchRule> forwardRules = getSimpleSwitchRules(flow, flow.getForwardPath(), flow.getReversePath()); flowValidationResponse.add(compare(switchRules, forwardRules, flowId, rulesCount, metersCount)); List<SimpleSwitchRule> reverseRules = getSimpleSwitchRules(flow, flow.getReversePath(), flow.getForwardPath()); flowValidationResponse.add(compare(switchRules, reverseRules, flowId, rulesCount, metersCount)); if (flow.getProtectedForwardPath() != null) { List<SimpleSwitchRule> forwardProtectedRules = getSimpleSwitchRules(flow, flow.getProtectedForwardPath(), flow.getProtectedReversePath()); flowValidationResponse.add(compare(switchRules, forwardProtectedRules, flowId, rulesCount, metersCount)); } if (flow.getProtectedReversePath() != null) { List<SimpleSwitchRule> reverseProtectedRules = getSimpleSwitchRules(flow, flow.getProtectedReversePath(), flow.getProtectedForwardPath()); flowValidationResponse.add(compare(switchRules, reverseProtectedRules, flowId, rulesCount, metersCount)); } return flowValidationResponse; } FlowValidationService(PersistenceManager persistenceManager, FlowResourcesConfig flowResourcesConfig,
long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient); }
|
FlowValidationService { public List<FlowValidationResponse> validateFlow(String flowId, List<SwitchFlowEntries> switchFlowEntries, List<SwitchMeterEntries> switchMeterEntries) throws FlowNotFoundException, SwitchNotFoundException { Map<SwitchId, List<SimpleSwitchRule>> switchRules = new HashMap<>(); int rulesCount = 0; int metersCount = 0; for (SwitchFlowEntries switchRulesEntries : switchFlowEntries) { SwitchMeterEntries switchMeters = switchMeterEntries.stream() .filter(meterEntries -> switchRulesEntries.getSwitchId().equals(meterEntries.getSwitchId())) .findFirst() .orElse(null); List<SimpleSwitchRule> simpleSwitchRules = simpleSwitchRuleConverter .convertSwitchFlowEntriesToSimpleSwitchRules(switchRulesEntries, switchMeters); switchRules.put(switchRulesEntries.getSwitchId(), simpleSwitchRules); rulesCount += Optional.ofNullable(switchRulesEntries.getFlowEntries()) .map(List::size) .orElse(0); metersCount += Optional.ofNullable(switchMeters) .map(SwitchMeterEntries::getMeterEntries) .map(List::size) .orElse(0); } Optional<Flow> foundFlow = flowRepository.findById(flowId); if (!foundFlow.isPresent()) { throw new FlowNotFoundException(flowId); } Flow flow = foundFlow.get(); if (flow.getForwardPath() == null) { throw new InvalidPathException(flowId, "Forward path was not returned."); } if (flow.getReversePath() == null) { throw new InvalidPathException(flowId, "Reverse path was not returned."); } List<FlowValidationResponse> flowValidationResponse = new ArrayList<>(); List<SimpleSwitchRule> forwardRules = getSimpleSwitchRules(flow, flow.getForwardPath(), flow.getReversePath()); flowValidationResponse.add(compare(switchRules, forwardRules, flowId, rulesCount, metersCount)); List<SimpleSwitchRule> reverseRules = getSimpleSwitchRules(flow, flow.getReversePath(), flow.getForwardPath()); flowValidationResponse.add(compare(switchRules, reverseRules, flowId, rulesCount, metersCount)); if (flow.getProtectedForwardPath() != null) { List<SimpleSwitchRule> forwardProtectedRules = getSimpleSwitchRules(flow, flow.getProtectedForwardPath(), flow.getProtectedReversePath()); flowValidationResponse.add(compare(switchRules, forwardProtectedRules, flowId, rulesCount, metersCount)); } if (flow.getProtectedReversePath() != null) { List<SimpleSwitchRule> reverseProtectedRules = getSimpleSwitchRules(flow, flow.getProtectedReversePath(), flow.getProtectedForwardPath()); flowValidationResponse.add(compare(switchRules, reverseProtectedRules, flowId, rulesCount, metersCount)); } return flowValidationResponse; } FlowValidationService(PersistenceManager persistenceManager, FlowResourcesConfig flowResourcesConfig,
long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient); void checkFlowStatus(String flowId); List<SwitchId> getSwitchIdListByFlowId(String flowId); List<FlowValidationResponse> validateFlow(String flowId, List<SwitchFlowEntries> switchFlowEntries,
List<SwitchMeterEntries> switchMeterEntries); }
|
FlowValidationService { public List<FlowValidationResponse> validateFlow(String flowId, List<SwitchFlowEntries> switchFlowEntries, List<SwitchMeterEntries> switchMeterEntries) throws FlowNotFoundException, SwitchNotFoundException { Map<SwitchId, List<SimpleSwitchRule>> switchRules = new HashMap<>(); int rulesCount = 0; int metersCount = 0; for (SwitchFlowEntries switchRulesEntries : switchFlowEntries) { SwitchMeterEntries switchMeters = switchMeterEntries.stream() .filter(meterEntries -> switchRulesEntries.getSwitchId().equals(meterEntries.getSwitchId())) .findFirst() .orElse(null); List<SimpleSwitchRule> simpleSwitchRules = simpleSwitchRuleConverter .convertSwitchFlowEntriesToSimpleSwitchRules(switchRulesEntries, switchMeters); switchRules.put(switchRulesEntries.getSwitchId(), simpleSwitchRules); rulesCount += Optional.ofNullable(switchRulesEntries.getFlowEntries()) .map(List::size) .orElse(0); metersCount += Optional.ofNullable(switchMeters) .map(SwitchMeterEntries::getMeterEntries) .map(List::size) .orElse(0); } Optional<Flow> foundFlow = flowRepository.findById(flowId); if (!foundFlow.isPresent()) { throw new FlowNotFoundException(flowId); } Flow flow = foundFlow.get(); if (flow.getForwardPath() == null) { throw new InvalidPathException(flowId, "Forward path was not returned."); } if (flow.getReversePath() == null) { throw new InvalidPathException(flowId, "Reverse path was not returned."); } List<FlowValidationResponse> flowValidationResponse = new ArrayList<>(); List<SimpleSwitchRule> forwardRules = getSimpleSwitchRules(flow, flow.getForwardPath(), flow.getReversePath()); flowValidationResponse.add(compare(switchRules, forwardRules, flowId, rulesCount, metersCount)); List<SimpleSwitchRule> reverseRules = getSimpleSwitchRules(flow, flow.getReversePath(), flow.getForwardPath()); flowValidationResponse.add(compare(switchRules, reverseRules, flowId, rulesCount, metersCount)); if (flow.getProtectedForwardPath() != null) { List<SimpleSwitchRule> forwardProtectedRules = getSimpleSwitchRules(flow, flow.getProtectedForwardPath(), flow.getProtectedReversePath()); flowValidationResponse.add(compare(switchRules, forwardProtectedRules, flowId, rulesCount, metersCount)); } if (flow.getProtectedReversePath() != null) { List<SimpleSwitchRule> reverseProtectedRules = getSimpleSwitchRules(flow, flow.getProtectedReversePath(), flow.getProtectedForwardPath()); flowValidationResponse.add(compare(switchRules, reverseProtectedRules, flowId, rulesCount, metersCount)); } return flowValidationResponse; } FlowValidationService(PersistenceManager persistenceManager, FlowResourcesConfig flowResourcesConfig,
long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient); void checkFlowStatus(String flowId); List<SwitchId> getSwitchIdListByFlowId(String flowId); List<FlowValidationResponse> validateFlow(String flowId, List<SwitchFlowEntries> switchFlowEntries,
List<SwitchMeterEntries> switchMeterEntries); }
|
@Test public void failed() { NetworkDecisionMakerService w = new NetworkDecisionMakerService(carrier, 10, 5); w.failed(endpointAlpha, 0L, 0); w.failed(endpointAlpha, 1L, 1); w.failed(endpointAlpha, 2L, 4); verify(carrier, never()).linkDestroyed(any(Endpoint.class)); w.failed(endpointAlpha, 3L, 5); verify(carrier).linkDestroyed(eq(endpointAlpha)); w.discovered(endpointAlpha, 4L, islBetaAlpha, 20); verify(carrier).linkDiscovered(islBetaAlpha); reset(carrier); w.failed(endpointAlpha, 5L, 21); w.failed(endpointAlpha, 6L, 23); w.failed(endpointAlpha, 7L, 24); verify(carrier, never()).linkDestroyed(any(Endpoint.class)); w.failed(endpointAlpha, 8L, 31); verify(carrier).linkDestroyed(eq(endpointAlpha)); }
|
public void failed(Endpoint endpoint, long packetId) { failed(endpoint, packetId, now()); }
|
NetworkDecisionMakerService { public void failed(Endpoint endpoint, long packetId) { failed(endpoint, packetId, now()); } }
|
NetworkDecisionMakerService { public void failed(Endpoint endpoint, long packetId) { failed(endpoint, packetId, now()); } NetworkDecisionMakerService(IDecisionMakerCarrier carrier, long failTimeout, long awaitTime); }
|
NetworkDecisionMakerService { public void failed(Endpoint endpoint, long packetId) { failed(endpoint, packetId, now()); } NetworkDecisionMakerService(IDecisionMakerCarrier carrier, long failTimeout, long awaitTime); void discovered(Endpoint endpoint, long packetId, IslInfoData discoveryEvent); void failed(Endpoint endpoint, long packetId); void tick(); void clear(Endpoint endpoint); }
|
NetworkDecisionMakerService { public void failed(Endpoint endpoint, long packetId) { failed(endpoint, packetId, now()); } NetworkDecisionMakerService(IDecisionMakerCarrier carrier, long failTimeout, long awaitTime); void discovered(Endpoint endpoint, long packetId, IslInfoData discoveryEvent); void failed(Endpoint endpoint, long packetId); void tick(); void clear(Endpoint endpoint); }
|
@Test public void colonSeparatedBytesIllegalArgumentExceptionNegativeOffset() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", -1)); new SwitchId("00").colonSeparatedBytes(new char[]{'t', 'e', 's', 't'}, -1); }
|
@VisibleForTesting String colonSeparatedBytes(char[] hex, int offset) { if (offset < 0 || offset % 2 != 0 || offset >= hex.length) { throw new IllegalArgumentException(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", offset)); } int length = hex.length - offset; length += length / 2 - 1; char[] buffer = new char[length]; int dst = 0; for (int src = offset; src < hex.length; src++) { if (offset < src && src % 2 == 0) { buffer[dst++] = ':'; } buffer[dst++] = hex[src]; } return new String(buffer); }
|
SwitchId implements Comparable<SwitchId>, Serializable { @VisibleForTesting String colonSeparatedBytes(char[] hex, int offset) { if (offset < 0 || offset % 2 != 0 || offset >= hex.length) { throw new IllegalArgumentException(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", offset)); } int length = hex.length - offset; length += length / 2 - 1; char[] buffer = new char[length]; int dst = 0; for (int src = offset; src < hex.length; src++) { if (offset < src && src % 2 == 0) { buffer[dst++] = ':'; } buffer[dst++] = hex[src]; } return new String(buffer); } }
|
SwitchId implements Comparable<SwitchId>, Serializable { @VisibleForTesting String colonSeparatedBytes(char[] hex, int offset) { if (offset < 0 || offset % 2 != 0 || offset >= hex.length) { throw new IllegalArgumentException(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", offset)); } int length = hex.length - offset; length += length / 2 - 1; char[] buffer = new char[length]; int dst = 0; for (int src = offset; src < hex.length; src++) { if (offset < src && src % 2 == 0) { buffer[dst++] = ':'; } buffer[dst++] = hex[src]; } return new String(buffer); } SwitchId(long switchId); SwitchId(String switchId); }
|
SwitchId implements Comparable<SwitchId>, Serializable { @VisibleForTesting String colonSeparatedBytes(char[] hex, int offset) { if (offset < 0 || offset % 2 != 0 || offset >= hex.length) { throw new IllegalArgumentException(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", offset)); } int length = hex.length - offset; length += length / 2 - 1; char[] buffer = new char[length]; int dst = 0; for (int src = offset; src < hex.length; src++) { if (offset < src && src % 2 == 0) { buffer[dst++] = ':'; } buffer[dst++] = hex[src]; } return new String(buffer); } SwitchId(long switchId); SwitchId(String switchId); long toLong(); String toMacAddress(); @JsonValue @Override String toString(); String toOtsdFormat(); @Override int compareTo(SwitchId other); }
|
SwitchId implements Comparable<SwitchId>, Serializable { @VisibleForTesting String colonSeparatedBytes(char[] hex, int offset) { if (offset < 0 || offset % 2 != 0 || offset >= hex.length) { throw new IllegalArgumentException(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", offset)); } int length = hex.length - offset; length += length / 2 - 1; char[] buffer = new char[length]; int dst = 0; for (int src = offset; src < hex.length; src++) { if (offset < src && src % 2 == 0) { buffer[dst++] = ':'; } buffer[dst++] = hex[src]; } return new String(buffer); } SwitchId(long switchId); SwitchId(String switchId); long toLong(); String toMacAddress(); @JsonValue @Override String toString(); String toOtsdFormat(); @Override int compareTo(SwitchId other); }
|
@Test public void colonSeparatedBytesIllegalArgumentExceptionOddOffset() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", 3)); new SwitchId("00").colonSeparatedBytes(new char[]{'t', 'e', 's', 't'}, 3); }
|
@VisibleForTesting String colonSeparatedBytes(char[] hex, int offset) { if (offset < 0 || offset % 2 != 0 || offset >= hex.length) { throw new IllegalArgumentException(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", offset)); } int length = hex.length - offset; length += length / 2 - 1; char[] buffer = new char[length]; int dst = 0; for (int src = offset; src < hex.length; src++) { if (offset < src && src % 2 == 0) { buffer[dst++] = ':'; } buffer[dst++] = hex[src]; } return new String(buffer); }
|
SwitchId implements Comparable<SwitchId>, Serializable { @VisibleForTesting String colonSeparatedBytes(char[] hex, int offset) { if (offset < 0 || offset % 2 != 0 || offset >= hex.length) { throw new IllegalArgumentException(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", offset)); } int length = hex.length - offset; length += length / 2 - 1; char[] buffer = new char[length]; int dst = 0; for (int src = offset; src < hex.length; src++) { if (offset < src && src % 2 == 0) { buffer[dst++] = ':'; } buffer[dst++] = hex[src]; } return new String(buffer); } }
|
SwitchId implements Comparable<SwitchId>, Serializable { @VisibleForTesting String colonSeparatedBytes(char[] hex, int offset) { if (offset < 0 || offset % 2 != 0 || offset >= hex.length) { throw new IllegalArgumentException(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", offset)); } int length = hex.length - offset; length += length / 2 - 1; char[] buffer = new char[length]; int dst = 0; for (int src = offset; src < hex.length; src++) { if (offset < src && src % 2 == 0) { buffer[dst++] = ':'; } buffer[dst++] = hex[src]; } return new String(buffer); } SwitchId(long switchId); SwitchId(String switchId); }
|
SwitchId implements Comparable<SwitchId>, Serializable { @VisibleForTesting String colonSeparatedBytes(char[] hex, int offset) { if (offset < 0 || offset % 2 != 0 || offset >= hex.length) { throw new IllegalArgumentException(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", offset)); } int length = hex.length - offset; length += length / 2 - 1; char[] buffer = new char[length]; int dst = 0; for (int src = offset; src < hex.length; src++) { if (offset < src && src % 2 == 0) { buffer[dst++] = ':'; } buffer[dst++] = hex[src]; } return new String(buffer); } SwitchId(long switchId); SwitchId(String switchId); long toLong(); String toMacAddress(); @JsonValue @Override String toString(); String toOtsdFormat(); @Override int compareTo(SwitchId other); }
|
SwitchId implements Comparable<SwitchId>, Serializable { @VisibleForTesting String colonSeparatedBytes(char[] hex, int offset) { if (offset < 0 || offset % 2 != 0 || offset >= hex.length) { throw new IllegalArgumentException(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", offset)); } int length = hex.length - offset; length += length / 2 - 1; char[] buffer = new char[length]; int dst = 0; for (int src = offset; src < hex.length; src++) { if (offset < src && src % 2 == 0) { buffer[dst++] = ':'; } buffer[dst++] = hex[src]; } return new String(buffer); } SwitchId(long switchId); SwitchId(String switchId); long toLong(); String toMacAddress(); @JsonValue @Override String toString(); String toOtsdFormat(); @Override int compareTo(SwitchId other); }
|
@Test public void colonSeparatedBytesIllegalArgumentExceptionMoreThenHexLength() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", 6)); new SwitchId("00").colonSeparatedBytes(new char[]{'t', 'e', 's', 't'}, 6); }
|
@VisibleForTesting String colonSeparatedBytes(char[] hex, int offset) { if (offset < 0 || offset % 2 != 0 || offset >= hex.length) { throw new IllegalArgumentException(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", offset)); } int length = hex.length - offset; length += length / 2 - 1; char[] buffer = new char[length]; int dst = 0; for (int src = offset; src < hex.length; src++) { if (offset < src && src % 2 == 0) { buffer[dst++] = ':'; } buffer[dst++] = hex[src]; } return new String(buffer); }
|
SwitchId implements Comparable<SwitchId>, Serializable { @VisibleForTesting String colonSeparatedBytes(char[] hex, int offset) { if (offset < 0 || offset % 2 != 0 || offset >= hex.length) { throw new IllegalArgumentException(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", offset)); } int length = hex.length - offset; length += length / 2 - 1; char[] buffer = new char[length]; int dst = 0; for (int src = offset; src < hex.length; src++) { if (offset < src && src % 2 == 0) { buffer[dst++] = ':'; } buffer[dst++] = hex[src]; } return new String(buffer); } }
|
SwitchId implements Comparable<SwitchId>, Serializable { @VisibleForTesting String colonSeparatedBytes(char[] hex, int offset) { if (offset < 0 || offset % 2 != 0 || offset >= hex.length) { throw new IllegalArgumentException(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", offset)); } int length = hex.length - offset; length += length / 2 - 1; char[] buffer = new char[length]; int dst = 0; for (int src = offset; src < hex.length; src++) { if (offset < src && src % 2 == 0) { buffer[dst++] = ':'; } buffer[dst++] = hex[src]; } return new String(buffer); } SwitchId(long switchId); SwitchId(String switchId); }
|
SwitchId implements Comparable<SwitchId>, Serializable { @VisibleForTesting String colonSeparatedBytes(char[] hex, int offset) { if (offset < 0 || offset % 2 != 0 || offset >= hex.length) { throw new IllegalArgumentException(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", offset)); } int length = hex.length - offset; length += length / 2 - 1; char[] buffer = new char[length]; int dst = 0; for (int src = offset; src < hex.length; src++) { if (offset < src && src % 2 == 0) { buffer[dst++] = ':'; } buffer[dst++] = hex[src]; } return new String(buffer); } SwitchId(long switchId); SwitchId(String switchId); long toLong(); String toMacAddress(); @JsonValue @Override String toString(); String toOtsdFormat(); @Override int compareTo(SwitchId other); }
|
SwitchId implements Comparable<SwitchId>, Serializable { @VisibleForTesting String colonSeparatedBytes(char[] hex, int offset) { if (offset < 0 || offset % 2 != 0 || offset >= hex.length) { throw new IllegalArgumentException(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", offset)); } int length = hex.length - offset; length += length / 2 - 1; char[] buffer = new char[length]; int dst = 0; for (int src = offset; src < hex.length; src++) { if (offset < src && src % 2 == 0) { buffer[dst++] = ':'; } buffer[dst++] = hex[src]; } return new String(buffer); } SwitchId(long switchId); SwitchId(String switchId); long toLong(); String toMacAddress(); @JsonValue @Override String toString(); String toOtsdFormat(); @Override int compareTo(SwitchId other); }
|
@Test public void shouldComputeIsUnstable() { Isl isl = Isl.builder() .srcSwitch(Switch.builder().switchId(new SwitchId(1)).build()) .destSwitch(Switch.builder().switchId(new SwitchId(2)).build()) .build(); isl.setIslConfig(islConfig); isl.setTimeUnstable(Instant.now().minus(islConfig.getUnstableIslTimeout())); assertFalse(isl.isUnstable()); isl.setTimeUnstable(Instant.now()); assertTrue(isl.isUnstable()); }
|
public boolean isUnstable() { if (islConfig == null) { throw new IllegalStateException("IslConfig has not initialized."); } return getTimeUnstable() != null && getTimeUnstable().plus(islConfig.getUnstableIslTimeout()).isAfter(Instant.now()); }
|
Isl implements CompositeDataEntity<Isl.IslData> { public boolean isUnstable() { if (islConfig == null) { throw new IllegalStateException("IslConfig has not initialized."); } return getTimeUnstable() != null && getTimeUnstable().plus(islConfig.getUnstableIslTimeout()).isAfter(Instant.now()); } }
|
Isl implements CompositeDataEntity<Isl.IslData> { public boolean isUnstable() { if (islConfig == null) { throw new IllegalStateException("IslConfig has not initialized."); } return getTimeUnstable() != null && getTimeUnstable().plus(islConfig.getUnstableIslTimeout()).isAfter(Instant.now()); } private Isl(); Isl(@NonNull Isl entityToClone); @Builder Isl(@NonNull Switch srcSwitch, @NonNull Switch destSwitch, int srcPort, int destPort,
long latency, long speed, int cost, long maxBandwidth, long defaultMaxBandwidth,
long availableBandwidth, IslStatus status, IslStatus actualStatus, IslStatus roundTripStatus,
IslDownReason downReason,
boolean underMaintenance, boolean enableBfd, BfdSessionStatus bfdSessionStatus, Instant timeUnstable); Isl(@NonNull IslData data); }
|
Isl implements CompositeDataEntity<Isl.IslData> { public boolean isUnstable() { if (islConfig == null) { throw new IllegalStateException("IslConfig has not initialized."); } return getTimeUnstable() != null && getTimeUnstable().plus(islConfig.getUnstableIslTimeout()).isAfter(Instant.now()); } private Isl(); Isl(@NonNull Isl entityToClone); @Builder Isl(@NonNull Switch srcSwitch, @NonNull Switch destSwitch, int srcPort, int destPort,
long latency, long speed, int cost, long maxBandwidth, long defaultMaxBandwidth,
long availableBandwidth, IslStatus status, IslStatus actualStatus, IslStatus roundTripStatus,
IslDownReason downReason,
boolean underMaintenance, boolean enableBfd, BfdSessionStatus bfdSessionStatus, Instant timeUnstable); Isl(@NonNull IslData data); boolean isUnstable(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
|
Isl implements CompositeDataEntity<Isl.IslData> { public boolean isUnstable() { if (islConfig == null) { throw new IllegalStateException("IslConfig has not initialized."); } return getTimeUnstable() != null && getTimeUnstable().plus(islConfig.getUnstableIslTimeout()).isAfter(Instant.now()); } private Isl(); Isl(@NonNull Isl entityToClone); @Builder Isl(@NonNull Switch srcSwitch, @NonNull Switch destSwitch, int srcPort, int destPort,
long latency, long speed, int cost, long maxBandwidth, long defaultMaxBandwidth,
long availableBandwidth, IslStatus status, IslStatus actualStatus, IslStatus roundTripStatus,
IslDownReason downReason,
boolean underMaintenance, boolean enableBfd, BfdSessionStatus bfdSessionStatus, Instant timeUnstable); Isl(@NonNull IslData data); boolean isUnstable(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
|
@Test public void calculateBurstSize() { assertEquals(1024, Meter.calculateBurstSize(512L, 1024L, 1.0, "centec")); assertEquals(32000, Meter.calculateBurstSize(32333L, 1024L, 1.0, "centec")); assertEquals(10030, Meter.calculateBurstSize(10000L, 1024L, 1.003, "centec")); assertEquals(1105500, Meter.calculateBurstSize(1100000L, 1024L, 1.005, "NW000.0.0")); assertEquals(1105500, Meter.calculateBurstSize(1100000L, 1024L, 1.05, "NW000.0.0")); }
|
public static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient, String switchDescription) { return calculateBurstSize(bandwidth, flowMeterMinBurstSizeInKbits, flowMeterBurstCoefficient, switchDescription, switchDescription); }
|
Meter implements Serializable { public static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient, String switchDescription) { return calculateBurstSize(bandwidth, flowMeterMinBurstSizeInKbits, flowMeterBurstCoefficient, switchDescription, switchDescription); } }
|
Meter implements Serializable { public static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient, String switchDescription) { return calculateBurstSize(bandwidth, flowMeterMinBurstSizeInKbits, flowMeterBurstCoefficient, switchDescription, switchDescription); } }
|
Meter implements Serializable { public static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient, String switchDescription) { return calculateBurstSize(bandwidth, flowMeterMinBurstSizeInKbits, flowMeterBurstCoefficient, switchDescription, switchDescription); } static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchDescription); static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchManufacturerDescription,
String switchSoftwareDescription); static long calculateBurstSizeConsideringHardwareLimitations(
long bandwidth, long requestedBurstSize, Set<SwitchFeature> features); static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes); static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes); static String[] getMeterKbpsFlags(); static String[] getMeterPktpsFlags(); static boolean equalsRate(long actual, long expected, boolean isESwitch); static boolean equalsBurstSize(long actual, long expected, boolean isESwitch); }
|
Meter implements Serializable { public static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient, String switchDescription) { return calculateBurstSize(bandwidth, flowMeterMinBurstSizeInKbits, flowMeterBurstCoefficient, switchDescription, switchDescription); } static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchDescription); static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchManufacturerDescription,
String switchSoftwareDescription); static long calculateBurstSizeConsideringHardwareLimitations(
long bandwidth, long requestedBurstSize, Set<SwitchFeature> features); static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes); static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes); static String[] getMeterKbpsFlags(); static String[] getMeterPktpsFlags(); static boolean equalsRate(long actual, long expected, boolean isESwitch); static boolean equalsBurstSize(long actual, long expected, boolean isESwitch); static final int MIN_RATE_IN_KBPS; }
|
@Test public void convertRateToKiloBitsTest() { assertEquals(800, Meter.convertRateToKiloBits(100, 1024)); assertEquals(64, Meter.convertRateToKiloBits(1, 1)); assertEquals(64, Meter.convertRateToKiloBits(8, 16)); }
|
public static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes) { return Math.max(MIN_RATE_IN_KBPS, (rateInPackets * packetSizeInBytes * 8) / 1024L); }
|
Meter implements Serializable { public static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes) { return Math.max(MIN_RATE_IN_KBPS, (rateInPackets * packetSizeInBytes * 8) / 1024L); } }
|
Meter implements Serializable { public static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes) { return Math.max(MIN_RATE_IN_KBPS, (rateInPackets * packetSizeInBytes * 8) / 1024L); } }
|
Meter implements Serializable { public static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes) { return Math.max(MIN_RATE_IN_KBPS, (rateInPackets * packetSizeInBytes * 8) / 1024L); } static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchDescription); static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchManufacturerDescription,
String switchSoftwareDescription); static long calculateBurstSizeConsideringHardwareLimitations(
long bandwidth, long requestedBurstSize, Set<SwitchFeature> features); static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes); static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes); static String[] getMeterKbpsFlags(); static String[] getMeterPktpsFlags(); static boolean equalsRate(long actual, long expected, boolean isESwitch); static boolean equalsBurstSize(long actual, long expected, boolean isESwitch); }
|
Meter implements Serializable { public static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes) { return Math.max(MIN_RATE_IN_KBPS, (rateInPackets * packetSizeInBytes * 8) / 1024L); } static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchDescription); static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchManufacturerDescription,
String switchSoftwareDescription); static long calculateBurstSizeConsideringHardwareLimitations(
long bandwidth, long requestedBurstSize, Set<SwitchFeature> features); static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes); static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes); static String[] getMeterKbpsFlags(); static String[] getMeterPktpsFlags(); static boolean equalsRate(long actual, long expected, boolean isESwitch); static boolean equalsBurstSize(long actual, long expected, boolean isESwitch); static final int MIN_RATE_IN_KBPS; }
|
@Test public void convertBurstSizeToKiloBitsTest() { assertEquals(800, Meter.convertBurstSizeToKiloBits(100, 1024)); assertEquals(1, Meter.convertBurstSizeToKiloBits(8, 16)); }
|
public static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes) { return (burstSizeInPackets * packetSizeInBytes * 8) / 1024L; }
|
Meter implements Serializable { public static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes) { return (burstSizeInPackets * packetSizeInBytes * 8) / 1024L; } }
|
Meter implements Serializable { public static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes) { return (burstSizeInPackets * packetSizeInBytes * 8) / 1024L; } }
|
Meter implements Serializable { public static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes) { return (burstSizeInPackets * packetSizeInBytes * 8) / 1024L; } static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchDescription); static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchManufacturerDescription,
String switchSoftwareDescription); static long calculateBurstSizeConsideringHardwareLimitations(
long bandwidth, long requestedBurstSize, Set<SwitchFeature> features); static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes); static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes); static String[] getMeterKbpsFlags(); static String[] getMeterPktpsFlags(); static boolean equalsRate(long actual, long expected, boolean isESwitch); static boolean equalsBurstSize(long actual, long expected, boolean isESwitch); }
|
Meter implements Serializable { public static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes) { return (burstSizeInPackets * packetSizeInBytes * 8) / 1024L; } static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchDescription); static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchManufacturerDescription,
String switchSoftwareDescription); static long calculateBurstSizeConsideringHardwareLimitations(
long bandwidth, long requestedBurstSize, Set<SwitchFeature> features); static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes); static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes); static String[] getMeterKbpsFlags(); static String[] getMeterPktpsFlags(); static boolean equalsRate(long actual, long expected, boolean isESwitch); static boolean equalsBurstSize(long actual, long expected, boolean isESwitch); static final int MIN_RATE_IN_KBPS; }
|
@Test public void convertCalculateBurstSizeConsideringHardwareLimitations() { Set<SwitchFeature> limitationFeature = newHashSet(MAX_BURST_COEFFICIENT_LIMITATION); assertEquals(4096, Meter.calculateBurstSizeConsideringHardwareLimitations(1, 4096, newHashSet())); assertEquals(1, Meter.calculateBurstSizeConsideringHardwareLimitations(1, 4096, limitationFeature)); assertEquals(100, Meter.calculateBurstSizeConsideringHardwareLimitations(100, 100, limitationFeature)); assertEquals(10, Meter.calculateBurstSizeConsideringHardwareLimitations(100, 10, limitationFeature)); }
|
public static long calculateBurstSizeConsideringHardwareLimitations( long bandwidth, long requestedBurstSize, Set<SwitchFeature> features) { if (features.contains(SwitchFeature.MAX_BURST_COEFFICIENT_LIMITATION)) { return Math.min(requestedBurstSize, Math.round(bandwidth * MAX_NOVIFLOW_BURST_COEFFICIENT)); } return requestedBurstSize; }
|
Meter implements Serializable { public static long calculateBurstSizeConsideringHardwareLimitations( long bandwidth, long requestedBurstSize, Set<SwitchFeature> features) { if (features.contains(SwitchFeature.MAX_BURST_COEFFICIENT_LIMITATION)) { return Math.min(requestedBurstSize, Math.round(bandwidth * MAX_NOVIFLOW_BURST_COEFFICIENT)); } return requestedBurstSize; } }
|
Meter implements Serializable { public static long calculateBurstSizeConsideringHardwareLimitations( long bandwidth, long requestedBurstSize, Set<SwitchFeature> features) { if (features.contains(SwitchFeature.MAX_BURST_COEFFICIENT_LIMITATION)) { return Math.min(requestedBurstSize, Math.round(bandwidth * MAX_NOVIFLOW_BURST_COEFFICIENT)); } return requestedBurstSize; } }
|
Meter implements Serializable { public static long calculateBurstSizeConsideringHardwareLimitations( long bandwidth, long requestedBurstSize, Set<SwitchFeature> features) { if (features.contains(SwitchFeature.MAX_BURST_COEFFICIENT_LIMITATION)) { return Math.min(requestedBurstSize, Math.round(bandwidth * MAX_NOVIFLOW_BURST_COEFFICIENT)); } return requestedBurstSize; } static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchDescription); static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchManufacturerDescription,
String switchSoftwareDescription); static long calculateBurstSizeConsideringHardwareLimitations(
long bandwidth, long requestedBurstSize, Set<SwitchFeature> features); static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes); static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes); static String[] getMeterKbpsFlags(); static String[] getMeterPktpsFlags(); static boolean equalsRate(long actual, long expected, boolean isESwitch); static boolean equalsBurstSize(long actual, long expected, boolean isESwitch); }
|
Meter implements Serializable { public static long calculateBurstSizeConsideringHardwareLimitations( long bandwidth, long requestedBurstSize, Set<SwitchFeature> features) { if (features.contains(SwitchFeature.MAX_BURST_COEFFICIENT_LIMITATION)) { return Math.min(requestedBurstSize, Math.round(bandwidth * MAX_NOVIFLOW_BURST_COEFFICIENT)); } return requestedBurstSize; } static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchDescription); static long calculateBurstSize(long bandwidth, long flowMeterMinBurstSizeInKbits,
double flowMeterBurstCoefficient, String switchManufacturerDescription,
String switchSoftwareDescription); static long calculateBurstSizeConsideringHardwareLimitations(
long bandwidth, long requestedBurstSize, Set<SwitchFeature> features); static long convertRateToKiloBits(long rateInPackets, long packetSizeInBytes); static long convertBurstSizeToKiloBits(long burstSizeInPackets, long packetSizeInBytes); static String[] getMeterKbpsFlags(); static String[] getMeterPktpsFlags(); static boolean equalsRate(long actual, long expected, boolean isESwitch); static boolean equalsBurstSize(long actual, long expected, boolean isESwitch); static final int MIN_RATE_IN_KBPS; }
|
@Test public void changingOfFlowSegmentCookieTypeTest() { FlowSegmentCookie flowCookie = new FlowSegmentCookie(FlowPathDirection.FORWARD, 10); Assert.assertEquals(CookieType.SERVICE_OR_FLOW_SEGMENT, flowCookie.getType()); FlowSegmentCookie server42Cookie = flowCookie.toBuilder() .type(CookieType.SERVER_42_INGRESS) .build(); Assert.assertEquals(CookieType.SERVER_42_INGRESS, server42Cookie.getType()); }
|
@Override public FlowSegmentCookieBuilder toBuilder() { return new FlowSegmentCookieBuilder() .type(getType()) .direction(getDirection()) .flowEffectiveId(getFlowEffectiveId()); }
|
FlowSegmentCookie extends Cookie { @Override public FlowSegmentCookieBuilder toBuilder() { return new FlowSegmentCookieBuilder() .type(getType()) .direction(getDirection()) .flowEffectiveId(getFlowEffectiveId()); } }
|
FlowSegmentCookie extends Cookie { @Override public FlowSegmentCookieBuilder toBuilder() { return new FlowSegmentCookieBuilder() .type(getType()) .direction(getDirection()) .flowEffectiveId(getFlowEffectiveId()); } @JsonCreator FlowSegmentCookie(long value); FlowSegmentCookie(FlowPathDirection direction, long flowEffectiveId); FlowSegmentCookie(CookieType type, long value); @Builder private FlowSegmentCookie(CookieType type, FlowPathDirection direction, long flowEffectiveId); }
|
FlowSegmentCookie extends Cookie { @Override public FlowSegmentCookieBuilder toBuilder() { return new FlowSegmentCookieBuilder() .type(getType()) .direction(getDirection()) .flowEffectiveId(getFlowEffectiveId()); } @JsonCreator FlowSegmentCookie(long value); FlowSegmentCookie(FlowPathDirection direction, long flowEffectiveId); FlowSegmentCookie(CookieType type, long value); @Builder private FlowSegmentCookie(CookieType type, FlowPathDirection direction, long flowEffectiveId); @Override void validate(); @Override FlowSegmentCookieBuilder toBuilder(); FlowPathDirection getValidatedDirection(); FlowPathDirection getDirection(); long getFlowEffectiveId(); static FlowSegmentCookieBuilder builder(); }
|
FlowSegmentCookie extends Cookie { @Override public FlowSegmentCookieBuilder toBuilder() { return new FlowSegmentCookieBuilder() .type(getType()) .direction(getDirection()) .flowEffectiveId(getFlowEffectiveId()); } @JsonCreator FlowSegmentCookie(long value); FlowSegmentCookie(FlowPathDirection direction, long flowEffectiveId); FlowSegmentCookie(CookieType type, long value); @Builder private FlowSegmentCookie(CookieType type, FlowPathDirection direction, long flowEffectiveId); @Override void validate(); @Override FlowSegmentCookieBuilder toBuilder(); FlowPathDirection getValidatedDirection(); FlowPathDirection getDirection(); long getFlowEffectiveId(); static FlowSegmentCookieBuilder builder(); }
|
@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()); } }
|
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 { 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 { 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); }
|
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); }
|
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(expected = IllegalArgumentException.class) public void testContainsNodeInvalidInput() { flow.getForwardPath().getSegments().get(0).containsNode(null, 1); }
|
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()); }
|
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()); } }
|
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); }
|
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(); }
|
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 public void testContainsNodeSourceMatch() { assertTrue(flow.getForwardPath().getSegments().get(0).containsNode(SWITCH_ID_A, 1)); }
|
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()); }
|
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()); } }
|
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); }
|
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(); }
|
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 public void testContainsNodeDestinationMatch() { assertTrue(flow.getForwardPath().getSegments().get(0).containsNode(SWITCH_ID_B, 1)); }
|
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()); }
|
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()); } }
|
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); }
|
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(); }
|
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 public void testContainsNodeNoSwitchMatch() { assertFalse(flow.getForwardPath().getSegments().get(0).containsNode(SWITCH_ID_C, 1)); }
|
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()); }
|
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()); } }
|
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); }
|
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(); }
|
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 public void testContainsNodeNoPortMatch() { assertFalse(flow.getForwardPath().getSegments().get(0).containsNode(SWITCH_ID_B, 2)); }
|
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()); }
|
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()); } }
|
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); }
|
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(); }
|
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 public void testContainsNodeNoSwitchPortMatch() { assertFalse(flow.getForwardPath().getSegments().get(0).containsNode(SWITCH_ID_C, 2)); }
|
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()); }
|
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()); } }
|
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); }
|
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(); }
|
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 createMeterIdForInvalidDefaultRuleTest() { MeterId.createMeterIdForDefaultRule(0x0000000000000123L); }
|
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)); }
|
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)); } }
|
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); }
|
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); }
|
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 validatePropRaiseTest() { Switch sw = Switch.builder() .switchId(new SwitchId(1)) .build(); SwitchProperties sp = SwitchProperties.builder() .switchObj(sw) .build(); sp.validateProp(SwitchFeature.BFD); }
|
@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; }
|
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; } }
|
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); }
|
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(); }
|
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 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)); }
|
@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; }
|
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; } }
|
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); }
|
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(); }
|
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 setUnsupportedMultiTableFlagTest() { Switch sw = Switch.builder() .switchId(new SwitchId(1)) .build(); SwitchProperties sp = SwitchProperties.builder() .switchObj(sw) .build(); sp.setMultiTable(true); }
|
public void setMultiTable(boolean multiTable) { if (multiTable) { validateProp(SwitchFeature.MULTI_TABLE); } data.setMultiTable(multiTable); }
|
SwitchProperties implements CompositeDataEntity<SwitchProperties.SwitchPropertiesData> { public void setMultiTable(boolean multiTable) { if (multiTable) { validateProp(SwitchFeature.MULTI_TABLE); } data.setMultiTable(multiTable); } }
|
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); }
|
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(); }
|
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 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()); }
|
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 { 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 { 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); }
|
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); }
|
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(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); }
|
public void setSupportedTransitEncapsulation(Set<FlowEncapsulationType> supportedTransitEncapsulation) { if (supportedTransitEncapsulation != null && supportedTransitEncapsulation.contains(FlowEncapsulationType.VXLAN)) { validateProp(SwitchFeature.NOVIFLOW_COPY_FIELD); } data.setSupportedTransitEncapsulation(supportedTransitEncapsulation); }
|
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); } }
|
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); }
|
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(); }
|
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 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))); }
|
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 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 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 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); }
|
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 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); }
|
@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 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 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 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); }
|
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 shouldCreateAnInstance() { PathComputerFactory factory = new PathComputerFactory( mock(PathComputerConfig.class), mock(AvailableNetworkFactory.class)); PathComputer pathComputer = factory.getPathComputer(); assertTrue(pathComputer instanceof InMemoryPathComputer); }
|
public PathComputer getPathComputer() { return new InMemoryPathComputer(availableNetworkFactory, new BestWeightAndShortestPathFinder(config.getMaxAllowedDepth()), config); }
|
PathComputerFactory { public PathComputer getPathComputer() { return new InMemoryPathComputer(availableNetworkFactory, new BestWeightAndShortestPathFinder(config.getMaxAllowedDepth()), config); } }
|
PathComputerFactory { public PathComputer getPathComputer() { return new InMemoryPathComputer(availableNetworkFactory, new BestWeightAndShortestPathFinder(config.getMaxAllowedDepth()), config); } PathComputerFactory(PathComputerConfig config, AvailableNetworkFactory availableNetworkFactory); }
|
PathComputerFactory { public PathComputer getPathComputer() { return new InMemoryPathComputer(availableNetworkFactory, new BestWeightAndShortestPathFinder(config.getMaxAllowedDepth()), config); } PathComputerFactory(PathComputerConfig config, AvailableNetworkFactory availableNetworkFactory); PathComputer getPathComputer(); }
|
PathComputerFactory { public PathComputer getPathComputer() { return new InMemoryPathComputer(availableNetworkFactory, new BestWeightAndShortestPathFinder(config.getMaxAllowedDepth()), config); } PathComputerFactory(PathComputerConfig config, AvailableNetworkFactory availableNetworkFactory); PathComputer getPathComputer(); }
|
@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); }
|
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 { 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 { 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); }
|
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); }
|
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 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()); }
|
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 { 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 { 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); }
|
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); }
|
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 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); }
|
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 { 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 { 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); }
|
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); }
|
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 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); }
|
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 { 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 { 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); }
|
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); }
|
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 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); }
|
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 { 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 { 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); }
|
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); }
|
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 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)); }
|
public FlowIdStatusPayload getPayload() { return payload; }
|
FlowStatusResponse extends InfoData { public FlowIdStatusPayload getPayload() { return payload; } }
|
FlowStatusResponse extends InfoData { public FlowIdStatusPayload getPayload() { return payload; } @JsonCreator FlowStatusResponse(@JsonProperty(PAYLOAD) final FlowIdStatusPayload payload); }
|
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); }
|
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(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); }
|
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 { 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 { 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); }
|
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); }
|
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(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); }
|
@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 { @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 { @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); }
|
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); }
|
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 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); }
|
@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 { @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 { @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); }
|
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); }
|
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 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); }
|
@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 { @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 { @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); }
|
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); }
|
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 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); }
|
@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 { @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 { @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); }
|
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); }
|
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 = 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); }
|
@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 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 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); }
|
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); }
|
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() 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); }
|
@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 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 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); }
|
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); }
|
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 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); }
|
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 { 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 { 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); }
|
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); }
|
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 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); }
|
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 { 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 { 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); }
|
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); }
|
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 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)); }
|
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 { 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 { 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); }
|
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); }
|
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 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)); }
|
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 { 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 { 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); }
|
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); }
|
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(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); }
|
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 { 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 { 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); }
|
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); }
|
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(expected = IllegalSwitchPropertiesException.class) public void shouldValidateMultiTableFlagWhenUpdatingSwitchProperties() { Switch sw = Switch.builder().switchId(TEST_SWITCH_ID).status(SwitchStatus.ACTIVE).build(); switchRepository.add(sw); createSwitchProperties(sw, Collections.singleton(FlowEncapsulationType.TRANSIT_VLAN), true, true, false); SwitchPropertiesDto update = new SwitchPropertiesDto(); update.setSupportedTransitEncapsulation( Collections.singleton(org.openkilda.messaging.payload.flow.FlowEncapsulationType.TRANSIT_VLAN)); update.setMultiTable(false); update.setSwitchLldp(true); switchOperationsService.updateSwitchProperties(TEST_SWITCH_ID, update); }
|
public SwitchPropertiesDto updateSwitchProperties(SwitchId switchId, SwitchPropertiesDto switchPropertiesDto) { if (isEmpty(switchPropertiesDto.getSupportedTransitEncapsulation())) { throw new IllegalSwitchPropertiesException("Supported transit encapsulations should not be null or empty"); } SwitchProperties update = SwitchPropertiesMapper.INSTANCE.map(switchPropertiesDto); UpdateSwitchPropertiesResult result = transactionManager.doInTransaction(() -> { SwitchProperties switchProperties = switchPropertiesRepository.findBySwitchId(switchId) .orElseThrow(() -> new SwitchPropertiesNotFoundException(switchId)); validateSwitchProperties(switchId, update); final boolean isSwitchSyncNeeded = isSwitchSyncNeeded(switchProperties, update); switchProperties.setMultiTable(update.isMultiTable()); switchProperties.setSwitchLldp(update.isSwitchLldp()); switchProperties.setSwitchArp(update.isSwitchArp()); switchProperties.setSupportedTransitEncapsulation(update.getSupportedTransitEncapsulation()); switchProperties.setServer42FlowRtt(update.isServer42FlowRtt()); switchProperties.setServer42Port(update.getServer42Port()); switchProperties.setServer42Vlan(update.getServer42Vlan()); switchProperties.setServer42MacAddress(update.getServer42MacAddress()); return new UpdateSwitchPropertiesResult( SwitchPropertiesMapper.INSTANCE.map(switchProperties), isSwitchSyncNeeded); }); if (result.isSwitchSyncRequired()) { carrier.requestSwitchSync(switchId); } if (switchPropertiesDto.isServer42FlowRtt()) { carrier.enableServer42FlowRttOnSwitch(switchId); } else { carrier.disableServer42FlowRttOnSwitch(switchId); } return result.switchPropertiesDto; }
|
SwitchOperationsService implements ILinkOperationsServiceCarrier { public SwitchPropertiesDto updateSwitchProperties(SwitchId switchId, SwitchPropertiesDto switchPropertiesDto) { if (isEmpty(switchPropertiesDto.getSupportedTransitEncapsulation())) { throw new IllegalSwitchPropertiesException("Supported transit encapsulations should not be null or empty"); } SwitchProperties update = SwitchPropertiesMapper.INSTANCE.map(switchPropertiesDto); UpdateSwitchPropertiesResult result = transactionManager.doInTransaction(() -> { SwitchProperties switchProperties = switchPropertiesRepository.findBySwitchId(switchId) .orElseThrow(() -> new SwitchPropertiesNotFoundException(switchId)); validateSwitchProperties(switchId, update); final boolean isSwitchSyncNeeded = isSwitchSyncNeeded(switchProperties, update); switchProperties.setMultiTable(update.isMultiTable()); switchProperties.setSwitchLldp(update.isSwitchLldp()); switchProperties.setSwitchArp(update.isSwitchArp()); switchProperties.setSupportedTransitEncapsulation(update.getSupportedTransitEncapsulation()); switchProperties.setServer42FlowRtt(update.isServer42FlowRtt()); switchProperties.setServer42Port(update.getServer42Port()); switchProperties.setServer42Vlan(update.getServer42Vlan()); switchProperties.setServer42MacAddress(update.getServer42MacAddress()); return new UpdateSwitchPropertiesResult( SwitchPropertiesMapper.INSTANCE.map(switchProperties), isSwitchSyncNeeded); }); if (result.isSwitchSyncRequired()) { carrier.requestSwitchSync(switchId); } if (switchPropertiesDto.isServer42FlowRtt()) { carrier.enableServer42FlowRttOnSwitch(switchId); } else { carrier.disableServer42FlowRttOnSwitch(switchId); } return result.switchPropertiesDto; } }
|
SwitchOperationsService implements ILinkOperationsServiceCarrier { public SwitchPropertiesDto updateSwitchProperties(SwitchId switchId, SwitchPropertiesDto switchPropertiesDto) { if (isEmpty(switchPropertiesDto.getSupportedTransitEncapsulation())) { throw new IllegalSwitchPropertiesException("Supported transit encapsulations should not be null or empty"); } SwitchProperties update = SwitchPropertiesMapper.INSTANCE.map(switchPropertiesDto); UpdateSwitchPropertiesResult result = transactionManager.doInTransaction(() -> { SwitchProperties switchProperties = switchPropertiesRepository.findBySwitchId(switchId) .orElseThrow(() -> new SwitchPropertiesNotFoundException(switchId)); validateSwitchProperties(switchId, update); final boolean isSwitchSyncNeeded = isSwitchSyncNeeded(switchProperties, update); switchProperties.setMultiTable(update.isMultiTable()); switchProperties.setSwitchLldp(update.isSwitchLldp()); switchProperties.setSwitchArp(update.isSwitchArp()); switchProperties.setSupportedTransitEncapsulation(update.getSupportedTransitEncapsulation()); switchProperties.setServer42FlowRtt(update.isServer42FlowRtt()); switchProperties.setServer42Port(update.getServer42Port()); switchProperties.setServer42Vlan(update.getServer42Vlan()); switchProperties.setServer42MacAddress(update.getServer42MacAddress()); return new UpdateSwitchPropertiesResult( SwitchPropertiesMapper.INSTANCE.map(switchProperties), isSwitchSyncNeeded); }); if (result.isSwitchSyncRequired()) { carrier.requestSwitchSync(switchId); } if (switchPropertiesDto.isServer42FlowRtt()) { carrier.enableServer42FlowRttOnSwitch(switchId); } else { carrier.disableServer42FlowRttOnSwitch(switchId); } return result.switchPropertiesDto; } SwitchOperationsService(RepositoryFactory repositoryFactory,
TransactionManager transactionManager,
SwitchOperationsServiceCarrier carrier); }
|
SwitchOperationsService implements ILinkOperationsServiceCarrier { public SwitchPropertiesDto updateSwitchProperties(SwitchId switchId, SwitchPropertiesDto switchPropertiesDto) { if (isEmpty(switchPropertiesDto.getSupportedTransitEncapsulation())) { throw new IllegalSwitchPropertiesException("Supported transit encapsulations should not be null or empty"); } SwitchProperties update = SwitchPropertiesMapper.INSTANCE.map(switchPropertiesDto); UpdateSwitchPropertiesResult result = transactionManager.doInTransaction(() -> { SwitchProperties switchProperties = switchPropertiesRepository.findBySwitchId(switchId) .orElseThrow(() -> new SwitchPropertiesNotFoundException(switchId)); validateSwitchProperties(switchId, update); final boolean isSwitchSyncNeeded = isSwitchSyncNeeded(switchProperties, update); switchProperties.setMultiTable(update.isMultiTable()); switchProperties.setSwitchLldp(update.isSwitchLldp()); switchProperties.setSwitchArp(update.isSwitchArp()); switchProperties.setSupportedTransitEncapsulation(update.getSupportedTransitEncapsulation()); switchProperties.setServer42FlowRtt(update.isServer42FlowRtt()); switchProperties.setServer42Port(update.getServer42Port()); switchProperties.setServer42Vlan(update.getServer42Vlan()); switchProperties.setServer42MacAddress(update.getServer42MacAddress()); return new UpdateSwitchPropertiesResult( SwitchPropertiesMapper.INSTANCE.map(switchProperties), isSwitchSyncNeeded); }); if (result.isSwitchSyncRequired()) { carrier.requestSwitchSync(switchId); } if (switchPropertiesDto.isServer42FlowRtt()) { carrier.enableServer42FlowRttOnSwitch(switchId); } else { carrier.disableServer42FlowRttOnSwitch(switchId); } return result.switchPropertiesDto; } SwitchOperationsService(RepositoryFactory repositoryFactory,
TransactionManager transactionManager,
SwitchOperationsServiceCarrier carrier); GetSwitchResponse getSwitch(SwitchId switchId); List<GetSwitchResponse> getAllSwitches(); Switch updateSwitchUnderMaintenanceFlag(SwitchId switchId, boolean underMaintenance); boolean deleteSwitch(SwitchId switchId, boolean force); void checkSwitchIsDeactivated(SwitchId switchId); void checkSwitchHasNoFlows(SwitchId switchId); void checkSwitchHasNoFlowSegments(SwitchId switchId); void checkSwitchHasNoIsls(SwitchId switchId); SwitchPropertiesDto getSwitchProperties(SwitchId switchId); SwitchPropertiesDto updateSwitchProperties(SwitchId switchId, SwitchPropertiesDto switchPropertiesDto); PortProperties getPortProperties(SwitchId switchId, int port); Collection<SwitchConnectedDevice> getSwitchConnectedDevices(
SwitchId switchId); List<IslEndpoint> getSwitchIslEndpoints(SwitchId switchId); Switch patchSwitch(SwitchId switchId, SwitchPatch data); }
|
SwitchOperationsService implements ILinkOperationsServiceCarrier { public SwitchPropertiesDto updateSwitchProperties(SwitchId switchId, SwitchPropertiesDto switchPropertiesDto) { if (isEmpty(switchPropertiesDto.getSupportedTransitEncapsulation())) { throw new IllegalSwitchPropertiesException("Supported transit encapsulations should not be null or empty"); } SwitchProperties update = SwitchPropertiesMapper.INSTANCE.map(switchPropertiesDto); UpdateSwitchPropertiesResult result = transactionManager.doInTransaction(() -> { SwitchProperties switchProperties = switchPropertiesRepository.findBySwitchId(switchId) .orElseThrow(() -> new SwitchPropertiesNotFoundException(switchId)); validateSwitchProperties(switchId, update); final boolean isSwitchSyncNeeded = isSwitchSyncNeeded(switchProperties, update); switchProperties.setMultiTable(update.isMultiTable()); switchProperties.setSwitchLldp(update.isSwitchLldp()); switchProperties.setSwitchArp(update.isSwitchArp()); switchProperties.setSupportedTransitEncapsulation(update.getSupportedTransitEncapsulation()); switchProperties.setServer42FlowRtt(update.isServer42FlowRtt()); switchProperties.setServer42Port(update.getServer42Port()); switchProperties.setServer42Vlan(update.getServer42Vlan()); switchProperties.setServer42MacAddress(update.getServer42MacAddress()); return new UpdateSwitchPropertiesResult( SwitchPropertiesMapper.INSTANCE.map(switchProperties), isSwitchSyncNeeded); }); if (result.isSwitchSyncRequired()) { carrier.requestSwitchSync(switchId); } if (switchPropertiesDto.isServer42FlowRtt()) { carrier.enableServer42FlowRttOnSwitch(switchId); } else { carrier.disableServer42FlowRttOnSwitch(switchId); } return result.switchPropertiesDto; } SwitchOperationsService(RepositoryFactory repositoryFactory,
TransactionManager transactionManager,
SwitchOperationsServiceCarrier carrier); GetSwitchResponse getSwitch(SwitchId switchId); List<GetSwitchResponse> getAllSwitches(); Switch updateSwitchUnderMaintenanceFlag(SwitchId switchId, boolean underMaintenance); boolean deleteSwitch(SwitchId switchId, boolean force); void checkSwitchIsDeactivated(SwitchId switchId); void checkSwitchHasNoFlows(SwitchId switchId); void checkSwitchHasNoFlowSegments(SwitchId switchId); void checkSwitchHasNoIsls(SwitchId switchId); SwitchPropertiesDto getSwitchProperties(SwitchId switchId); SwitchPropertiesDto updateSwitchProperties(SwitchId switchId, SwitchPropertiesDto switchPropertiesDto); PortProperties getPortProperties(SwitchId switchId, int port); Collection<SwitchConnectedDevice> getSwitchConnectedDevices(
SwitchId switchId); List<IslEndpoint> getSwitchIslEndpoints(SwitchId switchId); Switch patchSwitch(SwitchId switchId, SwitchPatch data); }
|
@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); }
|
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 { 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 { 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); }
|
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); }
|
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 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()); }
|
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 { 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 { 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); }
|
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); }
|
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 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); }
|
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 { 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 { 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); }
|
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); }
|
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 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()); }
|
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 { 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 { 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); }
|
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); }
|
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 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); }
|
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 { 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 { 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); }
|
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); }
|
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 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); }
|
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 { 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 { 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); }
|
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); }
|
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 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); }
|
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 { 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 { 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); }
|
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); }
|
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 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); }
|
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 { 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 { 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); }
|
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); }
|
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 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); }
|
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 { 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 { 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); }
|
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); }
|
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 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); }
|
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 { 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 { 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); }
|
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); }
|
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 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()); }
|
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 { 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 { 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); }
|
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); }
|
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 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); }
|
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 { 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 { 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); }
|
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); }
|
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 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()); }
|
public RequestedFlow toRequestedFlow(FlowRequest request) { RequestedFlow flow = generatedMap(request); RequestedFlowIncrementalMapper.INSTANCE.mapSource(flow, request.getSource()); RequestedFlowIncrementalMapper.INSTANCE.mapDestination(flow, request.getDestination()); return flow; }
|
RequestedFlowMapper { public RequestedFlow toRequestedFlow(FlowRequest request) { RequestedFlow flow = generatedMap(request); RequestedFlowIncrementalMapper.INSTANCE.mapSource(flow, request.getSource()); RequestedFlowIncrementalMapper.INSTANCE.mapDestination(flow, request.getDestination()); return flow; } }
|
RequestedFlowMapper { public RequestedFlow toRequestedFlow(FlowRequest request) { RequestedFlow flow = generatedMap(request); RequestedFlowIncrementalMapper.INSTANCE.mapSource(flow, request.getSource()); RequestedFlowIncrementalMapper.INSTANCE.mapDestination(flow, request.getDestination()); return flow; } }
|
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); }
|
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 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()); }
|
public RequestedFlow toRequestedFlow(FlowRequest request) { RequestedFlow flow = generatedMap(request); RequestedFlowIncrementalMapper.INSTANCE.mapSource(flow, request.getSource()); RequestedFlowIncrementalMapper.INSTANCE.mapDestination(flow, request.getDestination()); return flow; }
|
RequestedFlowMapper { public RequestedFlow toRequestedFlow(FlowRequest request) { RequestedFlow flow = generatedMap(request); RequestedFlowIncrementalMapper.INSTANCE.mapSource(flow, request.getSource()); RequestedFlowIncrementalMapper.INSTANCE.mapDestination(flow, request.getDestination()); return flow; } }
|
RequestedFlowMapper { public RequestedFlow toRequestedFlow(FlowRequest request) { RequestedFlow flow = generatedMap(request); RequestedFlowIncrementalMapper.INSTANCE.mapSource(flow, request.getSource()); RequestedFlowIncrementalMapper.INSTANCE.mapDestination(flow, request.getDestination()); return flow; } }
|
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); }
|
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 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()); }
|
@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);
|
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); }
|
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); }
|
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); }
|
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 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()); }
|
public RequestedFlow toRequestedFlow(FlowRequest request) { RequestedFlow flow = generatedMap(request); RequestedFlowIncrementalMapper.INSTANCE.mapSource(flow, request.getSource()); RequestedFlowIncrementalMapper.INSTANCE.mapDestination(flow, request.getDestination()); return flow; }
|
RequestedFlowMapper { public RequestedFlow toRequestedFlow(FlowRequest request) { RequestedFlow flow = generatedMap(request); RequestedFlowIncrementalMapper.INSTANCE.mapSource(flow, request.getSource()); RequestedFlowIncrementalMapper.INSTANCE.mapDestination(flow, request.getDestination()); return flow; } }
|
RequestedFlowMapper { public RequestedFlow toRequestedFlow(FlowRequest request) { RequestedFlow flow = generatedMap(request); RequestedFlowIncrementalMapper.INSTANCE.mapSource(flow, request.getSource()); RequestedFlowIncrementalMapper.INSTANCE.mapDestination(flow, request.getDestination()); return flow; } }
|
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); }
|
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 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)); }
|
public Boolean toBoolean(YesNo yesNo) { if (yesNo == null) { return null; } switch (yesNo) { case YES: return true; case NO: return false; default: return null; } }
|
NoviflowResponseMapper { public Boolean toBoolean(YesNo yesNo) { if (yesNo == null) { return null; } switch (yesNo) { case YES: return true; case NO: return false; default: return null; } } }
|
NoviflowResponseMapper { public Boolean toBoolean(YesNo yesNo) { if (yesNo == null) { return null; } switch (yesNo) { case YES: return true; case NO: return false; default: return null; } } }
|
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); }
|
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 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()); }
|
@Mapping(source = "logicalportno", target = "logicalPortNumber") @Mapping(source = "portnoList", target = "portNumbers") @Mapping(source = "logicalporttype", target = "type") public abstract LogicalPort map(io.grpc.noviflow.LogicalPort port);
|
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); }
|
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); }
|
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); }
|
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 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)); }
|
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; }
|
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; } }
|
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; } }
|
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); }
|
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 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)); }
|
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; }
|
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; } }
|
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; } }
|
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); }
|
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 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)); }
|
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; }
|
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; } }
|
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; } }
|
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); }
|
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 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()); }
|
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 { 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 { 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); }
|
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); }
|
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 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)); }
|
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; }
|
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; } }
|
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; } }
|
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); }
|
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 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)); }
|
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; }
|
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; } }
|
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; } }
|
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); }
|
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 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()); }
|
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; }
|
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; } }
|
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; } }
|
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); }
|
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 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)); }
|
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; }
|
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; } }
|
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; } }
|
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); }
|
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 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)); }
|
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; }
|
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; } }
|
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; } }
|
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); }
|
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 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())); }
|
@Override public List<FlowSegmentRequestFactory> buildAllExceptIngress(CommandContext context, @NonNull Flow flow) { return buildAllExceptIngress(context, flow, flow.getForwardPath(), flow.getReversePath()); }
|
SpeakerFlowSegmentRequestBuilder implements FlowCommandBuilder { @Override public List<FlowSegmentRequestFactory> buildAllExceptIngress(CommandContext context, @NonNull Flow flow) { return buildAllExceptIngress(context, flow, flow.getForwardPath(), flow.getReversePath()); } }
|
SpeakerFlowSegmentRequestBuilder implements FlowCommandBuilder { @Override public List<FlowSegmentRequestFactory> buildAllExceptIngress(CommandContext context, @NonNull Flow flow) { return buildAllExceptIngress(context, flow, flow.getForwardPath(), flow.getReversePath()); } SpeakerFlowSegmentRequestBuilder(FlowResourcesManager resourcesManager); }
|
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); }
|
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 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())); }
|
@Override public List<FlowSegmentRequestFactory> buildAllExceptIngress(CommandContext context, @NonNull Flow flow) { return buildAllExceptIngress(context, flow, flow.getForwardPath(), flow.getReversePath()); }
|
SpeakerFlowSegmentRequestBuilder implements FlowCommandBuilder { @Override public List<FlowSegmentRequestFactory> buildAllExceptIngress(CommandContext context, @NonNull Flow flow) { return buildAllExceptIngress(context, flow, flow.getForwardPath(), flow.getReversePath()); } }
|
SpeakerFlowSegmentRequestBuilder implements FlowCommandBuilder { @Override public List<FlowSegmentRequestFactory> buildAllExceptIngress(CommandContext context, @NonNull Flow flow) { return buildAllExceptIngress(context, flow, flow.getForwardPath(), flow.getReversePath()); } SpeakerFlowSegmentRequestBuilder(FlowResourcesManager resourcesManager); }
|
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); }
|
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 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())); }
|
@Override public List<FlowSegmentRequestFactory> buildAll(CommandContext context, Flow flow, FlowPath path, SpeakerRequestBuildContext speakerRequestBuildContext) { return makeRequests(context, flow, path, null, true, true, true, speakerRequestBuildContext); }
|
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 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); }
|
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); }
|
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 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); }
|
@Override public List<FlowSegmentRequestFactory> buildIngressOnly( CommandContext context, @NonNull Flow flow, SpeakerRequestBuildContext speakerRequestBuildContext) { return buildIngressOnly(context, flow, flow.getForwardPath(), flow.getReversePath(), speakerRequestBuildContext); }
|
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 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); }
|
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); }
|
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 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); }
|
public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); }
|
IntersectionComputer { public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); } }
|
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); }
|
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); }
|
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 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); }
|
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 { 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 { 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); }
|
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); }
|
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 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); }
|
public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); }
|
IntersectionComputer { public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); } }
|
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); }
|
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); }
|
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 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); }
|
public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); }
|
IntersectionComputer { public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); } }
|
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); }
|
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); }
|
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 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); }
|
public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); }
|
IntersectionComputer { public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); } }
|
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); }
|
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); }
|
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 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); }
|
public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); }
|
IntersectionComputer { public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); } }
|
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); }
|
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); }
|
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 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); }
|
public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); }
|
IntersectionComputer { public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); } }
|
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); }
|
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); }
|
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 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); }
|
public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); }
|
IntersectionComputer { public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); } }
|
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); }
|
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); }
|
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 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); }
|
public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); }
|
IntersectionComputer { public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); } }
|
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); }
|
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); }
|
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 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); }
|
public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); }
|
IntersectionComputer { public OverlappingSegmentsStats getOverlappingStats() { return computeIntersectionCounters( otherEdges.values().stream().flatMap(Collection::stream).collect(Collectors.toSet())); } }
|
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); }
|
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); }
|
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 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)); }
|
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 { 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 { 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); }
|
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); }
|
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 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)); }
|
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 { 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 { 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); }
|
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); }
|
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 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); }
|
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 { 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 { 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); }
|
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); }
|
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 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); }
|
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); }
|
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); } }
|
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); } }
|
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); }
|
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 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()); }
|
@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);
|
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); }
|
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); }
|
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); }
|
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 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()); }
|
@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);
|
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); }
|
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); }
|
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); }
|
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 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()); }
|
@Mapping(source = "state", target = "status") public abstract Port map(PortInfoData portInfoData);
|
PortMapper { @Mapping(source = "state", target = "status") public abstract Port map(PortInfoData portInfoData); }
|
PortMapper { @Mapping(source = "state", target = "status") public abstract Port map(PortInfoData portInfoData); }
|
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); }
|
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 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); }
|
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; }
|
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; } }
|
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; } }
|
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); }
|
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); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.