src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
|---|---|
FermaPortPropertiesRepository extends FermaGenericRepository<PortProperties, PortPropertiesData, PortPropertiesFrame> implements PortPropertiesRepository { @Override public Optional<PortProperties> getBySwitchIdAndPort(SwitchId switchId, int port) { List<? extends PortPropertiesFrame> portPropertiesFrames = framedGraph().traverse(g -> g.V() .hasLabel(PortPropertiesFrame.FRAME_LABEL) .has(PortPropertiesFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(PortPropertiesFrame.PORT_NO_PROPERTY, port)) .toListExplicit(PortPropertiesFrame.class); return portPropertiesFrames.isEmpty() ? Optional.empty() : Optional.of(portPropertiesFrames.get(0)) .map(PortProperties::new); } FermaPortPropertiesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<PortProperties> findAll(); @Override Optional<PortProperties> getBySwitchIdAndPort(SwitchId switchId, int port); @Override Collection<PortProperties> getAllBySwitchId(SwitchId switchId); }
|
@Test public void shouldGetPortPropertiesBySwitchIdAndPort() { Switch origSwitch = createTestSwitch(TEST_SWITCH_ID.getId()); int port = 7; PortProperties portProperties = PortProperties.builder() .switchObj(origSwitch) .port(port) .discoveryEnabled(false) .build(); portPropertiesRepository.add(portProperties); Optional<PortProperties> portPropertiesResult = portPropertiesRepository.getBySwitchIdAndPort(origSwitch.getSwitchId(), port); assertTrue(portPropertiesResult.isPresent()); assertEquals(origSwitch.getSwitchId(), portPropertiesResult.get().getSwitchObj().getSwitchId()); assertEquals(port, portPropertiesResult.get().getPort()); assertFalse(portPropertiesResult.get().isDiscoveryEnabled()); }
|
FermaFlowCookieRepository extends FermaGenericRepository<FlowCookie, FlowCookieData, FlowCookieFrame> implements FlowCookieRepository { @Override public Collection<FlowCookie> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(FlowCookieFrame.FRAME_LABEL)) .toListExplicit(FlowCookieFrame.class).stream() .map(FlowCookie::new) .collect(Collectors.toList()); } FermaFlowCookieRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowCookie> findAll(); @Override boolean exists(long unmaskedCookie); @Override Optional<FlowCookie> findByCookie(long unmaskedCookie); @Override Optional<Long> findFirstUnassignedCookie(long lowestCookieValue, long highestCookieValue); }
|
@Test public void shouldCreateFlowCookie() { createFlowCookie(); Collection<FlowCookie> allCookies = flowCookieRepository.findAll(); FlowCookie foundCookie = allCookies.iterator().next(); assertEquals(TEST_COOKIE, foundCookie.getUnmaskedCookie()); assertEquals(TEST_FLOW_ID, foundCookie.getFlowId()); }
@Test public void shouldDeleteFlowCookie() { FlowCookie cookie = createFlowCookie(); transactionManager.doInTransaction(() -> flowCookieRepository.remove(cookie)); assertEquals(0, flowCookieRepository.findAll().size()); }
@Test public void shouldDeleteFoundFlowCookie() { createFlowCookie(); transactionManager.doInTransaction(() -> { Collection<FlowCookie> allCookies = flowCookieRepository.findAll(); FlowCookie foundCookie = allCookies.iterator().next(); flowCookieRepository.remove(foundCookie); }); assertEquals(0, flowCookieRepository.findAll().size()); }
|
FermaFlowCookieRepository extends FermaGenericRepository<FlowCookie, FlowCookieData, FlowCookieFrame> implements FlowCookieRepository { @Override public Optional<FlowCookie> findByCookie(long unmaskedCookie) { List<? extends FlowCookieFrame> flowCookieFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowCookieFrame.FRAME_LABEL) .has(FlowCookieFrame.UNMASKED_COOKIE_PROPERTY, unmaskedCookie)) .toListExplicit(FlowCookieFrame.class); return flowCookieFrames.isEmpty() ? Optional.empty() : Optional.of(flowCookieFrames.get(0)) .map(FlowCookie::new); } FermaFlowCookieRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowCookie> findAll(); @Override boolean exists(long unmaskedCookie); @Override Optional<FlowCookie> findByCookie(long unmaskedCookie); @Override Optional<Long> findFirstUnassignedCookie(long lowestCookieValue, long highestCookieValue); }
|
@Test public void shouldSelectNextInOrderResourceWhenFindUnassignedCookie() { long first = findUnassignedCookieAndCreate("flow_1"); assertEquals(5, first); long second = findUnassignedCookieAndCreate("flow_2"); assertEquals(6, second); long third = findUnassignedCookieAndCreate("flow_3"); assertEquals(7, third); transactionManager.doInTransaction(() -> flowCookieRepository.findByCookie(second).ifPresent(flowCookieRepository::remove)); long fourth = findUnassignedCookieAndCreate("flow_4"); assertEquals(6, fourth); long fifth = findUnassignedCookieAndCreate("flow_5"); assertEquals(8, fifth); }
|
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Optional<FlowPath> findById(PathId pathId) { List<? extends FlowPathFrame> flowPathFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowPathFrame.FRAME_LABEL) .has(FlowPathFrame.PATH_ID_PROPERTY, PathIdConverter.INSTANCE.toGraphProperty(pathId))) .toListExplicit(FlowPathFrame.class); return flowPathFrames.isEmpty() ? Optional.empty() : Optional.of(flowPathFrames.get(0)) .map(FlowPath::new); } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }
|
@Test public void shouldFlowPathUpdateKeepRelations() { createTestFlowPathPair(); Flow foundFlow = flowRepository.findById(TEST_FLOW_ID).get(); assertThat(foundFlow.getPaths(), hasSize(2)); FlowPath foundPath = flowPathRepository.findById(flow.getForwardPathId()).get(); foundPath.setStatus(FlowPathStatus.INACTIVE); foundFlow = flowRepository.findById(TEST_FLOW_ID).get(); assertThat(foundFlow.getPaths(), hasSize(2)); }
@Test public void shouldFlowPathUpdateKeepFlowRelations() { createTestFlowPathPair(); Flow foundFlow = flowRepository.findById(TEST_FLOW_ID).get(); assertThat(foundFlow.getPaths(), hasSize(2)); FlowPath flowPath = foundFlow.getPaths().stream() .filter(path -> path.getPathId().equals(flow.getReversePathId())) .findAny().get(); flowPath.setStatus(FlowPathStatus.INACTIVE); foundFlow = flowRepository.findById(TEST_FLOW_ID).get(); assertThat(foundFlow.getPaths(), hasSize(2)); }
@Test public void shouldFindPathById() { FlowPath flowPath = createTestFlowPath(); Optional<FlowPath> foundPath = flowPathRepository.findById(flowPath.getPathId()); assertTrue(foundPath.isPresent()); }
@Test public void shouldKeepSegmentsOrdered() { FlowPath flowPath = createTestFlowPath(); List<PathSegment> segments = asList(PathSegment.builder() .srcSwitch(switchA) .destSwitch(switchC) .build(), PathSegment.builder() .srcSwitch(switchC) .destSwitch(switchB) .build()); flowPath.setSegments(segments); Optional<FlowPath> foundPath = flowPathRepository.findById(flowPath.getPathId()); assertEquals(foundPath.get().getSegments().get(0).getDestSwitchId(), switchC.getSwitchId()); }
|
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie) { List<? extends FlowPathFrame> flowPathFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowPathFrame.FRAME_LABEL) .has(FlowPathFrame.FLOW_ID_PROPERTY, flowId) .has(FlowPathFrame.COOKIE_PROPERTY, FlowSegmentCookieConverter.INSTANCE.toGraphProperty(cookie))) .toListExplicit(FlowPathFrame.class); if (flowPathFrames.size() > 1) { throw new PersistenceException(format("Found more that 1 FlowPath entity by (%s, %s)", flowId, cookie)); } return flowPathFrames.isEmpty() ? Optional.empty() : Optional.of(flowPathFrames.get(0)).map(FlowPath::new); } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }
|
@Test public void shouldFindPathByFlowIdAndCookie() { FlowPath flowPath = createTestFlowPath(); Optional<FlowPath> foundPath = flowPathRepository.findByFlowIdAndCookie(TEST_FLOW_ID, flowPath.getCookie()); assertTrue(foundPath.isPresent()); }
|
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected) { Map<PathId, FlowPath> result = new HashMap<>(); framedGraph().traverse(g -> g.V() .hasLabel(FlowPathFrame.FRAME_LABEL) .has(FlowPathFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .frameExplicit(FlowPathFrame.class) .forEachRemaining(frame -> result.put(frame.getPathId(), new FlowPath(frame))); framedGraph().traverse(g -> g.V() .hasLabel(FlowPathFrame.FRAME_LABEL) .has(FlowPathFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .frameExplicit(FlowPathFrame.class) .forEachRemaining(frame -> result.put(frame.getPathId(), new FlowPath(frame))); if (includeProtected) { return result.values(); } else { return result.values().stream() .filter(path -> !(path.isProtected() && switchId.equals(path.getSrcSwitchId()))) .collect(Collectors.toList()); } } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }
|
@Test public void shouldFindByEndpointSwitch() { createTestFlowPathPair(); Collection<FlowPath> paths = flowPathRepository.findByEndpointSwitch(switchA.getSwitchId()); assertThat(paths, containsInAnyOrder(flow.getForwardPath(), flow.getReversePath())); }
@Test public void shouldNotFindProtectedIngressByEndpointSwitch() { createTestFlowPathPair(); FlowPath protect = createFlowPath(flow, "_protectedpath", 10, 10, switchA, switchB); flow.setProtectedForwardPath(protect); Collection<FlowPath> paths = flowPathRepository.findByEndpointSwitch(switchA.getSwitchId()); assertThat(paths, containsInAnyOrder(flow.getForwardPath(), flow.getReversePath())); }
@Test public void shouldFindProtectedPathsByEndpointSwitchIncludeProtected() { createTestFlowPathPair(); flow.setProtectedForwardPath(createFlowPath(flow, "_forward_protected", 10, 10, switchA, switchB)); flow.setProtectedReversePath(createFlowPath(flow, "_reverse_protected", 11, 11, switchB, switchA)); Collection<FlowPath> paths = flowPathRepository.findByEndpointSwitch(switchA.getSwitchId(), true); assertThat(paths, containsInAnyOrder(flow.getForwardPath(), flow.getReversePath(), flow.getProtectedForwardPath(), flow.getProtectedReversePath())); }
@Test public void shouldFindPathByEndpointSwitch() { createTestFlowPath(); Collection<FlowPath> foundPaths = flowPathRepository.findByEndpointSwitch(switchB.getSwitchId()); assertThat(foundPaths, hasSize(1)); }
|
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected) { List<FlowPath> result = new ArrayList<>(); framedGraph().traverse(g -> g.V() .hasLabel(FlowPathFrame.FRAME_LABEL) .has(FlowPathFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .frameExplicit(FlowPathFrame.class) .forEachRemaining(frame -> result.add(new FlowPath(frame))); if (includeProtected) { return result; } else { return result.stream() .filter(path -> !(path.isProtected() && switchId.equals(path.getSrcSwitchId()))) .collect(Collectors.toList()); } } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }
|
@Test public void shouldFindProtectedPathsBySrcSwitchIncludeProtected() { createTestFlowPathPair(); flow.setProtectedForwardPath(createFlowPath(flow, "_forward_protected", 10, 10, switchA, switchB)); flow.setProtectedReversePath(createFlowPath(flow, "_reverse_protected", 11, 11, switchB, switchA)); assertThat(flowPathRepository.findBySrcSwitch(switchA.getSwitchId(), true), containsInAnyOrder(flow.getForwardPath(), flow.getProtectedForwardPath())); assertThat(flowPathRepository.findBySrcSwitch(switchB.getSwitchId(), true), containsInAnyOrder(flow.getReversePath(), flow.getProtectedReversePath())); }
@Test public void shouldFindBySrcSwitch() { createTestFlowPathPair(); Collection<FlowPath> paths = flowPathRepository.findBySrcSwitch(switchA.getSwitchId()); assertThat(paths, containsInAnyOrder(flow.getForwardPath())); }
@Test public void shouldFindPathBySrc() { createTestFlowPath(); Collection<FlowPath> foundPaths = flowPathRepository.findBySrcSwitch(switchA.getSwitchId()); assertThat(foundPaths, hasSize(1)); }
@Test public void shouldNotFindPathByWrongSrc() { createTestFlowPath(); Collection<FlowPath> foundPaths = flowPathRepository.findBySrcSwitch(switchB.getSwitchId()); assertThat(foundPaths, Matchers.empty()); }
|
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort) { return framedGraph().traverse(g -> g.V() .hasLabel(PathSegmentFrame.FRAME_LABEL) .has(PathSegmentFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(srcSwitchId)) .has(PathSegmentFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(dstSwitchId)) .has(PathSegmentFrame.SRC_PORT_PROPERTY, srcPort) .has(PathSegmentFrame.DST_PORT_PROPERTY, dstPort) .in(FlowPathFrame.OWNS_SEGMENTS_EDGE) .hasLabel(FlowPathFrame.FRAME_LABEL)) .toListExplicit(FlowPathFrame.class).stream() .map(FlowPath::new) .collect(Collectors.toList()); } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }
|
@Test public void shouldFindFlowPathsForIsl() { FlowPath flowPath = createTestFlowPathWithIntermediate(switchC, 100); flow.setForwardPath(flowPath); Collection<FlowPath> paths = flowPathRepository.findWithPathSegment(switchA.getSwitchId(), 1, switchC.getSwitchId(), 100); assertThat(paths, Matchers.hasSize(1)); assertThat(paths, containsInAnyOrder(flow.getForwardPath())); }
|
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port) { Map<PathId, FlowPath> result = new HashMap<>(); framedGraph().traverse(g -> g.V() .hasLabel(PathSegmentFrame.FRAME_LABEL) .has(PathSegmentFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(PathSegmentFrame.SRC_PORT_PROPERTY, port) .in(FlowPathFrame.OWNS_SEGMENTS_EDGE) .hasLabel(FlowPathFrame.FRAME_LABEL)) .frameExplicit(FlowPathFrame.class) .forEachRemaining(frame -> result.put(frame.getPathId(), new FlowPath(frame))); framedGraph().traverse(g -> g.V() .hasLabel(PathSegmentFrame.FRAME_LABEL) .has(PathSegmentFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(PathSegmentFrame.DST_PORT_PROPERTY, port) .in(FlowPathFrame.OWNS_SEGMENTS_EDGE) .hasLabel(FlowPathFrame.FRAME_LABEL)) .frameExplicit(FlowPathFrame.class) .forEachRemaining(frame -> result.put(frame.getPathId(), new FlowPath(frame))); return result.values(); } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }
|
@Test public void shouldFindActiveAffectedPaths() { FlowPath flowPath = createTestFlowPathWithIntermediate(switchC, 100); flow.setForwardPath(flowPath); Collection<FlowPath> paths = flowPathRepository.findBySegmentEndpoint( switchC.getSwitchId(), 100); assertThat(paths, containsInAnyOrder(flowPath)); }
|
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Collection<FlowPath> findByFlowId(String flowId) { return framedGraph().traverse(g -> g.V() .hasLabel(FlowPathFrame.FRAME_LABEL) .has(FlowPathFrame.FLOW_ID_PROPERTY, flowId)) .toListExplicit(FlowPathFrame.class).stream() .map(FlowPath::new) .collect(Collectors.toList()); } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }
|
@Test public void shouldFindPathByFlowId() { createTestFlowPath(); Collection<FlowPath> foundPaths = flowPathRepository.findByFlowId(TEST_FLOW_ID); assertThat(foundPaths, hasSize(1)); }
|
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Collection<FlowPath> findBySegmentSwitch(SwitchId switchId) { Map<PathId, FlowPath> result = new HashMap<>(); framedGraph().traverse(g -> g.V() .hasLabel(PathSegmentFrame.FRAME_LABEL) .has(PathSegmentFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .in(FlowPathFrame.OWNS_SEGMENTS_EDGE) .hasLabel(FlowPathFrame.FRAME_LABEL)) .frameExplicit(FlowPathFrame.class) .forEachRemaining(frame -> result.put(frame.getPathId(), new FlowPath(frame))); framedGraph().traverse(g -> g.V() .hasLabel(PathSegmentFrame.FRAME_LABEL) .has(PathSegmentFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .in(FlowPathFrame.OWNS_SEGMENTS_EDGE) .hasLabel(FlowPathFrame.FRAME_LABEL)) .frameExplicit(FlowPathFrame.class) .forEachRemaining(frame -> result.put(frame.getPathId(), new FlowPath(frame))); return result.values(); } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }
|
@Test public void shouldFindPathBySegmentSwitch() { FlowPath flowPath = createTestFlowPathWithIntermediate(switchC, 100); flow.setForwardPath(flowPath); Collection<FlowPath> foundPaths = flowPathRepository.findBySegmentSwitch(switchC.getSwitchId()); assertThat(foundPaths, hasSize(1)); }
|
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId) { String downFlowStatus = FlowStatusConverter.INSTANCE.toGraphProperty(FlowStatus.DOWN); String degragedFlowStatus = FlowStatusConverter.INSTANCE.toGraphProperty(FlowStatus.DEGRADED); Map<PathId, FlowPath> result = new HashMap<>(); framedGraph().traverse(g -> g.V() .hasLabel(PathSegmentFrame.FRAME_LABEL) .has(PathSegmentFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .in(FlowPathFrame.OWNS_SEGMENTS_EDGE) .hasLabel(FlowPathFrame.FRAME_LABEL).as("p") .in(FlowFrame.OWNS_PATHS_EDGE) .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.STATUS_PROPERTY, P.within(downFlowStatus, degragedFlowStatus)) .select("p")) .frameExplicit(FlowPathFrame.class) .forEachRemaining(frame -> result.put(frame.getPathId(), new FlowPath(frame))); framedGraph().traverse(g -> g.V() .hasLabel(PathSegmentFrame.FRAME_LABEL) .has(PathSegmentFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .in(FlowPathFrame.OWNS_SEGMENTS_EDGE) .hasLabel(FlowPathFrame.FRAME_LABEL).as("p") .in(FlowFrame.OWNS_PATHS_EDGE) .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.STATUS_PROPERTY, P.within(downFlowStatus, degragedFlowStatus)) .select("p")) .frameExplicit(FlowPathFrame.class) .forEachRemaining(frame -> result.put(frame.getPathId(), new FlowPath(frame))); return result.values(); } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }
|
@Test public void shouldFindInactivePathBySegmentSwitch() { Flow activeFlow = Flow.builder() .flowId("active flow") .srcSwitch(switchA) .srcPort(1) .destSwitch(switchB) .destPort(2) .status(FlowStatus.UP) .build(); flowRepository.add(activeFlow); FlowPath activeFlowPath = createFlowPath(activeFlow, "active", 100L, 200L, switchA, switchB); activeFlow.addPaths(activeFlowPath); activeFlowPath.getFlow().setStatus(FlowStatus.DOWN); FlowPath expectedFlowPath = createTestFlowPathWithIntermediate(switchC, 100); activeFlow.addPaths(expectedFlowPath); expectedFlowPath.getFlow().setStatus(FlowStatus.DOWN); Collection<FlowPath> foundPaths = flowPathRepository.findInactiveBySegmentSwitch(switchA.getSwitchId()); assertThat(foundPaths, hasSize(1)); FlowPath actualFlowPath = foundPaths.stream().findFirst().orElse(null); assertEquals(expectedFlowPath, actualFlowPath); }
|
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId) { return framedGraph().traverse(g -> g.V() .hasLabel(PathSegmentFrame.FRAME_LABEL) .has(PathSegmentFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .in(FlowPathFrame.OWNS_SEGMENTS_EDGE) .hasLabel(FlowPathFrame.FRAME_LABEL)) .toListExplicit(FlowPathFrame.class).stream() .map(FlowPath::new) .collect(Collectors.toList()); } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }
|
@Test public void shouldFindPathBySegmentDestSwitch() { FlowPath flowPath = createTestFlowPathWithIntermediate(switchC, 100); flow.setForwardPath(flowPath); Collection<FlowPath> foundPaths = flowPathRepository.findBySegmentDestSwitch(switchC.getSwitchId()); assertThat(foundPaths, hasSize(1)); }
@Test public void shouldNotFindPathByWrongSegmentDestSwitch() { FlowPath flowPath = createTestFlowPathWithIntermediate(switchC, 100); flow.setForwardPath(flowPath); Collection<FlowPath> foundPaths = flowPathRepository.findBySegmentDestSwitch(switchA.getSwitchId()); assertThat(foundPaths, Matchers.empty()); }
|
FermaFlowPathRepository extends FermaGenericRepository<FlowPath, FlowPathData, FlowPathFrame> implements FlowPathRepository { @Override public Collection<FlowPath> findActualByFlowIds(Set<String> flowIds) { Set<String> pathIds = new HashSet<>(); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.FLOW_ID_PROPERTY, P.within(flowIds)) .values(FlowFrame.FORWARD_PATH_ID_PROPERTY, FlowFrame.REVERSE_PATH_ID_PROPERTY, FlowFrame.PROTECTED_FORWARD_PATH_ID_PROPERTY, FlowFrame.PROTECTED_REVERSE_PATH_ID_PROPERTY)) .getRawTraversal() .forEachRemaining(pathId -> pathIds.add((String) pathId)); return framedGraph().traverse(g -> g.V() .hasLabel(FlowPathFrame.FRAME_LABEL) .has(FlowPathFrame.PATH_ID_PROPERTY, P.within(pathIds))) .toListExplicit(FlowPathFrame.class).stream() .map(FlowPath::new) .collect(Collectors.toList()); } FermaFlowPathRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowPath> findAll(); @Override Optional<FlowPath> findById(PathId pathId); @Override Optional<FlowPath> findByFlowIdAndCookie(String flowId, FlowSegmentCookie cookie); @Override Collection<FlowPath> findByFlowId(String flowId); @Override Collection<FlowPath> findByFlowGroupId(String flowGroupId); @Override Collection<PathId> findPathIdsByFlowGroupId(String flowGroupId); @Override Collection<FlowPath> findActualByFlowIds(Set<String> flowIds); @Override Collection<FlowPath> findBySrcSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findByEndpointSwitch(SwitchId switchId, boolean includeProtected); @Override Collection<FlowPath> findBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findInactiveBySegmentSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentSwitchWithMultiTable(SwitchId switchId, boolean multiTable); @Override Collection<FlowPath> findWithPathSegment(SwitchId srcSwitchId, int srcPort,
SwitchId dstSwitchId, int dstPort); @Override Collection<FlowPath> findBySegmentDestSwitch(SwitchId switchId); @Override Collection<FlowPath> findBySegmentEndpoint(SwitchId switchId, int port); @Override void updateStatus(PathId pathId, FlowPathStatus pathStatus); @Override long getUsedBandwidthBetweenEndpoints(SwitchId srcSwitchId, int srcPort, SwitchId dstSwitchId, int dstPort); @Override Optional<FlowPath> remove(PathId pathId); }
|
@Test public void shouldFindFlowPathIdsByFlowIds() { Flow flowA = buildTestProtectedFlow(TEST_FLOW_ID_1, switchA, PORT_1, VLAN_1, switchB, PORT_2, VLAN_2); flowRepository.add(flowA); Flow flowB = buildTestFlow(TEST_FLOW_ID_2, switchA, PORT_1, VLAN_2, switchB, PORT_2, 0); flowRepository.add(flowB); Flow flowC = buildTestProtectedFlow(TEST_FLOW_ID_3, switchB, PORT_1, VLAN_1, switchB, PORT_3, VLAN_1); flowRepository.add(flowC); Collection<FlowPath> flowPaths = flowPathRepository.findActualByFlowIds(Sets.newHashSet(TEST_FLOW_ID_1, TEST_FLOW_ID_2)); Collection<PathId> pathIds = flowPaths.stream().map(FlowPath::getPathId).collect(Collectors.toList()); assertEquals(6, pathIds.size()); assertTrue(pathIds.contains(flowA.getForwardPathId())); assertTrue(pathIds.contains(flowA.getReversePathId())); assertTrue(pathIds.contains(flowA.getProtectedForwardPathId())); assertTrue(pathIds.contains(flowA.getProtectedReversePathId())); assertTrue(pathIds.contains(flowB.getForwardPathId())); assertTrue(pathIds.contains(flowB.getReversePathId())); }
|
FermaApplicationRepository extends FermaGenericRepository<ApplicationRule, ApplicationRuleData,
ApplicationRuleFrame> implements ApplicationRepository { @Override public Optional<ApplicationRule> lookupRuleByMatchAndFlow(SwitchId switchId, String flowId, String srcIp, Integer srcPort, String dstIp, Integer dstPort, String proto, String ethType, Long metadata) { List<? extends ApplicationRuleFrame> applicationRuleFrames = framedGraph().traverse(g -> g.V() .hasLabel(ApplicationRuleFrame.FRAME_LABEL) .has(ApplicationRuleFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(ApplicationRuleFrame.FLOW_ID_PROPERTY, flowId) .has(ApplicationRuleFrame.SRC_IP_PROPERTY, srcIp) .has(ApplicationRuleFrame.SRC_PORT_PROPERTY, srcPort) .has(ApplicationRuleFrame.DST_IP_PROPERTY, dstIp) .has(ApplicationRuleFrame.DST_PORT_PROPERTY, dstPort) .has(ApplicationRuleFrame.PROTO_PROPERTY, proto) .has(ApplicationRuleFrame.ETH_TYPE_PROPERTY, ethType) .has(ApplicationRuleFrame.METADATA_PROPERTY, metadata)) .toListExplicit(ApplicationRuleFrame.class); return applicationRuleFrames.isEmpty() ? Optional.empty() : Optional.of(applicationRuleFrames.get(0)) .map(ApplicationRule::new); } FermaApplicationRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Optional<ApplicationRule> lookupRuleByMatchAndFlow(SwitchId switchId, String flowId, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Optional<ApplicationRule> lookupRuleByMatchAndCookie(SwitchId switchId, ExclusionCookie cookie, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Collection<ApplicationRule> findBySwitchId(SwitchId switchId); @Override Collection<ApplicationRule> findByFlowId(String flowId); }
|
@Test public void shouldLookupRuleByMatchAndFlow() { ApplicationRule ruleA = buildRuleA(); ApplicationRule foundRule = applicationRepository.lookupRuleByMatchAndFlow(ruleA.getSwitchId(), ruleA.getFlowId(), ruleA.getSrcIp(), ruleA.getSrcPort(), ruleA.getDstIp(), ruleA.getDstPort(), ruleA.getProto(), ruleA.getEthType(), ruleA.getMetadata()).get(); assertEquals(ruleA, foundRule); }
|
FermaApplicationRepository extends FermaGenericRepository<ApplicationRule, ApplicationRuleData,
ApplicationRuleFrame> implements ApplicationRepository { @Override public Optional<ApplicationRule> lookupRuleByMatchAndCookie(SwitchId switchId, ExclusionCookie cookie, String srcIp, Integer srcPort, String dstIp, Integer dstPort, String proto, String ethType, Long metadata) { List<? extends ApplicationRuleFrame> applicationRuleFrames = framedGraph().traverse(g -> g.V() .hasLabel(ApplicationRuleFrame.FRAME_LABEL) .has(ApplicationRuleFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(ApplicationRuleFrame.COOKIE_PROPERTY, ExclusionCookieConverter.INSTANCE.toGraphProperty(cookie)) .has(ApplicationRuleFrame.SRC_IP_PROPERTY, srcIp) .has(ApplicationRuleFrame.SRC_PORT_PROPERTY, srcPort) .has(ApplicationRuleFrame.DST_IP_PROPERTY, dstIp) .has(ApplicationRuleFrame.DST_PORT_PROPERTY, dstPort) .has(ApplicationRuleFrame.PROTO_PROPERTY, proto) .has(ApplicationRuleFrame.ETH_TYPE_PROPERTY, ethType) .has(ApplicationRuleFrame.METADATA_PROPERTY, metadata)) .toListExplicit(ApplicationRuleFrame.class); return applicationRuleFrames.isEmpty() ? Optional.empty() : Optional.of(applicationRuleFrames.get(0)) .map(ApplicationRule::new); } FermaApplicationRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Optional<ApplicationRule> lookupRuleByMatchAndFlow(SwitchId switchId, String flowId, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Optional<ApplicationRule> lookupRuleByMatchAndCookie(SwitchId switchId, ExclusionCookie cookie, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Collection<ApplicationRule> findBySwitchId(SwitchId switchId); @Override Collection<ApplicationRule> findByFlowId(String flowId); }
|
@Test public void shouldLookupRuleByMatchAndCookie() { ApplicationRule ruleA = buildRuleA(); ApplicationRule foundRule = applicationRepository.lookupRuleByMatchAndCookie(ruleA.getSwitchId(), ruleA.getCookie(), ruleA.getSrcIp(), ruleA.getSrcPort(), ruleA.getDstIp(), ruleA.getDstPort(), ruleA.getProto(), ruleA.getEthType(), ruleA.getMetadata()).get(); assertEquals(ruleA, foundRule); }
|
FermaApplicationRepository extends FermaGenericRepository<ApplicationRule, ApplicationRuleData,
ApplicationRuleFrame> implements ApplicationRepository { @Override public Collection<ApplicationRule> findBySwitchId(SwitchId switchId) { return framedGraph().traverse(g -> g.V() .hasLabel(ApplicationRuleFrame.FRAME_LABEL) .has(ApplicationRuleFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .toListExplicit(ApplicationRuleFrame.class).stream() .map(ApplicationRule::new) .collect(Collectors.toList()); } FermaApplicationRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Optional<ApplicationRule> lookupRuleByMatchAndFlow(SwitchId switchId, String flowId, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Optional<ApplicationRule> lookupRuleByMatchAndCookie(SwitchId switchId, ExclusionCookie cookie, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Collection<ApplicationRule> findBySwitchId(SwitchId switchId); @Override Collection<ApplicationRule> findByFlowId(String flowId); }
|
@Test public void shouldFindBySwitchId() { Collection<ApplicationRule> foundRules = applicationRepository.findBySwitchId(TEST_SWITCH_ID); assertEquals(2, foundRules.size()); assertTrue(foundRules.contains(buildRuleA())); assertTrue(foundRules.contains(buildRuleC())); }
|
FermaApplicationRepository extends FermaGenericRepository<ApplicationRule, ApplicationRuleData,
ApplicationRuleFrame> implements ApplicationRepository { @Override public Collection<ApplicationRule> findByFlowId(String flowId) { return framedGraph().traverse(g -> g.V() .hasLabel(ApplicationRuleFrame.FRAME_LABEL) .has(ApplicationRuleFrame.FLOW_ID_PROPERTY, flowId)) .toListExplicit(ApplicationRuleFrame.class).stream() .map(ApplicationRule::new) .collect(Collectors.toList()); } FermaApplicationRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Optional<ApplicationRule> lookupRuleByMatchAndFlow(SwitchId switchId, String flowId, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Optional<ApplicationRule> lookupRuleByMatchAndCookie(SwitchId switchId, ExclusionCookie cookie, String srcIp,
Integer srcPort, String dstIp, Integer dstPort,
String proto, String ethType, Long metadata); @Override Collection<ApplicationRule> findBySwitchId(SwitchId switchId); @Override Collection<ApplicationRule> findByFlowId(String flowId); }
|
@Test public void shouldFindByFlowId() { Collection<ApplicationRule> foundRules = applicationRepository.findByFlowId(TEST_FLOW_ID); assertEquals(2, foundRules.size()); assertTrue(foundRules.contains(buildRuleA())); assertTrue(foundRules.contains(buildRuleB())); }
|
FermaFlowEventRepository extends FermaGenericRepository<FlowEvent, FlowEventData, FlowEventFrame> implements FlowEventRepository { @Override public List<FlowEvent> findByFlowIdAndTimeFrame(String flowId, Instant timeFrom, Instant timeTo, int maxCount) { return framedGraph().traverse(g -> { GraphTraversal<Vertex, Vertex> traversal = g.V() .hasLabel(FlowEventFrame.FRAME_LABEL) .has(FlowEventFrame.FLOW_ID_PROPERTY, flowId); if (timeFrom != null) { traversal = traversal.has(FlowEventFrame.TIMESTAMP_PROPERTY, P.gte(InstantLongConverter.INSTANCE.toGraphProperty(timeFrom))); } if (timeTo != null) { traversal = traversal.has(FlowEventFrame.TIMESTAMP_PROPERTY, P.lte(InstantLongConverter.INSTANCE.toGraphProperty(timeTo))); } return traversal .order().by(FlowEventFrame.TIMESTAMP_PROPERTY, Order.decr) .limit(maxCount); }).toListExplicit(FlowEventFrame.class).stream() .sorted(Comparator.comparing(FlowEventFrame::getTimestamp)) .map(FlowEvent::new) .collect(Collectors.toList()); } FermaFlowEventRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override boolean existsByTaskId(String taskId); @Override Optional<FlowEvent> findByTaskId(String taskId); @Override List<FlowEvent> findByFlowIdAndTimeFrame(String flowId, Instant timeFrom, Instant timeTo, int maxCount); }
|
@Test public void findByFlowIdAndTimeFrameOrderTest() { List<FlowEvent> expected = new ArrayList<>(); expected.add(buildFlowEvent(FLOW_1, ACTION_1, TIME_1)); expected.add(buildFlowEvent(FLOW_1, ACTION_2, TIME_2)); expected.add(buildFlowEvent(FLOW_1, ACTION_3, TIME_3)); for (FlowEvent flowHistory : expected) { repository.add(flowHistory); } List<FlowEvent> actual = new ArrayList<>(repository.findByFlowIdAndTimeFrame( FLOW_1, TIME_1.minusSeconds(1), TIME_3.plusSeconds(1), 100)); assertEquals(expected, actual); assertTrue(actual.get(0).getTimestamp().isBefore(actual.get(1).getTimestamp())); assertTrue(actual.get(1).getTimestamp().isBefore(actual.get(2).getTimestamp())); }
@Test public void findByFlowIdAndTimeFrameTest() { repository.add(buildFlowEvent(FLOW_1, ACTION_1, TIME_1)); repository.add(buildFlowEvent(FLOW_1, ACTION_2, TIME_2)); repository.add(buildFlowEvent(FLOW_1, ACTION_3, TIME_3)); repository.add(buildFlowEvent(FLOW_1, ACTION_4, TIME_4)); repository.add(buildFlowEvent(FLOW_2, ACTION_5, TIME_3)); List<FlowEvent> events = new ArrayList<>(repository.findByFlowIdAndTimeFrame( FLOW_1, TIME_2, TIME_3, 1000)); assertEquals(2, events.size()); assertEquals(ACTION_2, events.get(0).getAction()); assertEquals(ACTION_3, events.get(1).getAction()); assertTrue(events.get(0).getTimestamp().isBefore(events.get(1).getTimestamp())); }
@Test public void findByFlowIdTimeFrameAndMaxCountTest() { repository.add(buildFlowEvent(FLOW_1, ACTION_1, TIME_1)); repository.add(buildFlowEvent(FLOW_1, ACTION_2, TIME_2)); repository.add(buildFlowEvent(FLOW_1, ACTION_3, TIME_3)); repository.add(buildFlowEvent(FLOW_1, ACTION_4, TIME_4)); repository.add(buildFlowEvent(FLOW_2, ACTION_5, TIME_3)); List<FlowEvent> events = new ArrayList<>(repository.findByFlowIdAndTimeFrame( FLOW_1, TIME_1, TIME_4, 2)); assertEquals(2, events.size()); assertEquals(ACTION_3, events.get(0).getAction()); assertEquals(ACTION_4, events.get(1).getAction()); assertTrue(events.get(0).getTimestamp().isBefore(events.get(1).getTimestamp())); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<Flow> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL)) .toListExplicit(FlowFrame.class).stream() .map(Flow::new) .collect(Collectors.toList()); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldCreateFlow() { createTestFlow(TEST_FLOW_ID, switchA, switchB); Collection<Flow> allFlows = flowRepository.findAll(); Flow foundFlow = allFlows.iterator().next(); assertEquals(switchA.getSwitchId(), foundFlow.getSrcSwitchId()); assertEquals(switchB.getSwitchId(), foundFlow.getDestSwitchId()); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Optional<Flow> findById(String flowId) { List<? extends FlowFrame> flowFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.FLOW_ID_PROPERTY, flowId)) .toListExplicit(FlowFrame.class); return flowFrames.isEmpty() ? Optional.empty() : Optional.of(flowFrames.get(0)) .map(Flow::new); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldNotFindByIdWithEndpoints() { assertFalse(flowRepository.findById("Non_existent").isPresent()); }
@Test public void shouldFindFlowById() { createTestFlow(TEST_FLOW_ID, switchA, switchB); Optional<Flow> foundFlow = flowRepository.findById(TEST_FLOW_ID); assertTrue(foundFlow.isPresent()); }
@Test public void shouldFind2SegmentFlowById() { Switch switchC = createTestSwitch(TEST_SWITCH_C_ID.getId()); createTestFlowWithIntermediate(TEST_FLOW_ID, switchA, switchC, 100, switchB); Optional<Flow> foundFlow = flowRepository.findById(TEST_FLOW_ID); assertTrue(foundFlow.isPresent()); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public boolean exists(String flowId) { try (GraphTraversal<?, ?> traversal = framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.FLOW_ID_PROPERTY, flowId)) .getRawTraversal()) { return traversal.hasNext(); } catch (Exception e) { throw new PersistenceException("Failed to traverse", e); } } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldCheckForExistence() { createTestFlow(TEST_FLOW_ID, switchA, switchB); assertTrue(flowRepository.exists(TEST_FLOW_ID)); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<Flow> findByGroupId(String flowGroupId) { return framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.GROUP_ID_PROPERTY, flowGroupId)) .toListExplicit(FlowFrame.class).stream() .map(Flow::new) .collect(Collectors.toList()); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldFindFlowByGroupId() { Flow flow = createTestFlow(TEST_FLOW_ID, switchA, switchB); flow.setGroupId(TEST_GROUP_ID); List<Flow> foundFlow = Lists.newArrayList(flowRepository.findByGroupId(TEST_GROUP_ID)); assertThat(foundFlow, Matchers.hasSize(1)); assertEquals(Collections.singletonList(flow), foundFlow); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<String> findFlowsIdByGroupId(String flowGroupId) { return framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.GROUP_ID_PROPERTY, flowGroupId) .values(FlowFrame.FLOW_ID_PROPERTY)) .getRawTraversal().toStream() .map(i -> (String) i) .collect(Collectors.toList()); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldFindFlowsIdByGroupId() { Flow flow = createTestFlow(TEST_FLOW_ID, switchA, switchB); flow.setGroupId(TEST_GROUP_ID); List<String> foundFlowId = Lists.newArrayList(flowRepository.findFlowsIdByGroupId(TEST_GROUP_ID)); assertThat(foundFlowId, Matchers.hasSize(1)); assertEquals(Collections.singletonList(TEST_FLOW_ID), foundFlowId); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId) { Map<String, Flow> result = new HashMap<>(); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.SRC_ARP_PROPERTY, true)) .frameExplicit(FlowFrame.class) .forEachRemaining(frame -> result.put(frame.getFlowId(), new Flow(frame))); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.DST_ARP_PROPERTY, true)) .frameExplicit(FlowFrame.class) .forEachRemaining(frame -> result.put(frame.getFlowId(), new Flow(frame))); return result.values(); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldFindFlowByEndpointSwitchWithEnabledArp() { createFlowWithArp(TEST_FLOW_ID, switchA, false, switchB, false); createFlowWithArp(TEST_FLOW_ID_2, switchA, true, switchB, false); createFlowWithArp(TEST_FLOW_ID_3, switchB, false, switchA, true); createFlowWithArp(TEST_FLOW_ID_4, switchA, true, switchA, true); Collection<Flow> foundFlows = flowRepository.findByEndpointSwitchWithEnabledArp(TEST_SWITCH_A_ID); Set<String> foundFlowIds = foundFlows.stream() .map(Flow::getFlowId) .collect(Collectors.toSet()); assertEquals(Sets.newHashSet(TEST_FLOW_ID_2, TEST_FLOW_ID_3, TEST_FLOW_ID_4), foundFlowIds); }
@Test public void shouldFindOneFlowByEndpointSwitchWithEnabledArp() { createFlowWithArp(TEST_FLOW_ID, switchA, true, switchA, true); Collection<Flow> foundFlows = flowRepository.findByEndpointSwitchWithEnabledArp(TEST_SWITCH_A_ID); assertEquals(1, foundFlows.size()); assertEquals(TEST_FLOW_ID, foundFlows.iterator().next().getFlowId()); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<Flow> findByEndpoint(SwitchId switchId, int port) { Map<String, Flow> result = new HashMap<>(); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.SRC_PORT_PROPERTY, port)) .frameExplicit(FlowFrame.class) .forEachRemaining(frame -> result.put(frame.getFlowId(), new Flow(frame))); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.DST_PORT_PROPERTY, port)) .frameExplicit(FlowFrame.class) .forEachRemaining(frame -> result.put(frame.getFlowId(), new Flow(frame))); return result.values(); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldFindFlowByEndpoint() { Flow flow = createTestFlow(TEST_FLOW_ID, switchA, switchB); Collection<Flow> foundFlows = flowRepository.findByEndpoint(TEST_SWITCH_A_ID, 1); Set<String> foundFlowIds = foundFlows.stream().map(foundFlow -> flow.getFlowId()).collect(Collectors.toSet()); assertThat(foundFlowIds, Matchers.hasSize(1)); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan) { List<? extends FlowFrame> flowFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.SRC_PORT_PROPERTY, port) .has(FlowFrame.SRC_VLAN_PROPERTY, vlan)) .toListExplicit(FlowFrame.class); if (!flowFrames.isEmpty()) { return Optional.of(flowFrames.get(0)).map(Flow::new); } flowFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.DST_PORT_PROPERTY, port) .has(FlowFrame.DST_VLAN_PROPERTY, vlan)) .toListExplicit(FlowFrame.class); return flowFrames.isEmpty() ? Optional.empty() : Optional.of(flowFrames.get(0)).map(Flow::new); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldNotFindFlowByEndpointAndVlan() { assertFalse(flowRepository.findByEndpointAndVlan(new SwitchId(1234), 999, 999).isPresent()); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan) { List<? extends FlowFrame> flowFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.SRC_PORT_PROPERTY, inPort) .has(FlowFrame.DST_VLAN_PROPERTY, outVlan)) .toListExplicit(FlowFrame.class); if (!flowFrames.isEmpty()) { return Optional.of(flowFrames.get(0)).map(Flow::new); } flowFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.DST_PORT_PROPERTY, inPort) .has(FlowFrame.SRC_VLAN_PROPERTY, outVlan)) .toListExplicit(FlowFrame.class); return flowFrames.isEmpty() ? Optional.empty() : Optional.of(flowFrames.get(0)).map(Flow::new); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldNotFindOneSwitchFlowBySwitchIdInPortAndOutVlanIfFlowNotExist() { assertFalse(flowRepository.findOneSwitchFlowBySwitchIdInPortAndOutVlan( new SwitchId(1234), 999, 999).isPresent()); }
@Test public void shouldNotFindNotOneSwitchFlowBySwitchIdInPortAndOutVlan() { createTestFlow(TEST_FLOW_ID, switchA, PORT_1, VLAN_1, switchB, PORT_2, VLAN_2); Optional<Flow> flow = flowRepository.findOneSwitchFlowBySwitchIdInPortAndOutVlan( switchA.getSwitchId(), PORT_1, VLAN_2); assertFalse(flow.isPresent()); }
@Test public void shouldFindOnlyOneSwitchFlowBySwitchIdInPortAndOutVlan() { createTestFlow(TEST_FLOW_ID, switchA, PORT_1, VLAN_1, switchA, PORT_2, VLAN_2); createTestFlow(TEST_FLOW_ID_2, switchA, PORT_1, VLAN_3, switchB, PORT_2, VLAN_2); Optional<Flow> flow = flowRepository.findOneSwitchFlowBySwitchIdInPortAndOutVlan( switchA.getSwitchId(), PORT_1, VLAN_2); assertTrue(flow.isPresent()); assertEquals(TEST_FLOW_ID, flow.get().getFlowId()); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port) { Set<String> result = new HashSet<>(); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.SRC_PORT_PROPERTY, port) .has(FlowFrame.SRC_MULTI_TABLE_PROPERTY, true) .values(FlowFrame.FLOW_ID_PROPERTY)) .getRawTraversal().toStream() .forEach(i -> result.add((String) i)); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.DST_PORT_PROPERTY, port) .has(FlowFrame.DST_MULTI_TABLE_PROPERTY, true) .values(FlowFrame.FLOW_ID_PROPERTY)) .getRawTraversal().toStream() .forEach(i -> result.add((String) i)); return result; } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldFindIsByEndpointWithMultiTableSupport() { createTestFlow(TEST_FLOW_ID, switchA, PORT_1, VLAN_1, switchB, PORT_2, VLAN_2, true); createTestFlow(TEST_FLOW_ID_2, switchA, PORT_1, VLAN_2, switchB, PORT_2, 0, true); createTestFlow(TEST_FLOW_ID_3, switchA, PORT_1, VLAN_3, switchB, PORT_2, 0, false); createTestFlow(TEST_FLOW_ID_4, switchB, PORT_1, VLAN_1, switchB, PORT_3, VLAN_1, true); Collection<String> flowIds = flowRepository.findFlowsIdsByEndpointWithMultiTableSupport(switchA.getSwitchId(), PORT_1); assertEquals(2, flowIds.size()); assertTrue(flowIds.contains(TEST_FLOW_ID)); assertTrue(flowIds.contains(TEST_FLOW_ID_2)); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId, int port) { Set<String> result = new HashSet<>(); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.SRC_PORT_PROPERTY, port) .has(FlowFrame.SRC_MULTI_TABLE_PROPERTY, true) .has(FlowFrame.DST_SWITCH_ID_PROPERTY, P.neq(SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .values(FlowFrame.FLOW_ID_PROPERTY)) .getRawTraversal().toStream() .forEach(i -> result.add((String) i)); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.DST_PORT_PROPERTY, port) .has(FlowFrame.DST_MULTI_TABLE_PROPERTY, true) .has(FlowFrame.SRC_SWITCH_ID_PROPERTY, P.neq(SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .values(FlowFrame.FLOW_ID_PROPERTY)) .getRawTraversal().toStream() .forEach(i -> result.add((String) i)); return result; } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldFindFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport() { createTestFlow(TEST_FLOW_ID, switchA, PORT_1, VLAN_1, switchB, PORT_2, VLAN_2, true); createTestFlow(TEST_FLOW_ID_2, switchA, PORT_2, VLAN_2, switchB, PORT_2, 0, true); createTestFlow(TEST_FLOW_ID_3, switchA, PORT_1, VLAN_3, switchB, PORT_2, 0, false); createTestFlow(TEST_FLOW_ID_4, switchA, PORT_1, VLAN_1, switchA, PORT_3, VLAN_1, true); Collection<String> flowIds = flowRepository.findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport( switchA.getSwitchId(), PORT_1); assertEquals(1, flowIds.size()); assertEquals(TEST_FLOW_ID, flowIds.iterator().next()); }
|
PathsService { public List<PathsInfoData> getPaths( SwitchId srcSwitchId, SwitchId dstSwitchId, FlowEncapsulationType requestEncapsulationType, PathComputationStrategy requestPathComputationStrategy) throws RecoverableException, SwitchNotFoundException, UnroutableFlowException { if (Objects.equals(srcSwitchId, dstSwitchId)) { throw new IllegalArgumentException( String.format("Source and destination switch IDs are equal: '%s'", srcSwitchId)); } if (!switchRepository.exists(srcSwitchId)) { throw new SwitchNotFoundException(srcSwitchId); } if (!switchRepository.exists(dstSwitchId)) { throw new SwitchNotFoundException(dstSwitchId); } KildaConfiguration kildaConfiguration = kildaConfigurationRepository.getOrDefault(); FlowEncapsulationType flowEncapsulationType = Optional.ofNullable(requestEncapsulationType) .orElse(kildaConfiguration.getFlowEncapsulationType()); PathComputationStrategy pathComputationStrategy = Optional.ofNullable(requestPathComputationStrategy) .orElse(kildaConfiguration.getPathComputationStrategy()); List<Path> flowPaths = pathComputer.getNPaths(srcSwitchId, dstSwitchId, MAX_PATH_COUNT, flowEncapsulationType, pathComputationStrategy); return flowPaths.stream().map(PathMapper.INSTANCE::map) .map(path -> PathsInfoData.builder().path(path).build()) .collect(Collectors.toList()); } PathsService(RepositoryFactory repositoryFactory, PathComputerConfig pathComputerConfig); List<PathsInfoData> getPaths(
SwitchId srcSwitchId, SwitchId dstSwitchId, FlowEncapsulationType requestEncapsulationType,
PathComputationStrategy requestPathComputationStrategy); static final int MAX_PATH_COUNT; }
|
@Test public void findNPathsByTransitVlanAndCost() throws SwitchNotFoundException, RecoverableException, UnroutableFlowException { List<PathsInfoData> paths = pathsService.getPaths(SWITCH_ID_1, SWITCH_ID_2, TRANSIT_VLAN, COST); assertEquals(MAX_PATH_COUNT, paths.size()); for (PathsInfoData path : paths) { assertEquals(3, path.getPath().getNodes().size()); assertEquals(SWITCH_ID_1, path.getPath().getNodes().get(0).getSwitchId()); assertEquals(SWITCH_ID_2, path.getPath().getNodes().get(2).getSwitchId()); } for (int i = 0; i < paths.size(); i++) { assertTrue(paths.get(i).getPath().getNodes().get(1).getSwitchId().getId() <= MAX_PATH_COUNT + 3); if (i > 0) { assertTrue(paths.get(i - 1).getPath().getBandwidth() >= paths.get(i).getPath().getBandwidth()); } } }
@Test public void findNPathsByTransitVlanAndLatency() throws SwitchNotFoundException, RecoverableException, UnroutableFlowException { List<PathsInfoData> paths = pathsService.getPaths(SWITCH_ID_1, SWITCH_ID_2, TRANSIT_VLAN, LATENCY); assertTransitVlanAndLatencyPaths(paths); }
@Test public void findNPathsByVxlanAndCost() throws SwitchNotFoundException, RecoverableException, UnroutableFlowException { List<PathsInfoData> paths = pathsService.getPaths(SWITCH_ID_1, SWITCH_ID_2, VXLAN, COST); assertVxlanAndCostPathes(paths); }
@Test public void findNPathsByTransitVlanAndDefaultStrategy() throws SwitchNotFoundException, RecoverableException, UnroutableFlowException { kildaConfigurationRepository.find().ifPresent(config -> { config.setPathComputationStrategy(LATENCY); }); List<PathsInfoData> paths = pathsService.getPaths(SWITCH_ID_1, SWITCH_ID_2, TRANSIT_VLAN, null); assertTransitVlanAndLatencyPaths(paths); }
@Test public void findNPathsByDefaultEncapsulationAndCost() throws SwitchNotFoundException, RecoverableException, UnroutableFlowException { kildaConfigurationRepository.find().ifPresent(config -> { config.setFlowEncapsulationType(VXLAN); }); List<PathsInfoData> paths = pathsService.getPaths(SWITCH_ID_1, SWITCH_ID_2, null, COST); assertVxlanAndCostPathes(paths); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<Flow> findByEndpointSwitch(SwitchId switchId) { Map<String, Flow> result = new HashMap<>(); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .frameExplicit(FlowFrame.class) .forEachRemaining(frame -> result.put(frame.getFlowId(), new Flow(frame))); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .frameExplicit(FlowFrame.class) .forEachRemaining(frame -> result.put(frame.getFlowId(), new Flow(frame))); return result.values(); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldFindFlowBySwitchEndpoint() { Flow flow = createTestFlow(TEST_FLOW_ID, switchA, switchB); Collection<Flow> foundFlows = flowRepository.findByEndpointSwitch(TEST_SWITCH_A_ID); Set<String> foundFlowIds = foundFlows.stream().map(foundFlow -> flow.getFlowId()).collect(Collectors.toSet()); assertThat(foundFlowIds, Matchers.hasSize(1)); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId) { Map<String, Flow> result = new HashMap<>(); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.SRC_MULTI_TABLE_PROPERTY, true)) .frameExplicit(FlowFrame.class) .forEachRemaining(frame -> result.put(frame.getFlowId(), new Flow(frame))); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.DST_MULTI_TABLE_PROPERTY, true)) .frameExplicit(FlowFrame.class) .forEachRemaining(frame -> result.put(frame.getFlowId(), new Flow(frame))); return result.values(); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldFindFlowBySwitchEndpointWithMultiTable() { Flow firstFlow = createTestFlow(TEST_FLOW_ID, switchA, switchB); firstFlow.setSrcWithMultiTable(true); Flow secondFlow = createTestFlow(TEST_FLOW_ID_2, switchA, switchB); secondFlow.setSrcWithMultiTable(false); Collection<Flow> foundFlows = flowRepository.findByEndpointSwitchWithMultiTableSupport(TEST_SWITCH_A_ID); Set<String> foundFlowIds = foundFlows.stream().map(Flow::getFlowId).collect(Collectors.toSet()); assertEquals(Collections.singleton(firstFlow.getFlowId()), foundFlowIds); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId) { Map<String, Flow> result = new HashMap<>(); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.SRC_LLDP_PROPERTY, true)) .frameExplicit(FlowFrame.class) .forEachRemaining(frame -> result.put(frame.getFlowId(), new Flow(frame))); framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.DST_LLDP_PROPERTY, true)) .frameExplicit(FlowFrame.class) .forEachRemaining(frame -> result.put(frame.getFlowId(), new Flow(frame))); return result.values(); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldFindFlowByEndpointSwitchWithEnabledLldp() { createFlowWithLldp(TEST_FLOW_ID, switchA, false, switchB, false); createFlowWithLldp(TEST_FLOW_ID_2, switchA, true, switchB, false); createFlowWithLldp(TEST_FLOW_ID_3, switchB, false, switchA, true); createFlowWithLldp(TEST_FLOW_ID_4, switchA, true, switchA, true); Collection<Flow> foundFlows = flowRepository.findByEndpointSwitchWithEnabledLldp(TEST_SWITCH_A_ID); Set<String> foundFlowIds = foundFlows.stream() .map(Flow::getFlowId) .collect(Collectors.toSet()); assertEquals(Sets.newHashSet(TEST_FLOW_ID_2, TEST_FLOW_ID_3, TEST_FLOW_ID_4), foundFlowIds); }
@Test public void shouldFindOneFlowByEndpointSwitchWithEnabledLldp() { createFlowWithLldp(TEST_FLOW_ID, switchA, true, switchA, true); Collection<Flow> foundFlows = flowRepository.findByEndpointSwitchWithEnabledLldp(TEST_SWITCH_A_ID); assertEquals(1, foundFlows.size()); assertEquals(TEST_FLOW_ID, foundFlows.iterator().next().getFlowId()); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<Flow> findOneSwitchFlows(SwitchId switchId) { return framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.SRC_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(FlowFrame.DST_SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .toListExplicit(FlowFrame.class).stream() .map(Flow::new) .collect(Collectors.toList()); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldFindOneFlowByEndpoint() { Flow flow1 = createTestFlow(TEST_FLOW_ID, switchA, switchA); flow1.setSrcPort(1); flow1.setDestPort(2); Flow flow2 = createTestFlow(TEST_FLOW_ID_2, switchB, switchB); flow2.setSrcPort(1); flow2.setDestPort(2); createTestFlow(TEST_FLOW_ID_3, switchA, switchB); Collection<Flow> foundFlows = flowRepository.findOneSwitchFlows(switchA.getSwitchId()); assertEquals(1, foundFlows.size()); assertEquals(TEST_FLOW_ID, foundFlows.iterator().next().getFlowId()); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<Flow> findInactiveFlows() { String downFlowStatus = FlowStatusConverter.INSTANCE.toGraphProperty(FlowStatus.DOWN); String degragedFlowStatus = FlowStatusConverter.INSTANCE.toGraphProperty(FlowStatus.DEGRADED); return framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.STATUS_PROPERTY, P.within(downFlowStatus, degragedFlowStatus))) .toListExplicit(FlowFrame.class).stream() .map(Flow::new) .collect(Collectors.toList()); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldFindDownFlowIdsByEndpoint() { Flow flow = createTestFlow(TEST_FLOW_ID, switchA, switchB); flow.setStatus(FlowStatus.DOWN); Collection<Flow> foundFlows = flowRepository.findInactiveFlows(); assertThat(foundFlows, Matchers.hasSize(1)); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Optional<String> getOrCreateFlowGroupId(String flowId) { return transactionManager.doInTransaction(() -> findById(flowId) .map(diverseFlow -> { if (diverseFlow.getGroupId() == null) { String groupId = UUID.randomUUID().toString(); diverseFlow.setGroupId(groupId); } return diverseFlow.getGroupId(); })); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldGetFlowGroupIdForFlow() { Flow flow = createTestFlow(TEST_FLOW_ID, switchA, switchB); flow.setGroupId(TEST_GROUP_ID); Optional<String> groupOptional = flowRepository.getOrCreateFlowGroupId(TEST_FLOW_ID); assertTrue(groupOptional.isPresent()); assertEquals(TEST_GROUP_ID, groupOptional.get()); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public long computeFlowsBandwidthSum(Set<String> flowIds) { try (GraphTraversal<?, ?> traversal = framedGraph().traverse(g -> g.V() .hasLabel(FlowFrame.FRAME_LABEL) .has(FlowFrame.FLOW_ID_PROPERTY, P.within(flowIds)) .values(FlowFrame.BANDWIDTH_PROPERTY).sum()) .getRawTraversal()) { return traversal.tryNext() .filter(n -> !(n instanceof Double && ((Double) n).isNaN())) .map(l -> (Long) l) .orElse(0L); } catch (Exception e) { throw new PersistenceException("Failed to traverse", e); } } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldComputeSumOfFlowsBandwidth() { long firstFlowBandwidth = 100000L; long secondFlowBandwidth = 500000L; Flow firstFlow = createTestFlow(TEST_FLOW_ID, switchA, switchB); firstFlow.setBandwidth(firstFlowBandwidth); Flow secondFlow = createTestFlow(TEST_FLOW_ID_2, switchA, switchB); secondFlow.setBandwidth(secondFlowBandwidth); long foundBandwidth = flowRepository.computeFlowsBandwidthSum(Sets.newHashSet(TEST_FLOW_ID, TEST_FLOW_ID_2)); assertEquals(firstFlowBandwidth + secondFlowBandwidth, foundBandwidth); }
|
FermaFlowRepository extends FermaGenericRepository<Flow, FlowData, FlowFrame> implements FlowRepository { @Override public Collection<Flow> findByFlowFilter(FlowFilter flowFilter) { return framedGraph().traverse(g -> { GraphTraversal<Vertex, Vertex> traversal = g.V() .hasLabel(FlowFrame.FRAME_LABEL); if (flowFilter.getFlowStatus() != null) { traversal = traversal.has(FlowFrame.STATUS_PROPERTY, FlowStatusConverter.INSTANCE.toGraphProperty(flowFilter.getFlowStatus())); } return traversal; }).toListExplicit(FlowFrame.class).stream() .map(Flow::new) .collect(Collectors.toList()); } FermaFlowRepository(FramedGraphFactory<?> graphFactory, FlowPathRepository flowPathRepository,
TransactionManager transactionManager); @Override long countFlows(); @Override Collection<Flow> findAll(); @Override boolean exists(String flowId); @Override Optional<Flow> findById(String flowId); @Override Collection<Flow> findByGroupId(String flowGroupId); @Override Collection<String> findFlowsIdByGroupId(String flowGroupId); @Override Collection<Flow> findWithPeriodicPingsEnabled(); @Override Collection<Flow> findByEndpoint(SwitchId switchId, int port); @Override Optional<Flow> findByEndpointAndVlan(SwitchId switchId, int port, int vlan); @Override Optional<Flow> findOneSwitchFlowBySwitchIdInPortAndOutVlan(SwitchId switchId, int inPort, int outVlan); @Override Collection<Flow> findOneSwitchFlows(SwitchId switchId); @Override Collection<Flow> findByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowsIdsByEndpointWithMultiTableSupport(SwitchId switchId, int port); @Override Collection<String> findFlowIdsForMultiSwitchFlowsByEndpointWithMultiTableSupport(SwitchId switchId,
int port); @Override Collection<Flow> findByEndpointSwitch(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithMultiTableSupport(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledLldp(SwitchId switchId); @Override Collection<Flow> findByEndpointSwitchWithEnabledArp(SwitchId switchId); @Override Collection<Flow> findInactiveFlows(); @Override Collection<Flow> findByFlowFilter(FlowFilter flowFilter); @Override Optional<String> getOrCreateFlowGroupId(String flowId); @Override void updateStatus(@NonNull String flowId, @NonNull FlowStatus flowStatus); @Override void updateStatus(String flowId, FlowStatus flowStatus, String flowStatusInfo); @Override void updateStatusInfo(String flowId, String flowStatusInfo); @Override @TransactionRequired void updateStatusSafe(Flow flow, FlowStatus flowStatus, String flowStatusInfo); @Override long computeFlowsBandwidthSum(Set<String> flowIds); @Override Optional<Flow> remove(String flowId); }
|
@Test public void shouldGetAllDownFlows() { Flow flowA = createTestFlow(TEST_FLOW_ID, switchA, switchB); flowA.setStatus(FlowStatus.DOWN); Flow flowB = createTestFlow(TEST_FLOW_ID_2, switchA, switchB); flowB.setStatus(FlowStatus.DOWN); createTestFlow(TEST_FLOW_ID_3, switchA, switchB); Collection<String> foundDownFlows = flowRepository.findByFlowFilter(FlowFilter.builder().flowStatus(FlowStatus.DOWN).build()).stream() .map(Flow::getFlowId) .collect(Collectors.toList()); assertEquals(2, foundDownFlows.size()); assertTrue(foundDownFlows.contains(TEST_FLOW_ID)); assertTrue(foundDownFlows.contains(TEST_FLOW_ID_2)); Collection<String> foundFlows = flowRepository.findByFlowFilter(FlowFilter.builder().build()).stream() .map(Flow::getFlowId) .collect(Collectors.toList()); assertEquals(3, foundFlows.size()); }
|
FermaSwitchRepository extends FermaGenericRepository<Switch, SwitchData, SwitchFrame> implements SwitchRepository { @Override public Collection<Switch> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(SwitchFrame.FRAME_LABEL)) .toListExplicit(SwitchFrame.class).stream() .map(Switch::new) .collect(Collectors.toList()); } FermaSwitchRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<Switch> findAll(); @Override boolean exists(SwitchId switchId); @Override Collection<Switch> findActive(); @Override Optional<Switch> findById(SwitchId switchId); @Override Collection<Switch> findSwitchesInFlowPathByFlowId(String flowId); @Override @TransactionRequired boolean removeIfNoDependant(Switch entity); }
|
@Test public void shouldCreateSwitch() { switchRepository.add(Switch.builder() .switchId(TEST_SWITCH_ID_A) .description("Some description") .build()); assertEquals(1, switchRepository.findAll().size()); }
@Test public void shouldDeleteSwitch() { Switch origSwitch = Switch.builder() .switchId(TEST_SWITCH_ID_A) .description("Some description") .build(); switchRepository.add(origSwitch); transactionManager.doInTransaction(() -> switchRepository.remove(origSwitch)); assertEquals(0, switchRepository.findAll().size()); }
|
FermaSwitchRepository extends FermaGenericRepository<Switch, SwitchData, SwitchFrame> implements SwitchRepository { @Override public Collection<Switch> findActive() { return framedGraph().traverse(g -> g.V() .hasLabel(SwitchFrame.FRAME_LABEL) .has(SwitchFrame.STATUS_PROPERTY, SwitchStatusConverter.INSTANCE.toGraphProperty(SwitchStatus.ACTIVE))) .toListExplicit(SwitchFrame.class).stream() .map(Switch::new) .collect(Collectors.toList()); } FermaSwitchRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<Switch> findAll(); @Override boolean exists(SwitchId switchId); @Override Collection<Switch> findActive(); @Override Optional<Switch> findById(SwitchId switchId); @Override Collection<Switch> findSwitchesInFlowPathByFlowId(String flowId); @Override @TransactionRequired boolean removeIfNoDependant(Switch entity); }
|
@Test public void shouldFindActive() { Switch activeSwitch = Switch.builder().switchId(TEST_SWITCH_ID_A) .status(SwitchStatus.ACTIVE).build(); Switch inactiveSwitch = Switch.builder().switchId(TEST_SWITCH_ID_B) .status(SwitchStatus.INACTIVE).build(); switchRepository.add(activeSwitch); switchRepository.add(inactiveSwitch); Collection<Switch> switches = switchRepository.findActive(); assertEquals(1, switches.size()); assertEquals(TEST_SWITCH_ID_A, switches.iterator().next().getSwitchId()); }
|
FermaSwitchRepository extends FermaGenericRepository<Switch, SwitchData, SwitchFrame> implements SwitchRepository { @Override public Optional<Switch> findById(SwitchId switchId) { return SwitchFrame.load(framedGraph(), SwitchIdConverter.INSTANCE.toGraphProperty(switchId)).map(Switch::new); } FermaSwitchRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<Switch> findAll(); @Override boolean exists(SwitchId switchId); @Override Collection<Switch> findActive(); @Override Optional<Switch> findById(SwitchId switchId); @Override Collection<Switch> findSwitchesInFlowPathByFlowId(String flowId); @Override @TransactionRequired boolean removeIfNoDependant(Switch entity); }
|
@Test public void shouldFindSwitchById() { Switch origSwitch = Switch.builder() .switchId(TEST_SWITCH_ID_A) .description("Some description") .build(); switchRepository.add(origSwitch); Switch foundSwitch = switchRepository.findById(TEST_SWITCH_ID_A).get(); assertEquals(origSwitch.getDescription(), foundSwitch.getDescription()); }
|
FermaSwitchRepository extends FermaGenericRepository<Switch, SwitchData, SwitchFrame> implements SwitchRepository { @Override public Collection<Switch> findSwitchesInFlowPathByFlowId(String flowId) { List<? extends FlowPathFrame> flowPathFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowPathFrame.FRAME_LABEL) .has(FlowPathFrame.FLOW_ID_PROPERTY, flowId)) .toListExplicit(FlowPathFrame.class); if (flowPathFrames.isEmpty()) { return emptyList(); } Map<SwitchId, Switch> result = new HashMap<>(); flowPathFrames.forEach(flowPath -> { Stream.of(flowPath.getSrcSwitch(), flowPath.getDestSwitch()) .forEach(sw -> result.put(sw.getSwitchId(), sw)); flowPath.getSegments().forEach(pathSegment -> { Stream.of(pathSegment.getSrcSwitch(), pathSegment.getDestSwitch()) .forEach(sw -> result.put(sw.getSwitchId(), sw)); }); }); return result.values(); } FermaSwitchRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<Switch> findAll(); @Override boolean exists(SwitchId switchId); @Override Collection<Switch> findActive(); @Override Optional<Switch> findById(SwitchId switchId); @Override Collection<Switch> findSwitchesInFlowPathByFlowId(String flowId); @Override @TransactionRequired boolean removeIfNoDependant(Switch entity); }
|
@Test public void shouldFindSwitchesByFlowId() { createTwoFlows(); Collection<SwitchId> switches = switchRepository.findSwitchesInFlowPathByFlowId(TEST_FLOW_ID_A).stream() .map(Switch::getSwitchId) .collect(Collectors.toList()); assertEquals(2, switches.size()); assertTrue(switches.contains(TEST_SWITCH_ID_A)); assertTrue(switches.contains(TEST_SWITCH_ID_B)); assertFalse(switches.contains(TEST_SWITCH_ID_C)); }
@Test public void shouldFindSwitchOfOneSwitchFlowByFlowId() { createOneSwitchFlow(); Collection<SwitchId> switches = switchRepository.findSwitchesInFlowPathByFlowId(TEST_FLOW_ID_A).stream() .map(Switch::getSwitchId) .collect(Collectors.toList()); assertEquals(1, switches.size()); assertTrue(switches.contains(TEST_SWITCH_ID_A)); }
|
FermaTransitVlanRepository extends FermaGenericRepository<TransitVlan, TransitVlanData, TransitVlanFrame> implements TransitVlanRepository { @Override public Collection<TransitVlan> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(TransitVlanFrame.FRAME_LABEL)) .toListExplicit(TransitVlanFrame.class).stream() .map(TransitVlan::new) .collect(Collectors.toList()); } FermaTransitVlanRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<TransitVlan> findAll(); @Override Collection<TransitVlan> findByPathId(PathId pathId, PathId oppositePathId); @Override Optional<TransitVlan> findByPathId(PathId pathId); @Override boolean exists(int vlan); @Override Optional<TransitVlan> findByVlan(int vlan); @Override Optional<Integer> findFirstUnassignedVlan(int lowestTransitVlan, int highestTransitVlan); }
|
@Test public void shouldCreateTransitVlan() { TransitVlan vlan = createTransitVlan(); Collection<TransitVlan> allVlans = transitVlanRepository.findAll(); TransitVlan foundVlan = allVlans.iterator().next(); assertEquals(vlan.getVlan(), foundVlan.getVlan()); assertEquals(TEST_FLOW_ID, foundVlan.getFlowId()); }
@Test public void shouldDeleteTransitVlan() { TransitVlan vlan = createTransitVlan(); transactionManager.doInTransaction(() -> transitVlanRepository.remove(vlan)); assertEquals(0, transitVlanRepository.findAll().size()); }
@Test public void shouldDeleteFoundTransitVlan() { createTransitVlan(); Collection<TransitVlan> allVlans = transitVlanRepository.findAll(); TransitVlan foundVlan = allVlans.iterator().next(); transactionManager.doInTransaction(() -> transitVlanRepository.remove(foundVlan)); assertEquals(0, transitVlanRepository.findAll().size()); }
|
FermaTransitVlanRepository extends FermaGenericRepository<TransitVlan, TransitVlanData, TransitVlanFrame> implements TransitVlanRepository { @Override public Optional<TransitVlan> findByVlan(int vlan) { List<? extends TransitVlanFrame> transitVlanFrames = framedGraph().traverse(g -> g.V() .hasLabel(TransitVlanFrame.FRAME_LABEL) .has(TransitVlanFrame.VLAN_PROPERTY, vlan)) .toListExplicit(TransitVlanFrame.class); return transitVlanFrames.isEmpty() ? Optional.empty() : Optional.of(transitVlanFrames.get(0)) .map(TransitVlan::new); } FermaTransitVlanRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<TransitVlan> findAll(); @Override Collection<TransitVlan> findByPathId(PathId pathId, PathId oppositePathId); @Override Optional<TransitVlan> findByPathId(PathId pathId); @Override boolean exists(int vlan); @Override Optional<TransitVlan> findByVlan(int vlan); @Override Optional<Integer> findFirstUnassignedVlan(int lowestTransitVlan, int highestTransitVlan); }
|
@Test public void shouldFindTransitVlan() { TransitVlan vlan = createTransitVlan(); vlan.setVlan(VLAN); Optional<TransitVlan> foundVlan = transitVlanRepository.findByVlan(VLAN); assertTrue(foundVlan.isPresent()); assertEquals(vlan.getVlan(), foundVlan.get().getVlan()); assertEquals(vlan.getFlowId(), foundVlan.get().getFlowId()); assertEquals(vlan.getPathId(), foundVlan.get().getPathId()); }
@Test public void shouldSelectNextInOrderResourceWhenFindUnassignedTransitVlan() { int first = findUnassignedTransitVlanAndCreate("flow_1"); assertEquals(5, first); int second = findUnassignedTransitVlanAndCreate("flow_2"); assertEquals(6, second); int third = findUnassignedTransitVlanAndCreate("flow_3"); assertEquals(7, third); transactionManager.doInTransaction(() -> transitVlanRepository.findByVlan(second).ifPresent(transitVlanRepository::remove)); int fourth = findUnassignedTransitVlanAndCreate("flow_4"); assertEquals(6, fourth); int fifth = findUnassignedTransitVlanAndCreate("flow_5"); assertEquals(8, fifth); }
|
FermaVxlanRepository extends FermaGenericRepository<Vxlan, VxlanData, VxlanFrame> implements VxlanRepository { @Override public Collection<Vxlan> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(VxlanFrame.FRAME_LABEL)) .toListExplicit(VxlanFrame.class).stream() .map(Vxlan::new) .collect(Collectors.toList()); } FermaVxlanRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<Vxlan> findAll(); @Override Collection<Vxlan> findByPathId(PathId pathId, PathId oppositePathId); @Override boolean exists(int vxlan); @Override Optional<Integer> findFirstUnassignedVxlan(int lowestVxlan, int highestVxlan); }
|
@Test public void shouldCreateVxlan() { Vxlan vxlan = createVxlan(); Collection<Vxlan> allVxlans = vxlanRepository.findAll(); Vxlan foundVxlan = allVxlans.iterator().next(); assertEquals(vxlan.getVni(), foundVxlan.getVni()); assertEquals(TEST_FLOW_ID, foundVxlan.getFlowId()); }
@Test public void shouldDeleteVxlan() { Vxlan vxlan = createVxlan(); transactionManager.doInTransaction(() -> vxlanRepository.remove(vxlan)); assertEquals(0, vxlanRepository.findAll().size()); }
@Test public void shouldDeleteFoundVxlan() { createVxlan(); transactionManager.doInTransaction(() -> { Collection<Vxlan> allVxlans = vxlanRepository.findAll(); Vxlan foundVxlan = allVxlans.iterator().next(); vxlanRepository.remove(foundVxlan); }); assertEquals(0, vxlanRepository.findAll().size()); }
@Test public void shouldSelectNextInOrderResourceWhenFindUnassignedVxlan() { int first = findUnassignedVxlanAndCreate("flow_1"); assertEquals(5, first); int second = findUnassignedVxlanAndCreate("flow_2"); assertEquals(6, second); int third = findUnassignedVxlanAndCreate("flow_3"); assertEquals(7, third); transactionManager.doInTransaction(() -> { vxlanRepository.findAll().stream() .filter(vxlan -> vxlan.getVni() == second) .forEach(vxlanRepository::remove); }); int fourth = findUnassignedVxlanAndCreate("flow_4"); assertEquals(6, fourth); int fifth = findUnassignedVxlanAndCreate("flow_5"); assertEquals(8, fifth); }
|
FermaFlowMeterRepository extends FermaGenericRepository<FlowMeter, FlowMeterData, FlowMeterFrame> implements FlowMeterRepository { @Override public Collection<FlowMeter> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(FlowMeterFrame.FRAME_LABEL)) .toListExplicit(FlowMeterFrame.class).stream() .map(FlowMeter::new) .collect(Collectors.toList()); } FermaFlowMeterRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowMeter> findAll(); @Override Optional<FlowMeter> findByPathId(PathId pathId); @Override boolean exists(SwitchId switchId, MeterId meterId); @Override Optional<MeterId> findFirstUnassignedMeter(SwitchId switchId, MeterId lowestMeterId,
MeterId highestMeterId); }
|
@Test public void shouldCreateFlowMeter() { createFlowMeter(); Collection<FlowMeter> allMeters = flowMeterRepository.findAll(); FlowMeter foundMeter = allMeters.iterator().next(); assertEquals(theSwitch.getSwitchId(), foundMeter.getSwitchId()); assertEquals(TEST_FLOW_ID, foundMeter.getFlowId()); }
@Test public void shouldDeleteFlowMeter() { FlowMeter meter = createFlowMeter(); transactionManager.doInTransaction(() -> flowMeterRepository.remove(meter)); assertEquals(0, flowMeterRepository.findAll().size()); }
@Test public void shouldDeleteFoundFlowMeter() { createFlowMeter(); transactionManager.doInTransaction(() -> { Collection<FlowMeter> allMeters = flowMeterRepository.findAll(); FlowMeter foundMeter = allMeters.iterator().next(); flowMeterRepository.remove(foundMeter); }); assertEquals(0, flowMeterRepository.findAll().size()); }
@Test public void shouldSelectNextInOrderResourceWhenFindUnassignedMeter() { long first = findUnassignedMeterAndCreate("flow_1"); assertEquals(5, first); long second = findUnassignedMeterAndCreate("flow_2"); assertEquals(6, second); long third = findUnassignedMeterAndCreate("flow_3"); assertEquals(7, third); transactionManager.doInTransaction(() -> { flowMeterRepository.findAll().stream() .filter(flowMeter -> flowMeter.getMeterId().getValue() == second) .forEach(flowMeterRepository::remove); }); long fourth = findUnassignedMeterAndCreate("flow_4"); assertEquals(6, fourth); long fifth = findUnassignedMeterAndCreate("flow_5"); assertEquals(8, fifth); }
|
FermaFlowMeterRepository extends FermaGenericRepository<FlowMeter, FlowMeterData, FlowMeterFrame> implements FlowMeterRepository { @Override public Optional<FlowMeter> findByPathId(PathId pathId) { List<? extends FlowMeterFrame> flowMeterFrames = framedGraph().traverse(g -> g.V() .hasLabel(FlowMeterFrame.FRAME_LABEL) .has(FlowMeterFrame.PATH_ID_PROPERTY, PathIdConverter.INSTANCE.toGraphProperty(pathId))) .toListExplicit(FlowMeterFrame.class); return flowMeterFrames.isEmpty() ? Optional.empty() : Optional.of(flowMeterFrames.get(0)) .map(FlowMeter::new); } FermaFlowMeterRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<FlowMeter> findAll(); @Override Optional<FlowMeter> findByPathId(PathId pathId); @Override boolean exists(SwitchId switchId, MeterId meterId); @Override Optional<MeterId> findFirstUnassignedMeter(SwitchId switchId, MeterId lowestMeterId,
MeterId highestMeterId); }
|
@Ignore("InMemoryGraph doesn't enforce constraint") @Test(expected = PersistenceException.class) public void shouldNotGetMoreThanOneMetersForPath() { createFlowMeter(1, new PathId(TEST_PATH_ID)); createFlowMeter(2, new PathId(TEST_PATH_ID)); flowMeterRepository.findByPathId(new PathId(TEST_PATH_ID)); }
@Test public void shouldGetZeroMetersForPath() { Optional<FlowMeter> meters = flowMeterRepository.findByPathId(new PathId(TEST_PATH_ID)); assertFalse(meters.isPresent()); }
|
FermaSwitchConnectedDevicesRepository extends FermaGenericRepository<SwitchConnectedDevice, SwitchConnectedDeviceData, SwitchConnectedDeviceFrame> implements SwitchConnectedDeviceRepository { @Override public Collection<SwitchConnectedDevice> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(SwitchConnectedDeviceFrame.FRAME_LABEL)) .toListExplicit(SwitchConnectedDeviceFrame.class).stream() .map(SwitchConnectedDevice::new) .collect(Collectors.toList()); } FermaSwitchConnectedDevicesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<SwitchConnectedDevice> findAll(); @Override Collection<SwitchConnectedDevice> findBySwitchId(SwitchId switchId); @Override Collection<SwitchConnectedDevice> findByFlowId(String flowId); @Override Optional<SwitchConnectedDevice> findLldpByUniqueFieldCombination(
SwitchId switchId, int portNumber, int vlan, String macAddress, String chassisId, String portId); @Override Optional<SwitchConnectedDevice> findArpByUniqueFieldCombination(
SwitchId switchId, int portNumber, int vlan, String macAddress, String ipAddress); }
|
@Test public void createConnectedDeviceTest() { connectedDeviceRepository.add(lldpConnectedDeviceA); Collection<SwitchConnectedDevice> devices = connectedDeviceRepository.findAll(); assertEquals(lldpConnectedDeviceA, devices.iterator().next()); assertNotNull(devices.iterator().next().getSwitchObj()); }
@Test public void deleteConnectedDeviceTest() { transactionManager.doInTransaction(() -> { connectedDeviceRepository.add(lldpConnectedDeviceA); connectedDeviceRepository.add(lldpConnectedDeviceB); assertEquals(2, connectedDeviceRepository.findAll().size()); connectedDeviceRepository.remove(lldpConnectedDeviceA); assertEquals(1, connectedDeviceRepository.findAll().size()); assertEquals(lldpConnectedDeviceB, connectedDeviceRepository.findAll().iterator().next()); connectedDeviceRepository.remove(lldpConnectedDeviceB); assertEquals(0, connectedDeviceRepository.findAll().size()); }); }
|
FermaSwitchConnectedDevicesRepository extends FermaGenericRepository<SwitchConnectedDevice, SwitchConnectedDeviceData, SwitchConnectedDeviceFrame> implements SwitchConnectedDeviceRepository { @Override public Collection<SwitchConnectedDevice> findBySwitchId(SwitchId switchId) { return framedGraph().traverse(g -> g.V() .hasLabel(SwitchConnectedDeviceFrame.FRAME_LABEL) .has(SwitchConnectedDeviceFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .toListExplicit(SwitchConnectedDeviceFrame.class).stream() .map(SwitchConnectedDevice::new) .collect(Collectors.toList()); } FermaSwitchConnectedDevicesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<SwitchConnectedDevice> findAll(); @Override Collection<SwitchConnectedDevice> findBySwitchId(SwitchId switchId); @Override Collection<SwitchConnectedDevice> findByFlowId(String flowId); @Override Optional<SwitchConnectedDevice> findLldpByUniqueFieldCombination(
SwitchId switchId, int portNumber, int vlan, String macAddress, String chassisId, String portId); @Override Optional<SwitchConnectedDevice> findArpByUniqueFieldCombination(
SwitchId switchId, int portNumber, int vlan, String macAddress, String ipAddress); }
|
@Test public void findBySwitchIdTest() { connectedDeviceRepository.add(lldpConnectedDeviceA); connectedDeviceRepository.add(lldpConnectedDeviceB); connectedDeviceRepository.add(arpConnectedDeviceC); connectedDeviceRepository.add(arpConnectedDeviceD); Collection<SwitchConnectedDevice> firstSwitchDevices = connectedDeviceRepository .findBySwitchId(FIRST_SWITCH_ID); assertEquals(1, firstSwitchDevices.size()); assertEquals(lldpConnectedDeviceA, firstSwitchDevices.iterator().next()); Collection<SwitchConnectedDevice> secondFlowDevices = connectedDeviceRepository .findBySwitchId(SECOND_SWITCH_ID); assertEquals(3, secondFlowDevices.size()); assertEquals(newHashSet(lldpConnectedDeviceB, arpConnectedDeviceC, arpConnectedDeviceD), newHashSet(secondFlowDevices)); }
|
FermaSwitchConnectedDevicesRepository extends FermaGenericRepository<SwitchConnectedDevice, SwitchConnectedDeviceData, SwitchConnectedDeviceFrame> implements SwitchConnectedDeviceRepository { @Override public Collection<SwitchConnectedDevice> findByFlowId(String flowId) { return framedGraph().traverse(g -> g.V() .hasLabel(SwitchConnectedDeviceFrame.FRAME_LABEL) .has(SwitchConnectedDeviceFrame.FLOW_ID_PROPERTY, flowId)) .toListExplicit(SwitchConnectedDeviceFrame.class).stream() .map(SwitchConnectedDevice::new) .collect(Collectors.toList()); } FermaSwitchConnectedDevicesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<SwitchConnectedDevice> findAll(); @Override Collection<SwitchConnectedDevice> findBySwitchId(SwitchId switchId); @Override Collection<SwitchConnectedDevice> findByFlowId(String flowId); @Override Optional<SwitchConnectedDevice> findLldpByUniqueFieldCombination(
SwitchId switchId, int portNumber, int vlan, String macAddress, String chassisId, String portId); @Override Optional<SwitchConnectedDevice> findArpByUniqueFieldCombination(
SwitchId switchId, int portNumber, int vlan, String macAddress, String ipAddress); }
|
@Test public void findByFlowIdTest() { connectedDeviceRepository.add(lldpConnectedDeviceA); connectedDeviceRepository.add(lldpConnectedDeviceB); connectedDeviceRepository.add(arpConnectedDeviceC); connectedDeviceRepository.add(arpConnectedDeviceD); Collection<SwitchConnectedDevice> firstDevice = connectedDeviceRepository.findByFlowId(FIRST_FLOW_ID); assertEquals(1, firstDevice.size()); assertEquals(lldpConnectedDeviceA, firstDevice.iterator().next()); Collection<SwitchConnectedDevice> secondDevices = connectedDeviceRepository.findByFlowId(SECOND_FLOW_ID); assertEquals(2, secondDevices.size()); assertEquals(newHashSet(lldpConnectedDeviceB, arpConnectedDeviceD), newHashSet(secondDevices)); }
|
FermaSwitchConnectedDevicesRepository extends FermaGenericRepository<SwitchConnectedDevice, SwitchConnectedDeviceData, SwitchConnectedDeviceFrame> implements SwitchConnectedDeviceRepository { @Override public Optional<SwitchConnectedDevice> findLldpByUniqueFieldCombination( SwitchId switchId, int portNumber, int vlan, String macAddress, String chassisId, String portId) { Collection<? extends SwitchConnectedDeviceFrame> devices = framedGraph().traverse(g -> g.V() .hasLabel(SwitchConnectedDeviceFrame.FRAME_LABEL) .has(SwitchConnectedDeviceFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(SwitchConnectedDeviceFrame.PORT_NUMBER_PROPERTY, portNumber) .has(SwitchConnectedDeviceFrame.VLAN_PROPERTY, vlan) .has(SwitchConnectedDeviceFrame.MAC_ADDRESS_PROPERTY, macAddress) .has(SwitchConnectedDeviceFrame.TYPE_PROPERTY, ConnectedDeviceTypeConverter.INSTANCE.toGraphProperty(ConnectedDeviceType.LLDP)) .has(SwitchConnectedDeviceFrame.CHASSIS_ID_PROPERTY, chassisId) .has(SwitchConnectedDeviceFrame.PORT_ID_PROPERTY, portId)) .toListExplicit(SwitchConnectedDeviceFrame.class); if (devices.size() > 1) { throw new PersistenceException(format("Found more that 1 LLDP Connected Device by switch ID '%s', " + "port number '%d', vlan '%d', mac address '%s', chassis ID '%s' and port ID '%s'", switchId, portNumber, vlan, macAddress, chassisId, portId)); } return devices.isEmpty() ? Optional.empty() : Optional.of(devices.iterator().next()).map(SwitchConnectedDevice::new); } FermaSwitchConnectedDevicesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<SwitchConnectedDevice> findAll(); @Override Collection<SwitchConnectedDevice> findBySwitchId(SwitchId switchId); @Override Collection<SwitchConnectedDevice> findByFlowId(String flowId); @Override Optional<SwitchConnectedDevice> findLldpByUniqueFieldCombination(
SwitchId switchId, int portNumber, int vlan, String macAddress, String chassisId, String portId); @Override Optional<SwitchConnectedDevice> findArpByUniqueFieldCombination(
SwitchId switchId, int portNumber, int vlan, String macAddress, String ipAddress); }
|
@Test public void findByLldpUniqueFields() { connectedDeviceRepository.add(lldpConnectedDeviceA); connectedDeviceRepository.add(lldpConnectedDeviceB); connectedDeviceRepository.add(arpConnectedDeviceC); runFindByLldpUniqueFields(lldpConnectedDeviceA); runFindByLldpUniqueFields(lldpConnectedDeviceB); runFindByLldpUniqueFields(arpConnectedDeviceC); assertFalse(connectedDeviceRepository.findLldpByUniqueFieldCombination( firstSwitch.getSwitchId(), 999, 999, "fake", CHASSIS_ID, PORT_ID).isPresent()); }
@Test public void findByArpUniqueFields() { connectedDeviceRepository.add(lldpConnectedDeviceA); connectedDeviceRepository.add(arpConnectedDeviceC); connectedDeviceRepository.add(arpConnectedDeviceD); runFindByArpUniqueFields(lldpConnectedDeviceA); runFindByArpUniqueFields(arpConnectedDeviceC); runFindByArpUniqueFields(arpConnectedDeviceD); assertFalse(connectedDeviceRepository.findLldpByUniqueFieldCombination( firstSwitch.getSwitchId(), 999, 999, "fake", CHASSIS_ID, PORT_ID).isPresent()); }
|
FermaPortHistoryRepository extends FermaGenericRepository<PortHistory, PortHistoryData, PortHistoryFrame> implements PortHistoryRepository { @Override public List<PortHistory> findBySwitchIdAndPortNumber(SwitchId switchId, int portNumber, Instant timeFrom, Instant timeTo) { return framedGraph().traverse(g -> { GraphTraversal<Vertex, Vertex> traversal = g.V() .hasLabel(PortHistoryFrame.FRAME_LABEL) .has(PortHistoryFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(PortHistoryFrame.PORT_NUMBER_PROPERTY, portNumber); if (timeFrom != null) { traversal = traversal.has(PortHistoryFrame.TIME_PROPERTY, P.gte(InstantLongConverter.INSTANCE.toGraphProperty(timeFrom))); } if (timeTo != null) { traversal = traversal.has(PortHistoryFrame.TIME_PROPERTY, P.lte(InstantLongConverter.INSTANCE.toGraphProperty(timeTo))); } return traversal .order().by(PortHistoryFrame.TIME_PROPERTY, Order.incr); }).toListExplicit(PortHistoryFrame.class).stream() .map(PortHistory::new) .collect(Collectors.toList()); } FermaPortHistoryRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override List<PortHistory> findBySwitchIdAndPortNumber(SwitchId switchId, int portNumber,
Instant timeFrom, Instant timeTo); }
|
@Test public void shouldFindHistoryRecordsBySwitchByIdAndPortNumber() { Instant start = new Date().toInstant(); Instant end = new Date().toInstant().plus(1, ChronoUnit.DAYS); PortHistory portUp = createPortHistory(SWITCH_ID, PORT_NUMBER, "PORT_UP", start.plus(1, ChronoUnit.HOURS)); PortHistory portDown = createPortHistory(SWITCH_ID, PORT_NUMBER, "PORT_DOWN", end); createPortHistory(new SwitchId(2L), PORT_NUMBER, "TEST1", end); createPortHistory(SWITCH_ID, 3, "TEST2", end); createPortHistory(SWITCH_ID, PORT_NUMBER, "TEST3", start.minus(1, ChronoUnit.SECONDS)); createPortHistory(SWITCH_ID, PORT_NUMBER, "TEST4", end.plus(1, ChronoUnit.HOURS)); Collection<PortHistory> portHistory = repository.findBySwitchIdAndPortNumber(SWITCH_ID, PORT_NUMBER, start, end); assertEquals(2, portHistory.size()); assertTrue(portHistory.contains(portUp)); assertTrue(portHistory.contains(portDown)); }
|
FermaFeatureTogglesRepository extends FermaGenericRepository<FeatureToggles, FeatureTogglesData, FeatureTogglesFrame> implements FeatureTogglesRepository { @Override public Optional<FeatureToggles> find() { List<? extends FeatureTogglesFrame> featureTogglesFrames = framedGraph().traverse(g -> g.V() .hasLabel(FeatureTogglesFrame.FRAME_LABEL)) .toListExplicit(FeatureTogglesFrame.class); return featureTogglesFrames.isEmpty() ? Optional.empty() : Optional.of(featureTogglesFrames.get(0)) .map(FeatureToggles::new); } FermaFeatureTogglesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Optional<FeatureToggles> find(); @Override FeatureToggles getOrDefault(); }
|
@Test public void shouldCreateAndUpdateFeatureToggles() { FeatureToggles featureTogglesA = FeatureToggles.builder() .flowsRerouteOnIslDiscoveryEnabled(false) .createFlowEnabled(false) .updateFlowEnabled(false) .deleteFlowEnabled(false) .useBfdForIslIntegrityCheck(false) .floodlightRoutePeriodicSync(false) .flowsRerouteUsingDefaultEncapType(false) .build(); featureTogglesRepository.add(featureTogglesA); FeatureToggles foundFeatureToggles = featureTogglesRepository.find().get(); assertEquals(featureTogglesA, foundFeatureToggles); foundFeatureToggles.setUpdateFlowEnabled(true); FeatureToggles updatedFeatureToggles = featureTogglesRepository.find().get(); assertTrue(updatedFeatureToggles.getUpdateFlowEnabled()); }
|
FermaBfdSessionRepository extends FermaGenericRepository<BfdSession, BfdSessionData, BfdSessionFrame> implements BfdSessionRepository { @Override public Collection<BfdSession> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(BfdSessionFrame.FRAME_LABEL)) .toListExplicit(BfdSessionFrame.class).stream() .map(BfdSession::new) .collect(Collectors.toList()); } FermaBfdSessionRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<BfdSession> findAll(); @Override boolean exists(SwitchId switchId, Integer port); @Override Optional<BfdSession> findBySwitchIdAndPort(SwitchId switchId, Integer port); }
|
@Test public void shouldCreateBfdPort() { createBfdSession(); assertEquals(1, repository.findAll().size()); }
@Test public void shouldDeleteBfdPort() { BfdSession bfdSession = createBfdSession(); assertEquals(1, repository.findAll().size()); transactionManager.doInTransaction(() -> repository.remove(bfdSession)); assertEquals(0, repository.findAll().size()); }
@Ignore("Need to fix: in-memory persistence doesn't impose constraints") @Test(expected = ConstraintViolationException.class) public void createUseCaseTest() { assertEquals(TEST_DISCRIMINATOR, getDiscriminator(TEST_SWITCH_ID, TEST_PORT, TEST_DISCRIMINATOR)); assertEquals(TEST_DISCRIMINATOR, getDiscriminator(TEST_SWITCH_ID, TEST_PORT, TEST_DISCRIMINATOR)); assertEquals(1, repository.findAll().size()); assertEquals(TEST_DISCRIMINATOR, getDiscriminator(TEST_SWITCH_ID, TEST_PORT + 1, TEST_DISCRIMINATOR)); }
@Test public void deleteUseCaseTest() { getDiscriminator(TEST_SWITCH_ID, TEST_PORT, TEST_DISCRIMINATOR); assertEquals(1, repository.findAll().size()); freeDiscriminator(TEST_SWITCH_ID, TEST_PORT); assertEquals(0, repository.findAll().size()); }
|
FermaBfdSessionRepository extends FermaGenericRepository<BfdSession, BfdSessionData, BfdSessionFrame> implements BfdSessionRepository { @Override public Optional<BfdSession> findBySwitchIdAndPort(SwitchId switchId, Integer port) { List<? extends BfdSessionFrame> bfdSessionFrames = framedGraph().traverse(g -> g.V() .hasLabel(BfdSessionFrame.FRAME_LABEL) .has(BfdSessionFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId)) .has(BfdSessionFrame.PORT_PROPERTY, port)) .toListExplicit(BfdSessionFrame.class); return bfdSessionFrames.isEmpty() ? Optional.empty() : Optional.of(bfdSessionFrames.get(0)) .map(BfdSession::new); } FermaBfdSessionRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<BfdSession> findAll(); @Override boolean exists(SwitchId switchId, Integer port); @Override Optional<BfdSession> findBySwitchIdAndPort(SwitchId switchId, Integer port); }
|
@Test public void shouldFindBySwitchIdAndPort() { BfdSession bfdSession = createBfdSession(); BfdSession foundPort = repository.findBySwitchIdAndPort(TEST_SWITCH_ID, TEST_PORT).get(); assertEquals(bfdSession.getDiscriminator(), foundPort.getDiscriminator()); }
|
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(expected = IllegalSwitchPropertiesException.class) public void shouldValidateSupportedEncapsulationTypeWhenUpdatingSwitchProperties() { Switch sw = Switch.builder().switchId(TEST_SWITCH_ID).status(SwitchStatus.ACTIVE).build(); switchRepository.add(sw); createSwitchProperties(sw, Collections.singleton(FlowEncapsulationType.TRANSIT_VLAN), false, false, false); switchOperationsService.updateSwitchProperties(TEST_SWITCH_ID, new SwitchPropertiesDto()); }
@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); }
@Test(expected = IllegalSwitchPropertiesException.class) public void shouldValidateFlowWithLldpFlagWhenUpdatingSwitchProperties() { Switch firstSwitch = Switch.builder().switchId(TEST_SWITCH_ID).status(SwitchStatus.ACTIVE).build(); Switch secondSwitch = Switch.builder().switchId(TEST_SWITCH_ID_2).status(SwitchStatus.ACTIVE).build(); switchRepository.add(firstSwitch); switchRepository.add(secondSwitch); Flow flow = Flow.builder() .flowId(TEST_FLOW_ID_1) .srcSwitch(firstSwitch) .destSwitch(secondSwitch) .detectConnectedDevices(new DetectConnectedDevices( true, false, true, false, false, false, false, false)) .build(); flowRepository.add(flow); createSwitchProperties( firstSwitch, Collections.singleton(FlowEncapsulationType.TRANSIT_VLAN), true, false, false); SwitchPropertiesDto update = new SwitchPropertiesDto(); update.setSupportedTransitEncapsulation( Collections.singleton(org.openkilda.messaging.payload.flow.FlowEncapsulationType.TRANSIT_VLAN)); update.setMultiTable(false); update.setSwitchLldp(false); switchOperationsService.updateSwitchProperties(TEST_SWITCH_ID, update); }
@Test(expected = IllegalSwitchPropertiesException.class) public void shouldValidateMultiTableFlagWhenUpdatingSwitchPropertiesWithArp() { Switch sw = Switch.builder().switchId(TEST_SWITCH_ID).status(SwitchStatus.ACTIVE).build(); switchRepository.add(sw); createSwitchProperties(sw, Collections.singleton(FlowEncapsulationType.TRANSIT_VLAN), true, false, true); SwitchPropertiesDto update = new SwitchPropertiesDto(); update.setSupportedTransitEncapsulation( Collections.singleton(org.openkilda.messaging.payload.flow.FlowEncapsulationType.TRANSIT_VLAN)); update.setMultiTable(false); update.setSwitchArp(true); switchOperationsService.updateSwitchProperties(TEST_SWITCH_ID, update); }
@Test(expected = IllegalSwitchPropertiesException.class) public void shouldValidateFlowWithArpFlagWhenUpdatingSwitchProperties() { Switch firstSwitch = Switch.builder().switchId(TEST_SWITCH_ID).status(SwitchStatus.ACTIVE).build(); Switch secondSwitch = Switch.builder().switchId(TEST_SWITCH_ID_2).status(SwitchStatus.ACTIVE).build(); switchRepository.add(firstSwitch); switchRepository.add(secondSwitch); Flow flow = Flow.builder() .flowId(TEST_FLOW_ID_1) .srcSwitch(firstSwitch) .destSwitch(secondSwitch) .detectConnectedDevices( new DetectConnectedDevices(false, true, false, true, false, false, false, false)) .build(); flowRepository.add(flow); createSwitchProperties(firstSwitch, Collections.singleton(FlowEncapsulationType.TRANSIT_VLAN), true, false, false); SwitchPropertiesDto update = new SwitchPropertiesDto(); update.setSupportedTransitEncapsulation( Collections.singleton(org.openkilda.messaging.payload.flow.FlowEncapsulationType.TRANSIT_VLAN)); update.setMultiTable(false); update.setSwitchArp(false); switchOperationsService.updateSwitchProperties(TEST_SWITCH_ID, update); }
@Test public void shouldUpdateServer42SwitchProperties() { Switch sw = Switch.builder() .switchId(TEST_SWITCH_ID) .status(SwitchStatus.ACTIVE) .features(Collections.singleton(SwitchFeature.MULTI_TABLE)) .build(); switchRepository.add(sw); createServer42SwitchProperties(sw, false, SERVER_42_PORT_1, SERVER_42_VLAN_1, SERVER_42_MAC_ADDRESS_1); SwitchPropertiesDto update = new SwitchPropertiesDto(); update.setSupportedTransitEncapsulation( Collections.singleton(org.openkilda.messaging.payload.flow.FlowEncapsulationType.TRANSIT_VLAN)); update.setMultiTable(true); update.setServer42FlowRtt(true); update.setServer42Port(SERVER_42_PORT_2); update.setServer42Vlan(SERVER_42_VLAN_2); update.setServer42MacAddress(SERVER_42_MAC_ADDRESS_2); switchOperationsService.updateSwitchProperties(TEST_SWITCH_ID, update); Optional<SwitchProperties> updated = switchPropertiesRepository.findBySwitchId(TEST_SWITCH_ID); assertTrue(updated.isPresent()); assertTrue(updated.get().isServer42FlowRtt()); assertEquals(SERVER_42_PORT_2, updated.get().getServer42Port()); assertEquals(SERVER_42_VLAN_2, updated.get().getServer42Vlan()); assertEquals(SERVER_42_MAC_ADDRESS_2, updated.get().getServer42MacAddress()); }
|
FermaSwitchPropertiesRepository extends FermaGenericRepository<SwitchProperties, SwitchPropertiesData, SwitchPropertiesFrame> implements SwitchPropertiesRepository { @Override public Collection<SwitchProperties> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(SwitchPropertiesFrame.FRAME_LABEL)) .toListExplicit(SwitchPropertiesFrame.class).stream() .map(SwitchProperties::new) .collect(Collectors.toList()); } FermaSwitchPropertiesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<SwitchProperties> findAll(); @Override Optional<SwitchProperties> findBySwitchId(SwitchId switchId); }
|
@Test public void shouldCreateSwitchPropertiesWithRelation() { Switch origSwitch = Switch.builder() .switchId(TEST_SWITCH_ID) .description("Some description") .build(); switchRepository.add(origSwitch); SwitchProperties switchProperties = SwitchProperties.builder() .switchObj(origSwitch) .supportedTransitEncapsulation(SwitchProperties.DEFAULT_FLOW_ENCAPSULATION_TYPES) .build(); switchPropertiesRepository.add(switchProperties); List<SwitchProperties> switchPropertiesResult = new ArrayList<>(switchPropertiesRepository.findAll()); assertEquals(1, switchPropertiesResult.size()); assertNotNull(switchPropertiesResult.get(0).getSwitchObj()); }
|
FermaSwitchPropertiesRepository extends FermaGenericRepository<SwitchProperties, SwitchPropertiesData, SwitchPropertiesFrame> implements SwitchPropertiesRepository { @Override public Optional<SwitchProperties> findBySwitchId(SwitchId switchId) { List<? extends SwitchPropertiesFrame> switchPropertiesFrames = framedGraph().traverse(g -> g.V() .hasLabel(SwitchPropertiesFrame.FRAME_LABEL) .has(SwitchPropertiesFrame.SWITCH_ID_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(switchId))) .toListExplicit(SwitchPropertiesFrame.class); return switchPropertiesFrames.isEmpty() ? Optional.empty() : Optional.of(switchPropertiesFrames.get(0)) .map(SwitchProperties::new); } FermaSwitchPropertiesRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<SwitchProperties> findAll(); @Override Optional<SwitchProperties> findBySwitchId(SwitchId switchId); }
|
@Test public void shouldFindSwitchPropertiesBySwitchId() { Switch origSwitch = Switch.builder() .switchId(TEST_SWITCH_ID) .description("Some description") .build(); switchRepository.add(origSwitch); SwitchProperties switchProperties = SwitchProperties.builder() .switchObj(origSwitch) .supportedTransitEncapsulation(SwitchProperties.DEFAULT_FLOW_ENCAPSULATION_TYPES) .build(); switchPropertiesRepository.add(switchProperties); Optional<SwitchProperties> switchPropertiesOptional = switchPropertiesRepository.findBySwitchId(TEST_SWITCH_ID); assertTrue(switchPropertiesOptional.isPresent()); }
@Test public void shouldCreatePropertiesWithServer42Props() { Switch origSwitch = Switch.builder().switchId(TEST_SWITCH_ID) .description("Some description").build(); switchRepository.add(origSwitch); SwitchProperties switchProperties = SwitchProperties.builder() .switchObj(origSwitch) .server42FlowRtt(true) .server42Port(SERVER_42_PORT) .server42Vlan(SERVER_42_VLAN) .server42MacAddress(SERVER_42_MAC_ADDRESS) .supportedTransitEncapsulation(SwitchProperties.DEFAULT_FLOW_ENCAPSULATION_TYPES) .build(); switchPropertiesRepository.add(switchProperties); Optional<SwitchProperties> switchPropertiesOptional = switchPropertiesRepository.findBySwitchId(TEST_SWITCH_ID); assertTrue(switchPropertiesOptional.isPresent()); assertTrue(switchPropertiesOptional.get().isServer42FlowRtt()); assertEquals(SERVER_42_PORT, switchPropertiesOptional.get().getServer42Port()); assertEquals(SERVER_42_VLAN, switchPropertiesOptional.get().getServer42Vlan()); assertEquals(SERVER_42_MAC_ADDRESS, switchPropertiesOptional.get().getServer42MacAddress()); }
@Test public void shouldCreatePropertiesWithNullServer42Props() { Switch origSwitch = Switch.builder().switchId(TEST_SWITCH_ID) .description("Some description").build(); switchRepository.add(origSwitch); SwitchProperties switchProperties = SwitchProperties.builder() .switchObj(origSwitch) .server42Port(null) .server42Vlan(null) .server42MacAddress(null) .supportedTransitEncapsulation(SwitchProperties.DEFAULT_FLOW_ENCAPSULATION_TYPES).build(); switchPropertiesRepository.add(switchProperties); Optional<SwitchProperties> switchPropertiesOptional = switchPropertiesRepository.findBySwitchId(TEST_SWITCH_ID); assertTrue(switchPropertiesOptional.isPresent()); assertFalse(switchPropertiesOptional.get().isServer42FlowRtt()); assertNull(switchPropertiesOptional.get().getServer42Port()); assertNull(switchPropertiesOptional.get().getServer42MacAddress()); }
|
FermaLinkPropsRepository extends FermaGenericRepository<LinkProps, LinkPropsData, LinkPropsFrame> implements LinkPropsRepository { @Override public Collection<LinkProps> findAll() { return framedGraph().traverse(g -> g.V() .hasLabel(LinkPropsFrame.FRAME_LABEL)) .toListExplicit(LinkPropsFrame.class).stream() .map(LinkProps::new) .collect(Collectors.toList()); } FermaLinkPropsRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<LinkProps> findAll(); @Override Collection<LinkProps> findByEndpoints(SwitchId srcSwitch, Integer srcPort,
SwitchId dstSwitch, Integer dstPort); }
|
@Test public void shouldCreateLinkProps() { createLinkProps(1); assertEquals(1, linkPropsRepository.findAll().size()); }
@Test public void shouldDeleteLinkProps() { LinkProps linkProps = createLinkProps(1); transactionManager.doInTransaction(() -> { linkPropsRepository.remove(linkProps); }); assertEquals(0, linkPropsRepository.findAll().size()); }
|
FermaLinkPropsRepository extends FermaGenericRepository<LinkProps, LinkPropsData, LinkPropsFrame> implements LinkPropsRepository { @Override public Collection<LinkProps> findByEndpoints(SwitchId srcSwitch, Integer srcPort, SwitchId dstSwitch, Integer dstPort) { return framedGraph().traverse(g -> { GraphTraversal<Vertex, Vertex> traversal = g.V() .hasLabel(LinkPropsFrame.FRAME_LABEL); if (srcSwitch != null) { traversal = traversal.has(LinkPropsFrame.SRC_SWITCH_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(srcSwitch)); } if (srcPort != null) { traversal = traversal.has(LinkPropsFrame.SRC_PORT_PROPERTY, srcPort); } if (dstSwitch != null) { traversal = traversal.has(LinkPropsFrame.DST_SWITCH_PROPERTY, SwitchIdConverter.INSTANCE.toGraphProperty(dstSwitch)); } if (dstPort != null) { traversal = traversal.has(LinkPropsFrame.DST_PORT_PROPERTY, dstPort); } return traversal; }).toListExplicit(LinkPropsFrame.class).stream() .map(LinkProps::new) .collect(Collectors.toList()); } FermaLinkPropsRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager); @Override Collection<LinkProps> findAll(); @Override Collection<LinkProps> findByEndpoints(SwitchId srcSwitch, Integer srcPort,
SwitchId dstSwitch, Integer dstPort); }
|
@Test public void shouldFindLinkPropsByEndpoints() { createLinkProps(2); List<LinkProps> foundLinkProps = Lists.newArrayList( linkPropsRepository.findByEndpoints(TEST_SWITCH_A_ID, 1, TEST_SWITCH_B_ID, 2)); assertThat(foundLinkProps, Matchers.hasSize(1)); }
@Test public void shouldFindLinkPropsBySrcEndpoint() { createLinkProps(2); List<LinkProps> foundLinkProps = Lists.newArrayList( linkPropsRepository.findByEndpoints(TEST_SWITCH_A_ID, 1, null, null)); assertThat(foundLinkProps, Matchers.hasSize(1)); }
@Test public void shouldFindLinkPropsByDestEndpoint() { createLinkProps(2); List<LinkProps> foundLinkProps = Lists.newArrayList( linkPropsRepository.findByEndpoints(null, null, TEST_SWITCH_B_ID, 2)); assertThat(foundLinkProps, Matchers.hasSize(1)); }
@Test public void shouldFindLinkPropsBySrcAndDestSwitches() { createLinkProps(1); List<LinkProps> foundLinkProps = Lists.newArrayList( linkPropsRepository.findByEndpoints(TEST_SWITCH_A_ID, null, TEST_SWITCH_B_ID, null)); assertThat(foundLinkProps, Matchers.hasSize(1)); }
|
FlowValidationService { public List<SwitchId> getSwitchIdListByFlowId(String flowId) { return switchRepository.findSwitchesInFlowPathByFlowId(flowId).stream() .map(Switch::getSwitchId) .collect(Collectors.toList()); } FlowValidationService(PersistenceManager persistenceManager, FlowResourcesConfig flowResourcesConfig,
long flowMeterMinBurstSizeInKbits, double flowMeterBurstCoefficient); void checkFlowStatus(String flowId); List<SwitchId> getSwitchIdListByFlowId(String flowId); List<FlowValidationResponse> validateFlow(String flowId, List<SwitchFlowEntries> switchFlowEntries,
List<SwitchMeterEntries> switchMeterEntries); }
|
@Test public void shouldGetSwitchIdListByFlowId() { buildTransitVlanFlow(""); List<SwitchId> switchIds = service.getSwitchIdListByFlowId(TEST_FLOW_ID_A); assertEquals(4, switchIds.size()); buildOneSwitchPortFlow(); switchIds = service.getSwitchIdListByFlowId(TEST_FLOW_ID_B); assertEquals(1, switchIds.size()); }
|
OneToOneMapping implements MappingApproach { public void remove(SwitchId switchId, String region) { remove(switchId); } OneToOneMapping(Clock clock, Duration staleWipeDelay); Optional<String> lookup(SwitchId switchId); @Override void set(SwitchId switchId, String region); void add(SwitchId switchId, String region); void remove(SwitchId switchId, String region); void remove(SwitchId switchId); Map<String, Set<SwitchId>> makeReversedMapping(); }
|
@Test public void testRemove() { OneToOneMapping subject = makeSubject(); subject.add(SWITCH_ALPHA, REGION_A); subject.add(SWITCH_BETA, REGION_A); subject.remove(SWITCH_ALPHA); Optional<String> result = subject.lookup(SWITCH_ALPHA); Assert.assertTrue(result.isPresent()); Assert.assertEquals(REGION_A, result.get()); Assert.assertTrue(subject.lookup(SWITCH_ALPHA).isPresent()); clock.adjust(staleDelay.plus(Duration.ofSeconds(1))); Assert.assertFalse(subject.lookup(SWITCH_ALPHA).isPresent()); Assert.assertTrue(subject.lookup(SWITCH_BETA).isPresent()); }
|
SwitchReadWriteConnectMonitor extends SwitchConnectMonitor { @Override protected boolean isReadWriteMode() { return true; } SwitchReadWriteConnectMonitor(SwitchMonitorCarrier carrier, Clock clock, SwitchId switchId); }
|
@Test public void multipleConnections() { SwitchReadWriteConnectMonitor subject = makeSubject(SWITCH_ALPHA); SwitchInfoData connectEvent = makeConnectNotification(SWITCH_ALPHA); subject.handleSwitchStatusNotification(connectEvent, REGION_A); verify(carrier, times(1)) .switchStatusUpdateNotification(eq(connectEvent.getSwitchId()), eq(connectEvent)); verify(carrier).regionUpdateNotification( eq(new RegionMappingSet(connectEvent.getSwitchId(), REGION_A, subject.isReadWriteMode()))); subject.handleSwitchStatusNotification(connectEvent, REGION_B); verify(carrier, times(1)) .switchStatusUpdateNotification(eq(connectEvent.getSwitchId()), eq(connectEvent)); verify(carrier, never()).regionUpdateNotification( eq(new RegionMappingSet(connectEvent.getSwitchId(), REGION_B, subject.isReadWriteMode()))); }
@Test public void disconnectOneOfOneConnections() { SwitchReadWriteConnectMonitor subject = makeSubject(SWITCH_ALPHA); SwitchInfoData connectEvent = makeConnectNotification(SWITCH_ALPHA); subject.handleSwitchStatusNotification(connectEvent, REGION_A); verify(carrier).switchStatusUpdateNotification(eq(connectEvent.getSwitchId()), eq(connectEvent)); verify(carrier).regionUpdateNotification( eq(new RegionMappingSet(connectEvent.getSwitchId(), REGION_A, subject.isReadWriteMode()))); Instant now = clock.adjust(Duration.ofSeconds(1)); Assert.assertTrue(subject.isAvailable()); SwitchInfoData disconnectEvent = makeDisconnectNotification(connectEvent.getSwitchId()); subject.handleSwitchStatusNotification(disconnectEvent, REGION_A); verify(carrier).switchStatusUpdateNotification( eq(disconnectEvent.getSwitchId()), ArgumentMatchers.eq(disconnectEvent)); Assert.assertFalse(subject.isAvailable()); Assert.assertEquals(now, subject.getBecomeUnavailableAt()); }
@Test public void disconnectTwoOfTwoConnections() { SwitchReadWriteConnectMonitor subject = makeSubject(SWITCH_ALPHA); SwitchInfoData connectEvent = makeConnectNotification(SWITCH_ALPHA); subject.handleSwitchStatusNotification(connectEvent, REGION_A); subject.handleSwitchStatusNotification(connectEvent, REGION_B); Assert.assertTrue(subject.isAvailable()); SwitchInfoData disconnectEvent = makeDisconnectNotification(connectEvent.getSwitchId()); clock.adjust(Duration.ofSeconds(1)); subject.handleSwitchStatusNotification(disconnectEvent, REGION_A); verify(carrier).regionUpdateNotification( eq(new RegionMappingSet(disconnectEvent.getSwitchId(), REGION_B, subject.isReadWriteMode()))); reset(carrier); Instant failedAt = clock.adjust(Duration.ofSeconds(1)); subject.handleSwitchStatusNotification(disconnectEvent, REGION_B); Assert.assertFalse(subject.isAvailable()); Assert.assertEquals(failedAt, subject.getBecomeUnavailableAt()); verify(carrier).switchStatusUpdateNotification(eq(disconnectEvent.getSwitchId()), eq(disconnectEvent)); verify(carrier).regionUpdateNotification( eq(new RegionMappingRemove(disconnectEvent.getSwitchId(), null, subject.isReadWriteMode()))); verifyNoMoreInteractions(carrier); }
|
SwitchMonitorService { public void handleStatusUpdateNotification(SwitchInfoData notification, String region) { SwitchMonitorEntry entry = lookupOrCreateSwitchMonitor(notification.getSwitchId()); entry.handleStatusUpdateNotification(notification, region); } SwitchMonitorService(Clock clock, SwitchMonitorCarrier carrier); void handleTimerTick(); void handleRegionOfflineNotification(String region); void handleStatusUpdateNotification(SwitchInfoData notification, String region); void handleNetworkDumpResponse(NetworkDumpSwitchData response, String region); }
|
@Test public void regularSwitchConnectSequence() { SwitchMonitorService subject = makeSubject(); SwitchInfoData swAdd = new SwitchInfoData(SWITCH_ALPHA, SwitchChangeType.ADDED); subject.handleStatusUpdateNotification(swAdd, REGION_ALPHA); verify(carrier).regionUpdateNotification( eq(new RegionMappingAdd(swAdd.getSwitchId(), REGION_ALPHA, false))); verifyNoMoreInteractions(carrier); SwitchInfoData swActivate = makeSwitchActivateNotification(swAdd.getSwitchId()); subject.handleStatusUpdateNotification(swActivate, REGION_ALPHA); verify(carrier).switchStatusUpdateNotification(eq(swActivate.getSwitchId()), eq(swActivate)); verify(carrier).regionUpdateNotification( eq(new RegionMappingSet(swActivate.getSwitchId(), REGION_ALPHA, true))); verifyNoMoreInteractions(carrier); }
|
PacketService { public void handleLldpData(LldpInfoData data) { transactionManager.doInTransaction(() -> { FlowRelatedData flowRelatedData = findFlowRelatedData(data); if (flowRelatedData == null) { return; } SwitchConnectedDevice device = getOrCreateLldpDevice(data, flowRelatedData.originalVlan); if (device == null) { return; } device.setTtl(data.getTtl()); device.setPortDescription(data.getPortDescription()); device.setSystemName(data.getSystemName()); device.setSystemDescription(data.getSystemDescription()); device.setSystemCapabilities(data.getSystemCapabilities()); device.setManagementAddress(data.getManagementAddress()); device.setTimeLastSeen(Instant.ofEpochMilli(data.getTimestamp())); device.setFlowId(flowRelatedData.flowId); device.setSource(flowRelatedData.source); }); } PacketService(PersistenceManager persistenceManager); void handleLldpData(LldpInfoData data); void handleArpData(ArpInfoData data); static final int FULL_PORT_VLAN; }
|
@Test public void testHandleLldpDataSameTimeOnCreate() { LldpInfoData data = createLldpInfoDataData(); packetService.handleLldpData(data); Collection<SwitchConnectedDevice> devices = switchConnectedDeviceRepository.findAll(); assertEquals(1, devices.size()); assertEquals(devices.iterator().next().getTimeFirstSeen(), devices.iterator().next().getTimeLastSeen()); }
@Test public void testHandleLldpDataDifferentTimeOnUpdate() throws InterruptedException { packetService.handleLldpData(createLldpInfoDataData()); Thread.sleep(10); packetService.handleLldpData(createLldpInfoDataData()); Collection<SwitchConnectedDevice> devices = switchConnectedDeviceRepository.findAll(); assertEquals(1, devices.size()); assertNotEquals(devices.iterator().next().getTimeFirstSeen(), devices.iterator().next().getTimeLastSeen()); }
@Test public void testHandleLldpDataNonExistentSwitch() { LldpInfoData data = createLldpInfoDataData(); data.setSwitchId(new SwitchId("12345")); packetService.handleLldpData(data); assertTrue(switchConnectedDeviceRepository.findAll().isEmpty()); }
|
PacketService { public void handleArpData(ArpInfoData data) { transactionManager.doInTransaction(() -> { FlowRelatedData flowRelatedData = findFlowRelatedData(data); if (flowRelatedData == null) { return; } SwitchConnectedDevice device = getOrCreateArpDevice(data, flowRelatedData.originalVlan); if (device == null) { return; } device.setTimeLastSeen(Instant.ofEpochMilli(data.getTimestamp())); device.setFlowId(flowRelatedData.flowId); device.setSource(flowRelatedData.source); }); } PacketService(PersistenceManager persistenceManager); void handleLldpData(LldpInfoData data); void handleArpData(ArpInfoData data); static final int FULL_PORT_VLAN; }
|
@Test public void testHandleArpDataSameTimeOnCreate() { packetService.handleArpData(createArpInfoData()); Collection<SwitchConnectedDevice> devices = switchConnectedDeviceRepository.findAll(); assertEquals(1, devices.size()); assertEquals(devices.iterator().next().getTimeFirstSeen(), devices.iterator().next().getTimeLastSeen()); }
@Test public void testHandleArpDataDifferentTimeOnUpdate() throws InterruptedException { packetService.handleArpData(createArpInfoData()); Thread.sleep(10); packetService.handleArpData(createArpInfoData()); Collection<SwitchConnectedDevice> devices = switchConnectedDeviceRepository.findAll(); assertEquals(1, devices.size()); assertNotEquals(devices.iterator().next().getTimeFirstSeen(), devices.iterator().next().getTimeLastSeen()); }
@Test public void testHandleArpDataNonExistentSwitch() { ArpInfoData data = createArpInfoData(); data.setSwitchId(new SwitchId("12345")); packetService.handleArpData(data); assertTrue(switchConnectedDeviceRepository.findAll().isEmpty()); }
|
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 shouldValidateFlowWithTransitVlanEncapsulation() throws FlowNotFoundException, SwitchNotFoundException { buildTransitVlanFlow(""); validateFlow(true); }
@Test public void shouldValidateFlowWithVxlanEncapsulation() throws FlowNotFoundException, SwitchNotFoundException { buildVxlanFlow(); validateFlow(false); }
@Test public void shouldValidateOneSwitchFlow() throws FlowNotFoundException, SwitchNotFoundException { buildOneSwitchPortFlow(); List<SwitchFlowEntries> switchEntries = getSwitchFlowEntriesOneSwitchFlow(); List<SwitchMeterEntries> meterEntries = getSwitchMeterEntriesOneSwitchFlow(); List<FlowValidationResponse> result = service.validateFlow(TEST_FLOW_ID_B, switchEntries, meterEntries); assertEquals(2, result.size()); assertEquals(0, result.get(0).getDiscrepancies().size()); assertEquals(0, result.get(1).getDiscrepancies().size()); }
@Test(expected = FlowNotFoundException.class) public void shouldValidateFlowUsingNotExistingFlow() throws FlowNotFoundException, SwitchNotFoundException { service.validateFlow("test", new ArrayList<>(), new ArrayList<>()); }
@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()); }
|
PacketService { @VisibleForTesting FlowRelatedData findFlowRelatedDataForOneSwitchFlow(ConnectedDevicePacketBase data) { int outputVlan = data.getVlans().isEmpty() ? 0 : data.getVlans().get(0); int customerVlan = data.getVlans().size() > 1 ? data.getVlans().get(1) : 0; Flow flow = getFlowBySwitchIdInPortAndOutVlan( data.getSwitchId(), data.getPortNumber(), outputVlan, getPacketName(data)); if (flow == null) { return null; } if (!flow.isOneSwitchFlow()) { log.warn("Found NOT one switch flow {} by SwitchId {}, port number {}, vlan {} from {} packet", flow.getFlowId(), data.getSwitchId(), data.getPortNumber(), outputVlan, getPacketName(data)); return null; } if (flow.getSrcPort() == flow.getDestPort()) { return getOneSwitchOnePortFlowRelatedData(flow, outputVlan, customerVlan, data); } if (data.getPortNumber() == flow.getSrcPort()) { if (flow.getSrcVlan() == FULL_PORT_VLAN) { if (flow.getDestVlan() == FULL_PORT_VLAN) { return new FlowRelatedData(outputVlan, flow.getFlowId(), true); } else { return new FlowRelatedData(customerVlan, flow.getFlowId(), true); } } else { return new FlowRelatedData(flow.getSrcVlan(), flow.getFlowId(), true); } } else if (data.getPortNumber() == flow.getDestPort()) { if (flow.getDestVlan() == FULL_PORT_VLAN) { if (flow.getSrcVlan() == FULL_PORT_VLAN) { return new FlowRelatedData(outputVlan, flow.getFlowId(), false); } else { return new FlowRelatedData(customerVlan, flow.getFlowId(), false); } } else { return new FlowRelatedData(flow.getDestVlan(), flow.getFlowId(), false); } } log.warn("Got LLDP packet from one switch flow {} with non-src/non-dst vlan {}. SwitchId {}, " + "port number {}", flow.getFlowId(), outputVlan, data.getSwitchId(), data.getPortNumber()); return null; } PacketService(PersistenceManager persistenceManager); void handleLldpData(LldpInfoData data); void handleArpData(ArpInfoData data); static final int FULL_PORT_VLAN; }
|
@Test @Parameters(method = "getOneSwitchOnePortFlowParameters") public void findFlowRelatedDataForOneSwitchOnePortFlowTest( int inVlan, int srcVlan, int dstVlan, List<Integer> vlansInPacket, boolean source) { createFlow(FLOW_ID, srcVlan, dstVlan, null, true, true); LldpInfoData data = createLldpInfoDataData(SWITCH_ID_1, vlansInPacket, PORT_NUMBER_1); FlowRelatedData flowRelatedData = packetService.findFlowRelatedDataForOneSwitchFlow(data); assertEquals(FLOW_ID, flowRelatedData.getFlowId()); assertEquals(inVlan, flowRelatedData.getOriginalVlan()); assertEquals(source, flowRelatedData.getSource()); }
@Test @Parameters(method = "getOneSwitchFlowParameters") public void findFlowRelatedDataForOneSwitchFlowTest( int inVlan, int srcVlan, int dstVlan, List<Integer> vlansInPacket, boolean source) { createFlow(FLOW_ID, srcVlan, dstVlan, null, true, false); LldpInfoData data = createLldpInfoDataData( SWITCH_ID_1, vlansInPacket, source ? PORT_NUMBER_1 : PORT_NUMBER_2); FlowRelatedData flowRelatedData = packetService.findFlowRelatedDataForOneSwitchFlow(data); assertEquals(FLOW_ID, flowRelatedData.getFlowId()); assertEquals(inVlan, flowRelatedData.getOriginalVlan()); assertEquals(source, flowRelatedData.getSource()); }
|
PacketService { @VisibleForTesting FlowRelatedData findFlowRelatedDataForVlanFlow(ConnectedDevicePacketBase data) { if (data.getVlans().isEmpty()) { log.warn("Got {} packet without transit VLAN: {}", getPacketName(data), data); return null; } int transitVlan = data.getVlans().get(0); Flow flow = findFlowByTransitVlan(transitVlan); if (flow == null) { return null; } int customerVlan = data.getVlans().size() > 1 ? data.getVlans().get(1) : 0; if (data.getSwitchId().equals(flow.getSrcSwitchId())) { if (flow.getSrcVlan() == FULL_PORT_VLAN) { return new FlowRelatedData(customerVlan, flow.getFlowId(), true); } else { return new FlowRelatedData(flow.getSrcVlan(), flow.getFlowId(), true); } } else if (data.getSwitchId().equals(flow.getDestSwitchId())) { if (flow.getDestVlan() == FULL_PORT_VLAN) { return new FlowRelatedData(customerVlan, flow.getFlowId(), false); } else { return new FlowRelatedData(flow.getDestVlan(), flow.getFlowId(), false); } } else { log.warn("Got {} packet from Flow {} on non-src/non-dst switch {}. Transit vlan: {}", getPacketName(data), flow.getFlowId(), data.getSwitchId(), transitVlan); return null; } } PacketService(PersistenceManager persistenceManager); void handleLldpData(LldpInfoData data); void handleArpData(ArpInfoData data); static final int FULL_PORT_VLAN; }
|
@Test @Parameters(method = "getVlanFlowParameters") public void findFlowRelatedDataForVlanFlowTest( int inVlan, int srcVlan, int dstVlan, int transitVlan, List<Integer> vlansInPacket, boolean source) { createFlow(FLOW_ID, srcVlan, dstVlan, transitVlan, false, false); LldpInfoData data = createLldpInfoDataData( source ? SWITCH_ID_1 : SWITCH_ID_2, vlansInPacket, source ? PORT_NUMBER_1 : PORT_NUMBER_2); FlowRelatedData flowRelatedData = packetService.findFlowRelatedDataForVlanFlow(data); assertEquals(FLOW_ID, flowRelatedData.getFlowId()); assertEquals(inVlan, flowRelatedData.getOriginalVlan()); assertEquals(source, flowRelatedData.getSource()); }
|
PacketService { @VisibleForTesting FlowRelatedData findFlowRelatedDataForVxlanFlow(ConnectedDevicePacketBase data) { int inputVlan = data.getVlans().isEmpty() ? 0 : data.getVlans().get(0); Flow flow = getFlowBySwitchIdPortAndVlan( data.getSwitchId(), data.getPortNumber(), inputVlan, getPacketName(data)); if (flow == null) { return null; } if (data.getSwitchId().equals(flow.getSrcSwitchId())) { return new FlowRelatedData(inputVlan, flow.getFlowId(), true); } else if (data.getSwitchId().equals(flow.getDestSwitchId())) { return new FlowRelatedData(inputVlan, flow.getFlowId(), false); } else { log.warn("Got {} packet from Flow {} on non-src/non-dst switch {}. Port number {}, input vlan {}", getPacketName(data), flow.getFlowId(), data.getSwitchId(), data.getPortNumber(), inputVlan); return null; } } PacketService(PersistenceManager persistenceManager); void handleLldpData(LldpInfoData data); void handleArpData(ArpInfoData data); static final int FULL_PORT_VLAN; }
|
@Test @Parameters(method = "getInOutVlanCombinationForVxlanParameters") public void findFlowRelatedDataForVxlanFlowTest( int inVlan, int srcVlan, int dstVlan, List<Integer> vlansInPacket, boolean source) { createFlow(FLOW_ID, srcVlan, dstVlan, null, false, false); LldpInfoData data = createLldpInfoDataData( source ? SWITCH_ID_1 : SWITCH_ID_2, vlansInPacket, source ? PORT_NUMBER_1 : PORT_NUMBER_2); FlowRelatedData flowRelatedData = packetService.findFlowRelatedDataForVxlanFlow(data); assertEquals(FLOW_ID, flowRelatedData.getFlowId()); assertEquals(inVlan, flowRelatedData.getOriginalVlan()); assertEquals(source, flowRelatedData.getSource()); }
|
RerouteService { public void rerouteInactiveFlows(MessageSender sender, String correlationId, RerouteInactiveFlows command) { PathNode pathNode = command.getPathNode(); int port = pathNode.getPortNo(); SwitchId switchId = pathNode.getSwitchId(); transactionManager.doInTransaction(() -> { Map<Flow, Set<PathId>> flowsForRerouting = getInactiveFlowsForRerouting(); for (Entry<Flow, Set<PathId>> entry : flowsForRerouting.entrySet()) { Flow flow = entry.getKey(); Set<IslEndpoint> allAffectedIslEndpoints = new HashSet<>(); for (FlowPath flowPath : flow.getPaths()) { Set<IslEndpoint> affectedIslEndpoints = new HashSet<>(); PathSegment firstSegment = null; int failedSegmentsCount = 0; for (PathSegment pathSegment : flowPath.getSegments()) { if (firstSegment == null) { firstSegment = pathSegment; } if (pathSegment.isFailed()) { affectedIslEndpoints.add(new IslEndpoint( pathSegment.getSrcSwitchId(), pathSegment.getSrcPort())); affectedIslEndpoints.add(new IslEndpoint( pathSegment.getDestSwitchId(), pathSegment.getDestPort())); if (pathSegment.containsNode(switchId, port)) { pathSegment.setFailed(false); pathSegmentRepository.updateFailedStatus(flowPath, pathSegment, false); } else { failedSegmentsCount++; } } } if (flowPath.getStatus().equals(FlowPathStatus.INACTIVE) && failedSegmentsCount == 0) { updateFlowPathStatus(flowPath, FlowPathStatus.ACTIVE); if (affectedIslEndpoints.isEmpty() && firstSegment != null) { affectedIslEndpoints.add(new IslEndpoint( firstSegment.getSrcSwitchId(), firstSegment.getSrcPort())); } } allAffectedIslEndpoints.addAll(affectedIslEndpoints); } FlowStatus flowStatus = flow.computeFlowStatus(); String flowStatusInfo = null; if (!FlowStatus.UP.equals(flowStatus)) { flowStatusInfo = command.getReason(); } flowRepository.updateStatusSafe(flow, flowStatus, flowStatusInfo); if (flow.isPinned()) { log.info("Skipping reroute command for pinned flow {}", flow.getFlowId()); } else { log.info("Produce reroute(attempt to restore inactive flows) request for {} (affected ISL " + "endpoints: {})", flow.getFlowId(), allAffectedIslEndpoints); FlowThrottlingData flowThrottlingData = getFlowThrottlingDataBuilder(flow) .correlationId(correlationId) .affectedIsl(allAffectedIslEndpoints) .force(false) .effectivelyDown(true) .reason(command.getReason()) .build(); sender.emitRerouteCommand(flow.getFlowId(), flowThrottlingData); } } }); } RerouteService(PersistenceManager persistenceManager); void rerouteAffectedFlows(MessageSender sender, String correlationId, RerouteAffectedFlows command); void rerouteInactiveAffectedFlows(MessageSender sender, String correlationId,
SwitchId switchId); void rerouteInactiveFlows(MessageSender sender, String correlationId, RerouteInactiveFlows command); Collection<FlowPath> getAffectedFlowPaths(SwitchId switchId, int port); List<FlowPath> getPathsForSwapping(Collection<FlowPath> paths); List<FlowWithAffectedPaths> groupPathsForRerouting(Collection<FlowPath> paths); Set<Flow> groupAffectedPinnedFlows(Collection<FlowPath> paths); Map<Flow, Set<PathId>> getInactiveFlowsForRerouting(); Set<Flow> getAffectedInactiveFlowsForRerouting(SwitchId switchId); void processManualRerouteRequest(MessageSender sender, String correlationId, FlowRerouteRequest request); void processSingleSwitchFlowStatusUpdate(SwitchStateChanged request); }
|
@Test public void testRerouteInactivePinnedFlowsOneFailedSegment() { pinnedFlow.setStatus(FlowStatus.DOWN); for (FlowPath flowPath : pinnedFlow.getPaths()) { flowPath.setStatus(FlowPathStatus.INACTIVE); for (PathSegment pathSegment : flowPath.getSegments()) { if (pathSegment.containsNode(SWITCH_ID_A, PORT)) { pathSegment.setFailed(true); } } } RepositoryFactory repositoryFactory = mock(RepositoryFactory.class); FlowRepository flowRepository = mock(FlowRepository.class); when(flowRepository.findInactiveFlows()) .thenReturn(Collections.singletonList(pinnedFlow)); doAnswer(invocation -> { FlowStatus status = invocation.getArgument(1); pinnedFlow.setStatus(status); return null; }).when(flowRepository).updateStatusSafe(eq(pinnedFlow), any(), any()); when(repositoryFactory.createFlowRepository()).thenReturn(flowRepository); FlowPathRepository pathRepository = mock(FlowPathRepository.class); when(repositoryFactory.createFlowPathRepository()).thenReturn(pathRepository); PathSegmentRepository pathSegmentRepository = mock(PathSegmentRepository.class); when(repositoryFactory.createPathSegmentRepository()).thenReturn(pathSegmentRepository); MessageSender messageSender = mock(MessageSender.class); PersistenceManager persistenceManager = mock(PersistenceManager.class); when(persistenceManager.getRepositoryFactory()).thenReturn(repositoryFactory); TransactionManager transactionManager = mock(TransactionManager.class); doAnswer(invocation -> { TransactionCallbackWithoutResult arg = invocation.getArgument(0); arg.doInTransaction(); return null; }).when(transactionManager).doInTransaction(Mockito.<TransactionCallbackWithoutResult>any()); when(persistenceManager.getTransactionManager()).thenReturn(transactionManager); RerouteService rerouteService = new RerouteService(persistenceManager); rerouteService.rerouteInactiveFlows(messageSender, CORRELATION_ID, REROUTE_INACTIVE_FLOWS_COMMAND); assertEquals(FlowStatus.UP, pinnedFlow.getStatus()); for (FlowPath fp : pinnedFlow.getPaths()) { assertEquals(FlowPathStatus.ACTIVE, fp.getStatus()); for (PathSegment ps : fp.getSegments()) { if (ps.containsNode(SWITCH_ID_A, PORT)) { assertFalse(ps.isFailed()); } } } }
@Test public void testRerouteInactivePinnedFlowsTwoFailedSegments() { pinnedFlow.setStatus(FlowStatus.DOWN); for (FlowPath flowPath : pinnedFlow.getPaths()) { flowPath.setStatus(FlowPathStatus.INACTIVE); for (PathSegment pathSegment : flowPath.getSegments()) { pathSegment.setFailed(true); } } RepositoryFactory repositoryFactory = mock(RepositoryFactory.class); FlowRepository flowRepository = mock(FlowRepository.class); when(flowRepository.findInactiveFlows()) .thenReturn(Collections.singletonList(pinnedFlow)); when(repositoryFactory.createFlowRepository()).thenReturn(flowRepository); FlowPathRepository pathRepository = mock(FlowPathRepository.class); when(repositoryFactory.createFlowPathRepository()).thenReturn(pathRepository); PathSegmentRepository pathSegmentRepository = mock(PathSegmentRepository.class); when(repositoryFactory.createPathSegmentRepository()).thenReturn(pathSegmentRepository); MessageSender messageSender = mock(MessageSender.class); PersistenceManager persistenceManager = mock(PersistenceManager.class); when(persistenceManager.getRepositoryFactory()).thenReturn(repositoryFactory); when(persistenceManager.getTransactionManager()).thenReturn(transactionManager); RerouteService rerouteService = new RerouteService(persistenceManager); rerouteService.rerouteInactiveFlows(messageSender, CORRELATION_ID, REROUTE_INACTIVE_FLOWS_COMMAND); verify(pathRepository, times(0)).updateStatus(any(), any()); assertTrue(FlowStatus.DOWN.equals(pinnedFlow.getStatus())); for (FlowPath fp : pinnedFlow.getPaths()) { assertTrue(FlowPathStatus.INACTIVE.equals(fp.getStatus())); for (PathSegment ps : fp.getSegments()) { if (ps.containsNode(SWITCH_ID_A, PORT)) { assertFalse(ps.isFailed()); } else { assertTrue(ps.isFailed()); } } } }
|
RerouteService { public void rerouteAffectedFlows(MessageSender sender, String correlationId, RerouteAffectedFlows command) { PathNode pathNode = command.getPathNode(); int port = pathNode.getPortNo(); SwitchId switchId = pathNode.getSwitchId(); final IslEndpoint affectedIsl = new IslEndpoint(switchId, port); transactionManager.doInTransaction(() -> { Collection<FlowPath> affectedFlowPaths = getAffectedFlowPaths(pathNode.getSwitchId(), pathNode.getPortNo()); List<FlowPath> pathsForSwapping = getPathsForSwapping(affectedFlowPaths); for (FlowPath path : pathsForSwapping) { sender.emitPathSwapCommand(correlationId, path, command.getReason()); } for (FlowWithAffectedPaths entry : groupPathsForRerouting(affectedFlowPaths)) { Flow flow = entry.getFlow(); boolean flowPathFound = updateFlowPathsStateForFlow(switchId, port, entry.getAffectedPaths()); FlowStatus flowStatus = flow.computeFlowStatus(); String flowStatusInfo = null; if (!FlowStatus.UP.equals(flowStatus)) { flowStatusInfo = command.getReason(); } flowRepository.updateStatusSafe(flow, flowStatus, flowStatusInfo); if (flowPathFound) { FlowThrottlingData flowThrottlingData = getFlowThrottlingDataBuilder(flow) .correlationId(correlationId) .affectedIsl(Collections.singleton(affectedIsl)) .force(false) .effectivelyDown(true) .reason(command.getReason()) .build(); sender.emitRerouteCommand(flow.getFlowId(), flowThrottlingData); } } Set<Flow> affectedPinnedFlows = groupAffectedPinnedFlows(affectedFlowPaths); for (Flow flow : affectedPinnedFlows) { List<FlowPath> flowPaths = new ArrayList<>(flow.getPaths()); updateFlowPathsStateForFlow(switchId, port, flowPaths); if (flow.getStatus() != FlowStatus.DOWN) { flowDashboardLogger.onFlowStatusUpdate(flow.getFlowId(), FlowStatus.DOWN); flowRepository.updateStatusSafe(flow, FlowStatus.DOWN, command.getReason()); } } }); } RerouteService(PersistenceManager persistenceManager); void rerouteAffectedFlows(MessageSender sender, String correlationId, RerouteAffectedFlows command); void rerouteInactiveAffectedFlows(MessageSender sender, String correlationId,
SwitchId switchId); void rerouteInactiveFlows(MessageSender sender, String correlationId, RerouteInactiveFlows command); Collection<FlowPath> getAffectedFlowPaths(SwitchId switchId, int port); List<FlowPath> getPathsForSwapping(Collection<FlowPath> paths); List<FlowWithAffectedPaths> groupPathsForRerouting(Collection<FlowPath> paths); Set<Flow> groupAffectedPinnedFlows(Collection<FlowPath> paths); Map<Flow, Set<PathId>> getInactiveFlowsForRerouting(); Set<Flow> getAffectedInactiveFlowsForRerouting(SwitchId switchId); void processManualRerouteRequest(MessageSender sender, String correlationId, FlowRerouteRequest request); void processSingleSwitchFlowStatusUpdate(SwitchStateChanged request); }
|
@Test public void handlePathNoFoundException() { PathNode islSide = new PathNode(SWITCH_A.getSwitchId(), 1, 0); FlowPathRepository pathRepository = mock(FlowPathRepository.class); when(pathRepository.findBySegmentEndpoint(eq(islSide.getSwitchId()), eq(islSide.getPortNo()))) .thenReturn(Arrays.asList(regularFlow.getForwardPath(), regularFlow.getReversePath())); FlowRepository flowRepository = mock(FlowRepository.class); RepositoryFactory repositoryFactory = mock(RepositoryFactory.class); when(repositoryFactory.createPathSegmentRepository()) .thenReturn(mock(PathSegmentRepository.class)); when(repositoryFactory.createFlowPathRepository()) .thenReturn(pathRepository); when(repositoryFactory.createFlowRepository()) .thenReturn(flowRepository); PersistenceManager persistenceManager = mock(PersistenceManager.class); when(persistenceManager.getRepositoryFactory()).thenReturn(repositoryFactory); when(persistenceManager.getTransactionManager()).thenReturn(transactionManager); RerouteService rerouteService = new RerouteService(persistenceManager); RerouteAffectedFlows request = new RerouteAffectedFlows(islSide, "dummy-reason - unittest"); rerouteService.rerouteAffectedFlows(carrier, CORRELATION_ID, request); verify(flowRepository).updateStatusSafe(eq(regularFlow), eq(FlowStatus.DOWN), any()); FlowThrottlingData expected = FlowThrottlingData.builder() .correlationId(CORRELATION_ID) .priority(regularFlow.getPriority()) .timeCreate(regularFlow.getTimeCreate()) .affectedIsl(Collections.singleton(new IslEndpoint(islSide.getSwitchId(), islSide.getPortNo()))) .force(false) .effectivelyDown(true) .reason(request.getReason()) .build(); verify(carrier).emitRerouteCommand(eq(regularFlow.getFlowId()), eq(expected)); }
@Test public void shouldSkipRerouteRequestsForFlowWithoutAffectedPathSegment() { PathNode islSide = new PathNode(SWITCH_A.getSwitchId(), 1, 0); FlowPathRepository pathRepository = mock(FlowPathRepository.class); when(pathRepository.findBySegmentEndpoint(eq(islSide.getSwitchId()), eq(islSide.getPortNo()))) .thenReturn(Arrays.asList(regularFlow.getForwardPath(), regularFlow.getReversePath())); FlowRepository flowRepository = mock(FlowRepository.class); PathSegmentRepository pathSegmentRepository = mock(PathSegmentRepository.class); doThrow(new EntityNotFoundException("Not found")) .when(pathSegmentRepository).updateFailedStatus(any(), any(), anyBoolean()); RepositoryFactory repositoryFactory = mock(RepositoryFactory.class); when(repositoryFactory.createPathSegmentRepository()) .thenReturn(pathSegmentRepository); when(repositoryFactory.createFlowPathRepository()) .thenReturn(pathRepository); when(repositoryFactory.createFlowRepository()) .thenReturn(flowRepository); PersistenceManager persistenceManager = mock(PersistenceManager.class); when(persistenceManager.getRepositoryFactory()).thenReturn(repositoryFactory); when(persistenceManager.getTransactionManager()).thenReturn(transactionManager); RerouteService rerouteService = new RerouteService(persistenceManager); RerouteAffectedFlows request = new RerouteAffectedFlows(islSide, "dummy-reason - unittest"); rerouteService.rerouteAffectedFlows(carrier, CORRELATION_ID, request); verifyZeroInteractions(carrier); }
|
RerouteService { public void processSingleSwitchFlowStatusUpdate(SwitchStateChanged request) { transactionManager.doInTransaction(() -> { Collection<Flow> affectedFlows = flowRepository.findOneSwitchFlows(request.getSwitchId()); FlowStatus newFlowStatus = request.getStatus() == SwitchStatus.ACTIVE ? FlowStatus.UP : FlowStatus.DOWN; String newFlowStatusInfo = request.getStatus() == SwitchStatus.ACTIVE ? null : format("Switch %s is inactive", request.getSwitchId()); FlowPathStatus newFlowPathStatus = request.getStatus() == SwitchStatus.ACTIVE ? FlowPathStatus.ACTIVE : FlowPathStatus.INACTIVE; for (Flow flow : affectedFlows) { log.info("Updating flow and path statuses for flow {} to {}, {}", flow.getFlowId(), newFlowStatus, newFlowPathStatus); flowDashboardLogger.onFlowStatusUpdate(flow.getFlowId(), newFlowStatus); flow.setStatus(newFlowStatus); flow.setStatusInfo(newFlowStatusInfo); flow.getForwardPath().setStatus(newFlowPathStatus); flow.getReversePath().setStatus(newFlowPathStatus); } }); } RerouteService(PersistenceManager persistenceManager); void rerouteAffectedFlows(MessageSender sender, String correlationId, RerouteAffectedFlows command); void rerouteInactiveAffectedFlows(MessageSender sender, String correlationId,
SwitchId switchId); void rerouteInactiveFlows(MessageSender sender, String correlationId, RerouteInactiveFlows command); Collection<FlowPath> getAffectedFlowPaths(SwitchId switchId, int port); List<FlowPath> getPathsForSwapping(Collection<FlowPath> paths); List<FlowWithAffectedPaths> groupPathsForRerouting(Collection<FlowPath> paths); Set<Flow> groupAffectedPinnedFlows(Collection<FlowPath> paths); Map<Flow, Set<PathId>> getInactiveFlowsForRerouting(); Set<Flow> getAffectedInactiveFlowsForRerouting(SwitchId switchId); void processManualRerouteRequest(MessageSender sender, String correlationId, FlowRerouteRequest request); void processSingleSwitchFlowStatusUpdate(SwitchStateChanged request); }
|
@Test public void handleUpdateSingleSwitchFlows() { FlowRepository flowRepository = mock(FlowRepository.class); when(flowRepository.findOneSwitchFlows(oneSwitchFlow.getSrcSwitch().getSwitchId())) .thenReturn(Arrays.asList(oneSwitchFlow)); FlowPathRepository flowPathRepository = mock(FlowPathRepository.class); RepositoryFactory repositoryFactory = mock(RepositoryFactory.class); when(repositoryFactory.createFlowRepository()) .thenReturn(flowRepository); when(repositoryFactory.createFlowPathRepository()) .thenReturn(flowPathRepository); PersistenceManager persistenceManager = mock(PersistenceManager.class); when(persistenceManager.getRepositoryFactory()).thenReturn(repositoryFactory); when(persistenceManager.getTransactionManager()).thenReturn(transactionManager); RerouteService rerouteService = new RerouteService(persistenceManager); rerouteService.processSingleSwitchFlowStatusUpdate( new SwitchStateChanged(oneSwitchFlow.getSrcSwitchId(), SwitchStatus.INACTIVE)); assertEquals(format("Switch %s is inactive", oneSwitchFlow.getSrcSwitchId()), FlowStatus.DOWN, oneSwitchFlow.getStatus()); }
|
RerouteService { public void rerouteInactiveAffectedFlows(MessageSender sender, String correlationId, SwitchId switchId) { Set<Flow> flowsForRerouting = getAffectedInactiveFlowsForRerouting(switchId); for (Flow flow : flowsForRerouting) { if (flow.isPinned()) { log.info("Skipping reroute command for pinned flow {}", flow.getFlowId()); } else { log.info("Produce reroute (attempt to restore inactive flow) request for {} (switch online {})", flow.getFlowId(), switchId); FlowThrottlingData flowThrottlingData = getFlowThrottlingDataBuilder(flow) .correlationId(correlationId) .affectedIsl(Collections.emptySet()) .force(false) .effectivelyDown(true) .reason(format("Switch '%s' online", switchId)) .build(); sender.emitRerouteCommand(flow.getFlowId(), flowThrottlingData); } } } RerouteService(PersistenceManager persistenceManager); void rerouteAffectedFlows(MessageSender sender, String correlationId, RerouteAffectedFlows command); void rerouteInactiveAffectedFlows(MessageSender sender, String correlationId,
SwitchId switchId); void rerouteInactiveFlows(MessageSender sender, String correlationId, RerouteInactiveFlows command); Collection<FlowPath> getAffectedFlowPaths(SwitchId switchId, int port); List<FlowPath> getPathsForSwapping(Collection<FlowPath> paths); List<FlowWithAffectedPaths> groupPathsForRerouting(Collection<FlowPath> paths); Set<Flow> groupAffectedPinnedFlows(Collection<FlowPath> paths); Map<Flow, Set<PathId>> getInactiveFlowsForRerouting(); Set<Flow> getAffectedInactiveFlowsForRerouting(SwitchId switchId); void processManualRerouteRequest(MessageSender sender, String correlationId, FlowRerouteRequest request); void processSingleSwitchFlowStatusUpdate(SwitchStateChanged request); }
|
@Test public void handleRerouteInactiveAffectedFlows() { FlowPathRepository pathRepository = mock(FlowPathRepository.class); when(pathRepository.findInactiveBySegmentSwitch(regularFlow.getSrcSwitchId())) .thenReturn(Arrays.asList(regularFlow.getForwardPath(), regularFlow.getReversePath())); RepositoryFactory repositoryFactory = mock(RepositoryFactory.class); when(repositoryFactory.createFlowPathRepository()) .thenReturn(pathRepository); PersistenceManager persistenceManager = mock(PersistenceManager.class); when(persistenceManager.getRepositoryFactory()).thenReturn(repositoryFactory); when(persistenceManager.getTransactionManager()).thenReturn(transactionManager); RerouteService rerouteService = new RerouteService(persistenceManager); regularFlow.setStatus(FlowStatus.DOWN); rerouteService.rerouteInactiveAffectedFlows(carrier, CORRELATION_ID, regularFlow.getSrcSwitchId()); FlowThrottlingData expected = FlowThrottlingData.builder() .correlationId(CORRELATION_ID) .priority(regularFlow.getPriority()) .timeCreate(regularFlow.getTimeCreate()) .affectedIsl(Collections.emptySet()) .force(false) .effectivelyDown(true) .reason(format("Switch '%s' online", regularFlow.getSrcSwitchId())) .build(); verify(carrier).emitRerouteCommand(eq(regularFlow.getFlowId()), eq(expected)); regularFlow.setStatus(FlowStatus.UP); }
|
RerouteService { public void processManualRerouteRequest(MessageSender sender, String correlationId, FlowRerouteRequest request) { Optional<Flow> flow = flowRepository.findById(request.getFlowId()); FlowThrottlingData flowThrottlingData = getFlowThrottlingDataBuilder(flow.orElse(null)) .correlationId(correlationId) .affectedIsl(request.getAffectedIsl()) .force(request.isForce()) .effectivelyDown(request.isEffectivelyDown()) .reason(request.getReason()) .build(); sender.emitManualRerouteCommand(request.getFlowId(), flowThrottlingData); } RerouteService(PersistenceManager persistenceManager); void rerouteAffectedFlows(MessageSender sender, String correlationId, RerouteAffectedFlows command); void rerouteInactiveAffectedFlows(MessageSender sender, String correlationId,
SwitchId switchId); void rerouteInactiveFlows(MessageSender sender, String correlationId, RerouteInactiveFlows command); Collection<FlowPath> getAffectedFlowPaths(SwitchId switchId, int port); List<FlowPath> getPathsForSwapping(Collection<FlowPath> paths); List<FlowWithAffectedPaths> groupPathsForRerouting(Collection<FlowPath> paths); Set<Flow> groupAffectedPinnedFlows(Collection<FlowPath> paths); Map<Flow, Set<PathId>> getInactiveFlowsForRerouting(); Set<Flow> getAffectedInactiveFlowsForRerouting(SwitchId switchId); void processManualRerouteRequest(MessageSender sender, String correlationId, FlowRerouteRequest request); void processSingleSwitchFlowStatusUpdate(SwitchStateChanged request); }
|
@Test public void processManualRerouteRequest() { FlowRepository flowRepository = mock(FlowRepository.class); when(flowRepository.findById(regularFlow.getFlowId())) .thenReturn(Optional.of(regularFlow)); RepositoryFactory repositoryFactory = mock(RepositoryFactory.class); when(repositoryFactory.createFlowRepository()) .thenReturn(flowRepository); PersistenceManager persistenceManager = mock(PersistenceManager.class); when(persistenceManager.getRepositoryFactory()).thenReturn(repositoryFactory); when(persistenceManager.getTransactionManager()).thenReturn(transactionManager); RerouteService rerouteService = new RerouteService(persistenceManager); FlowRerouteRequest request = new FlowRerouteRequest(regularFlow.getFlowId(), true, true, false, Collections.emptySet(), "reason"); rerouteService.processManualRerouteRequest(carrier, CORRELATION_ID, request); FlowThrottlingData expected = FlowThrottlingData.builder() .correlationId(CORRELATION_ID) .priority(regularFlow.getPriority()) .timeCreate(regularFlow.getTimeCreate()) .affectedIsl(Collections.emptySet()) .force(true) .effectivelyDown(true) .reason("reason") .build(); verify(carrier).emitManualRerouteCommand(eq(regularFlow.getFlowId()), eq(expected)); }
|
ExtendableTimeWindow { public boolean flushIfReady() { if (firstEventTime == null) { return false; } LocalDateTime now = LocalDateTime.now(clock); boolean isTimeToFlush = lastEventTime.plus(minDelay, ChronoUnit.SECONDS).isBefore(now) || firstEventTime.plus(maxDelay, ChronoUnit.SECONDS).isBefore(now); if (isTimeToFlush) { firstEventTime = null; lastEventTime = null; } return isTimeToFlush; } ExtendableTimeWindow(long minDelay, long maxDelay); ExtendableTimeWindow(long minDelay, long maxDelay, Clock clock); void registerEvent(); boolean flushIfReady(); }
|
@Test public void noFlushEmptyWindow() { assertFalse(extendableTimeWindow.flushIfReady()); }
@Test public void noFlushEmptyWindow2() { when(clock.instant()).thenReturn(Instant.now()); assertFalse(extendableTimeWindow.flushIfReady()); }
|
NetworkUniIslService { public void uniIslSetup(Endpoint endpoint, Isl history) { log.info("Uni-ISL service receive SETUP request for {}", endpoint); IslReference reference; if (history != null) { reference = IslReference.of(history); carrier.setupIslFromHistory(endpoint, reference, history); } else { reference = IslReference.of(endpoint); } endpointData.put(endpoint, reference); } NetworkUniIslService(IUniIslCarrier carrier); void uniIslSetup(Endpoint endpoint, Isl history); void uniIslDiscovery(Endpoint endpoint, IslInfoData speakerDiscoveryEvent); void uniIslFail(Endpoint endpoint); void uniIslPhysicalDown(Endpoint endpoint); void roundTripStatusNotification(RoundTripStatus status); void uniIslBfdStatusUpdate(Endpoint endpoint, BfdStatusUpdate status); void uniIslRemove(Endpoint endpoint); void islRemovedNotification(Endpoint endpoint, IslReference removedIsl); }
|
@Test public void newIslWithHistory() { NetworkUniIslService service = new NetworkUniIslService(carrier); Endpoint endpoint1 = Endpoint.of(alphaDatapath, 1); Endpoint endpoint2 = Endpoint.of(alphaDatapath, 2); Switch alphaSwitch = Switch.builder().switchId(alphaDatapath).build(); Switch betaSwitch = Switch.builder().switchId(betaDatapath).build(); Isl islAtoB = Isl.builder() .srcSwitch(alphaSwitch) .srcPort(1) .destSwitch(betaSwitch) .destPort(1).build(); Isl islAtoB2 = Isl.builder() .srcSwitch(alphaSwitch) .srcPort(2) .destSwitch(betaSwitch) .destPort(2).build(); service.uniIslSetup(endpoint1, islAtoB); service.uniIslSetup(endpoint2, islAtoB2); verify(carrier).setupIslFromHistory(endpoint1, IslReference.of(islAtoB), islAtoB); verify(carrier).setupIslFromHistory(endpoint2, IslReference.of(islAtoB2), islAtoB2); }
|
NetworkSwitchService { public void switchEvent(SwitchInfoData payload) { log.info("Switch service receive SWITCH event for {} status:{}", payload.getSwitchId(), payload.getState()); SwitchFsmContext.SwitchFsmContextBuilder fsmContextBuilder = SwitchFsmContext.builder(carrier); SwitchFsmEvent event = null; switch (payload.getState()) { case ACTIVATED: event = SwitchFsmEvent.ONLINE; fsmContextBuilder.speakerData(payload.getSwitchView()); break; case DEACTIVATED: event = SwitchFsmEvent.OFFLINE; break; default: log.info("Ignore switch event {} on {} (no need to handle it)", payload.getState(), payload.getSwitchId()); break; } if (event != null) { SwitchFsm fsm = locateControllerCreateIfAbsent(payload.getSwitchId()); controllerExecutor.fire(fsm, event, fsmContextBuilder.build()); } } NetworkSwitchService(ISwitchCarrier carrier, PersistenceManager persistenceManager,
NetworkOptions options); void switchAddWithHistory(HistoryFacts history); void switchEvent(SwitchInfoData payload); void switchManagerResponse(SwitchSyncResponse payload, String key); void switchManagerErrorResponse(SwitchSyncErrorData payload, String key); void switchManagerTimeout(SwitchId switchId, String key); void switchBecomeUnmanaged(SwitchId datapath); void switchBecomeManaged(SpeakerSwitchView switchView); void switchPortEvent(PortInfoData payload); void remove(SwitchId datapath); }
|
@Test public void newSwitch() { List<SpeakerSwitchPortView> ports = getSpeakerSwitchPortViews(); SpeakerSwitchView speakerSwitchView = getSpeakerSwitchView().toBuilder() .ports(ports) .build(); SwitchInfoData switchAddEvent = new SwitchInfoData( alphaDatapath, SwitchChangeType.ACTIVATED, alphaInetAddress.toString(), alphaInetAddress.toString(), alphaDescription, speakerInetAddress.toString(), false, speakerSwitchView); NetworkSwitchService service = new NetworkSwitchService(carrier, persistenceManager, options); service.switchEvent(switchAddEvent); verifySwitchSync(service); verifyNewSwitchAfterSwitchSync(ports); }
@Test public void switchFromOnlineToOffline() { List<SpeakerSwitchPortView> ports = getSpeakerSwitchPortViews(); SpeakerSwitchView speakerSwitchView = getSpeakerSwitchView().toBuilder() .ports(ports) .build(); SwitchInfoData switchAddEvent = new SwitchInfoData( alphaDatapath, SwitchChangeType.ACTIVATED, alphaInetAddress.toString(), alphaInetAddress.toString(), alphaDescription, speakerInetAddress.toString(), false, speakerSwitchView); NetworkSwitchService service = new NetworkSwitchService(carrier, persistenceManager, options); service.switchEvent(switchAddEvent); verifySwitchSync(service); resetMocks(); when(switchRepository.findById(alphaDatapath)).thenReturn( Optional.of(Switch.builder().switchId(alphaDatapath) .build())); SwitchInfoData deactivatedSwitch = switchAddEvent.toBuilder().state(SwitchChangeType.DEACTIVATED).build(); service.switchEvent(deactivatedSwitch); verify(carrier).setOnlineMode(Endpoint.of(alphaDatapath, ports.get(0).getNumber()), OnlineStatus.OFFLINE); verify(carrier).setBfdPortOnlineMode(Endpoint.of(alphaDatapath, ports.get(1).getNumber()), false); verify(carrier).setOnlineMode(Endpoint.of(alphaDatapath, ports.get(2).getNumber()), OnlineStatus.OFFLINE); verify(carrier).setBfdPortOnlineMode(Endpoint.of(alphaDatapath, ports.get(3).getNumber()), false); }
@Test public void switchFromOnlineToOfflineToOnline() { List<SpeakerSwitchPortView> ports = getSpeakerSwitchPortViews(); SpeakerSwitchView speakerSwitchView = getSpeakerSwitchView().toBuilder() .ports(ports) .build(); SwitchInfoData switchAddEvent = new SwitchInfoData( alphaDatapath, SwitchChangeType.ACTIVATED, alphaInetAddress.toString(), alphaInetAddress.toString(), alphaDescription, speakerInetAddress.toString(), false, speakerSwitchView); NetworkSwitchService service = new NetworkSwitchService(carrier, persistenceManager, options); service.switchEvent(switchAddEvent); verifySwitchSync(service); SwitchInfoData deactivatedSwitch = switchAddEvent.toBuilder().state(SwitchChangeType.DEACTIVATED).build(); service.switchEvent(deactivatedSwitch); List<SpeakerSwitchPortView> ports2 = getSpeakerSwitchPortViewsRevert(); SpeakerSwitchView speakerSwitchView2 = getSpeakerSwitchView().toBuilder() .ports(ports2) .build(); SwitchInfoData switchAddEvent2 = new SwitchInfoData( alphaDatapath, SwitchChangeType.ACTIVATED, alphaInetAddress.toString(), alphaInetAddress.toString(), alphaDescription, speakerInetAddress.toString(), false, speakerSwitchView2); resetMocks(); service.switchEvent(switchAddEvent2); verifySwitchSync(service); verify(carrier).setOnlineMode(Endpoint.of(alphaDatapath, ports.get(0).getNumber()), OnlineStatus.ONLINE); verify(carrier).setBfdPortOnlineMode(Endpoint.of(alphaDatapath, ports.get(1).getNumber()), true); verify(carrier).setOnlineMode(Endpoint.of(alphaDatapath, ports.get(2).getNumber()), OnlineStatus.ONLINE); verify(carrier).setBfdPortOnlineMode(Endpoint.of(alphaDatapath, ports.get(3).getNumber()), true); verify(carrier).setPortLinkMode(Endpoint.of(alphaDatapath, ports2.get(2).getNumber()), LinkStatus.of(ports2.get(2).getState())); verify(carrier).setBfdPortLinkMode(Endpoint.of(alphaDatapath, ports2.get(3).getNumber()), LinkStatus.of(ports2.get(3).getState())); verify(carrier).setPortLinkMode(Endpoint.of(alphaDatapath, ports2.get(0).getNumber()), LinkStatus.of(ports2.get(0).getState())); verify(carrier).setBfdPortLinkMode(Endpoint.of(alphaDatapath, ports2.get(1).getNumber()), LinkStatus.of(ports2.get(0).getState())); verify(carrier).sendAffectedFlowRerouteRequest(alphaDatapath); }
@Test public void switchWithNoBfdSupport() { List<SpeakerSwitchPortView> ports = getSpeakerSwitchPortViews(); SpeakerSwitchView speakerSwitchView = getSpeakerSwitchView().toBuilder() .ports(ports) .features(Collections.emptySet()) .build(); SwitchInfoData switchAddEvent = new SwitchInfoData( alphaDatapath, SwitchChangeType.ACTIVATED, alphaInetAddress.toString(), alphaInetAddress.toString(), alphaDescription, speakerInetAddress.toString(), false, speakerSwitchView); NetworkSwitchService service = new NetworkSwitchService(carrier, persistenceManager, options); service.switchEvent(switchAddEvent); verifySwitchSync(service); verify(carrier).setupPortHandler(Endpoint.of(alphaDatapath, ports.get(0).getNumber()), null); verify(carrier).setupPortHandler(Endpoint.of(alphaDatapath, ports.get(1).getNumber()), null); verify(carrier).setupPortHandler(Endpoint.of(alphaDatapath, ports.get(2).getNumber()), null); verify(carrier).setupPortHandler(Endpoint.of(alphaDatapath, ports.get(3).getNumber()), null); verify(carrier).setOnlineMode(Endpoint.of(alphaDatapath, ports.get(0).getNumber()), OnlineStatus.ONLINE); verify(carrier).setOnlineMode(Endpoint.of(alphaDatapath, ports.get(1).getNumber()), OnlineStatus.ONLINE); verify(carrier).setOnlineMode(Endpoint.of(alphaDatapath, ports.get(2).getNumber()), OnlineStatus.ONLINE); verify(carrier).setOnlineMode(Endpoint.of(alphaDatapath, ports.get(3).getNumber()), OnlineStatus.ONLINE); verify(carrier).setPortLinkMode(Endpoint.of(alphaDatapath, ports.get(2).getNumber()), LinkStatus.of(ports.get(2).getState())); verify(carrier).setPortLinkMode(Endpoint.of(alphaDatapath, ports.get(3).getNumber()), LinkStatus.of(ports.get(3).getState())); verify(carrier).setPortLinkMode(Endpoint.of(alphaDatapath, ports.get(0).getNumber()), LinkStatus.of(ports.get(0).getState())); verify(carrier).setPortLinkMode(Endpoint.of(alphaDatapath, ports.get(1).getNumber()), LinkStatus.of(ports.get(0).getState())); }
|
NetworkSwitchService { public void switchAddWithHistory(HistoryFacts history) { log.info("Switch service receive switch ADD from history request for {}", history.getSwitchId()); SwitchFsm switchFsm = controllerFactory.produce(persistenceManager, history.getSwitchId(), options); SwitchFsmContext fsmContext = SwitchFsmContext.builder(carrier) .history(history) .build(); controller.put(history.getSwitchId(), switchFsm); controllerExecutor.fire(switchFsm, SwitchFsmEvent.HISTORY, fsmContext); } NetworkSwitchService(ISwitchCarrier carrier, PersistenceManager persistenceManager,
NetworkOptions options); void switchAddWithHistory(HistoryFacts history); void switchEvent(SwitchInfoData payload); void switchManagerResponse(SwitchSyncResponse payload, String key); void switchManagerErrorResponse(SwitchSyncErrorData payload, String key); void switchManagerTimeout(SwitchId switchId, String key); void switchBecomeUnmanaged(SwitchId datapath); void switchBecomeManaged(SpeakerSwitchView switchView); void switchPortEvent(PortInfoData payload); void remove(SwitchId datapath); }
|
@Test public void switchFromHistoryToOffline() { when(switchRepository.findById(alphaDatapath)).thenReturn( Optional.of(Switch.builder().switchId(alphaDatapath) .build())); HistoryFacts history = new HistoryFacts(alphaDatapath); Switch alphaSwitch = Switch.builder().switchId(alphaDatapath).build(); Switch betaSwitch = Switch.builder().switchId(betaDatapath).build(); Isl islAtoB = Isl.builder() .srcSwitch(alphaSwitch) .srcPort(1) .destSwitch(betaSwitch) .destPort(1).build(); Isl islAtoB2 = Isl.builder() .srcSwitch(alphaSwitch) .srcPort(2) .destSwitch(betaSwitch) .destPort(2).build(); history.addLink(islAtoB); history.addLink(islAtoB2); NetworkSwitchService service = new NetworkSwitchService(carrier, persistenceManager, options); service.switchAddWithHistory(history); verify(carrier).setupPortHandler(Endpoint.of(alphaDatapath, 1), islAtoB); verify(carrier).setupPortHandler(Endpoint.of(alphaDatapath, 2), islAtoB2); verify(carrier).setOnlineMode(Endpoint.of(alphaDatapath, 1), OnlineStatus.OFFLINE); verify(carrier).setOnlineMode(Endpoint.of(alphaDatapath, 2), OnlineStatus.OFFLINE); }
|
NetworkSwitchService { public void switchBecomeManaged(SpeakerSwitchView switchView) { log.debug("Switch service receive MANAGED notification for {}", switchView.getDatapath()); SwitchFsm fsm = locateControllerCreateIfAbsent(switchView.getDatapath()); SwitchFsmContext context = SwitchFsmContext.builder(carrier) .speakerData(switchView) .build(); controllerExecutor.fire(fsm, SwitchFsmEvent.ONLINE, context); } NetworkSwitchService(ISwitchCarrier carrier, PersistenceManager persistenceManager,
NetworkOptions options); void switchAddWithHistory(HistoryFacts history); void switchEvent(SwitchInfoData payload); void switchManagerResponse(SwitchSyncResponse payload, String key); void switchManagerErrorResponse(SwitchSyncErrorData payload, String key); void switchManagerTimeout(SwitchId switchId, String key); void switchBecomeUnmanaged(SwitchId datapath); void switchBecomeManaged(SpeakerSwitchView switchView); void switchPortEvent(PortInfoData payload); void remove(SwitchId datapath); }
|
@Test public void switchFromOnlineToOnlineWithLostBfdFeature() { NetworkSwitchService service = new NetworkSwitchService(carrier, persistenceManager, options); List<SpeakerSwitchPortView> ports = doSpeakerOnline(service, Collections.singleton(SwitchFeature.BFD)); List<SpeakerSwitchPortView> ports2 = swapBfdPortsState(ports); resetMocks(); service.switchBecomeManaged(getSpeakerSwitchView().toBuilder() .features(Collections.emptySet()) .ports(ports2) .build()); verify(carrier).removeBfdPortHandler(Endpoint.of(alphaDatapath, 1 + BFD_LOGICAL_PORT_OFFSET)); verify(carrier).setupPortHandler(Endpoint.of(alphaDatapath, 1 + BFD_LOGICAL_PORT_OFFSET), null); verify(carrier).setOnlineMode(Endpoint.of(alphaDatapath, 1 + BFD_LOGICAL_PORT_OFFSET), OnlineStatus.ONLINE); verify(carrier).setPortLinkMode(Endpoint.of(alphaDatapath, 1 + BFD_LOGICAL_PORT_OFFSET), LinkStatus.DOWN); verify(carrier).removeBfdPortHandler(Endpoint.of(alphaDatapath, 2 + BFD_LOGICAL_PORT_OFFSET)); verify(carrier).setupPortHandler(Endpoint.of(alphaDatapath, 2 + BFD_LOGICAL_PORT_OFFSET), null); verify(carrier).setOnlineMode(Endpoint.of(alphaDatapath, 2 + BFD_LOGICAL_PORT_OFFSET), OnlineStatus.ONLINE); verify(carrier).setPortLinkMode(Endpoint.of(alphaDatapath, 2 + BFD_LOGICAL_PORT_OFFSET), LinkStatus.UP); }
@Test public void switchFromOnlineToOnlineWithAcquireBfdFeature() { NetworkSwitchService service = new NetworkSwitchService(carrier, persistenceManager, options); List<SpeakerSwitchPortView> ports = doSpeakerOnline(service, Collections.emptySet()); List<SpeakerSwitchPortView> ports2 = swapBfdPortsState(ports); resetMocks(); service.switchBecomeManaged(getSpeakerSwitchView().toBuilder() .features(Collections.singleton(SwitchFeature.BFD)) .ports(ports2) .build()); verify(carrier).removePortHandler(Endpoint.of(alphaDatapath, 1 + BFD_LOGICAL_PORT_OFFSET)); verify(carrier).setupBfdPortHandler(Endpoint.of(alphaDatapath, 1 + BFD_LOGICAL_PORT_OFFSET), 1); verify(carrier).setBfdPortOnlineMode(Endpoint.of(alphaDatapath, 1 + BFD_LOGICAL_PORT_OFFSET), true); verify(carrier).setBfdPortLinkMode(Endpoint.of(alphaDatapath, 1 + BFD_LOGICAL_PORT_OFFSET), LinkStatus.DOWN); verify(carrier).removePortHandler(Endpoint.of(alphaDatapath, 2 + BFD_LOGICAL_PORT_OFFSET)); verify(carrier).setupBfdPortHandler(Endpoint.of(alphaDatapath, 2 + BFD_LOGICAL_PORT_OFFSET), 2); verify(carrier).setBfdPortOnlineMode(Endpoint.of(alphaDatapath, 2 + BFD_LOGICAL_PORT_OFFSET), true); verify(carrier).setBfdPortLinkMode(Endpoint.of(alphaDatapath, 2 + BFD_LOGICAL_PORT_OFFSET), LinkStatus.UP); }
|
NetworkIslService { public void islUp(Endpoint endpoint, IslReference reference, IslDataHolder islData) { log.debug("ISL service receive DISCOVERY notification for {} (on {})", reference, endpoint); IslFsm islFsm = locateControllerCreateIfAbsent(endpoint, reference).fsm; IslFsmContext context = IslFsmContext.builder(carrier, endpoint) .islData(islData) .build(); controllerExecutor.fire(islFsm, IslFsmEvent.ISL_UP, context); } NetworkIslService(IIslCarrier carrier, PersistenceManager persistenceManager, NetworkOptions options); @VisibleForTesting NetworkIslService(IIslCarrier carrier, PersistenceManager persistenceManager, NetworkOptions options,
NetworkTopologyDashboardLogger.Builder dashboardLoggerBuilder, Clock clock); void islSetupFromHistory(Endpoint endpoint, IslReference reference, Isl history); void islUp(Endpoint endpoint, IslReference reference, IslDataHolder islData); void islDown(Endpoint endpoint, IslReference reference, IslDownReason reason); void islMove(Endpoint endpoint, IslReference reference); void roundTripStatusNotification(IslReference reference, RoundTripStatus status); void bfdStatusUpdate(Endpoint endpoint, IslReference reference, BfdStatusUpdate status); void bfdEnableDisable(IslReference reference, IslBfdFlagUpdated payload); void islDefaultRuleInstalled(IslReference reference, InstallIslDefaultRulesResult payload); void islDefaultRuleDeleted(IslReference reference, RemoveIslDefaultRulesResult payload); void islDefaultTimeout(IslReference reference, Endpoint endpoint); void remove(IslReference reference); }
|
@Test @Ignore("incomplete") public void initialUp() { persistenceManager = new InMemoryGraphPersistenceManager( new PropertiesBasedConfigurationProvider().getConfiguration(NetworkConfig.class)); emulateEmptyPersistentDb(); SwitchRepository switchRepository = persistenceManager.getRepositoryFactory() .createSwitchRepository(); Switch swA = Switch.builder() .switchId(endpointAlpha1.getDatapath()) .description("alpha") .build(); switchRepository.add(swA); switchPropertiesRepository.add(SwitchProperties.builder() .multiTable(false) .supportedTransitEncapsulation(SwitchProperties.DEFAULT_FLOW_ENCAPSULATION_TYPES) .switchObj(swA).build()); Switch swB = Switch.builder() .switchId(endpointBeta2.getDatapath()) .description("alpha") .build(); switchRepository.add(swB); switchPropertiesRepository.add(SwitchProperties.builder() .multiTable(false) .supportedTransitEncapsulation(SwitchProperties.DEFAULT_FLOW_ENCAPSULATION_TYPES) .switchObj(swB).build()); IslReference ref = new IslReference(endpointAlpha1, endpointBeta2); IslDataHolder islData = new IslDataHolder(1000, 1000, 1000); service = new NetworkIslService(carrier, persistenceManager, options); service.islUp(ref.getSource(), ref, islData); System.out.println(mockingDetails(carrier).printInvocations()); System.out.println(mockingDetails(islRepository).printInvocations()); }
@Test public void repeatOnTransientDbErrors() { mockPersistenceIsl(endpointAlpha1, endpointBeta2, null); mockPersistenceIsl(endpointBeta2, endpointAlpha1, null); mockPersistenceLinkProps(endpointAlpha1, endpointBeta2, null); mockPersistenceLinkProps(endpointBeta2, endpointAlpha1, null); mockPersistenceBandwidthAllocation(endpointAlpha1, endpointBeta2, 0); mockPersistenceBandwidthAllocation(endpointBeta2, endpointAlpha1, 0); IslReference reference = new IslReference(endpointAlpha1, endpointBeta2); service.islUp(endpointAlpha1, reference, new IslDataHolder(100, 1, 100)); assertEquals(new SwitchId(1), endpointAlpha1.getDatapath()); assertEquals(1, endpointAlpha1.getPortNumber()); }
@Test public void considerLinkPropsDataOnCreate() { setupIslStorageStub(); mockPersistenceLinkProps(endpointAlpha1, endpointBeta2, makeLinkProps(endpointAlpha1, endpointBeta2) .maxBandwidth(50L) .build()); mockPersistenceLinkProps(endpointBeta2, endpointAlpha1, null); mockPersistenceBandwidthAllocation(endpointAlpha1, endpointBeta2, 0L); mockPersistenceBandwidthAllocation(endpointBeta2, endpointAlpha1, 0L); IslReference reference = new IslReference(endpointAlpha1, endpointBeta2); service.islUp(endpointAlpha1, reference, new IslDataHolder(200L, 200L, 200L)); service.islUp(endpointBeta2, reference, new IslDataHolder(200L, 200L, 200L)); verifyIslBandwidthUpdate(50L, 200L); }
|
NetworkIslService { public void islMove(Endpoint endpoint, IslReference reference) { log.debug("ISL service receive MOVED(FAIL) notification for {} (on {})", reference, endpoint); IslFsm islFsm = locateController(reference).fsm; IslFsmContext context = IslFsmContext.builder(carrier, endpoint).build(); controllerExecutor.fire(islFsm, IslFsmEvent.ISL_MOVE, context); } NetworkIslService(IIslCarrier carrier, PersistenceManager persistenceManager, NetworkOptions options); @VisibleForTesting NetworkIslService(IIslCarrier carrier, PersistenceManager persistenceManager, NetworkOptions options,
NetworkTopologyDashboardLogger.Builder dashboardLoggerBuilder, Clock clock); void islSetupFromHistory(Endpoint endpoint, IslReference reference, Isl history); void islUp(Endpoint endpoint, IslReference reference, IslDataHolder islData); void islDown(Endpoint endpoint, IslReference reference, IslDownReason reason); void islMove(Endpoint endpoint, IslReference reference); void roundTripStatusNotification(IslReference reference, RoundTripStatus status); void bfdStatusUpdate(Endpoint endpoint, IslReference reference, BfdStatusUpdate status); void bfdEnableDisable(IslReference reference, IslBfdFlagUpdated payload); void islDefaultRuleInstalled(IslReference reference, InstallIslDefaultRulesResult payload); void islDefaultRuleDeleted(IslReference reference, RemoveIslDefaultRulesResult payload); void islDefaultTimeout(IslReference reference, Endpoint endpoint); void remove(IslReference reference); }
|
@Test @Ignore("become invalid due to change initialisation logic") public void initialMoveEvent() { emulateEmptyPersistentDb(); IslReference ref = new IslReference(endpointAlpha1, endpointBeta2); service.islMove(ref.getSource(), ref); verify(carrier, times(2)).triggerReroute(any(RerouteAffectedFlows.class)); verify(islRepository).add(argThat( link -> link.getSrcSwitchId().equals(endpointAlpha1.getDatapath()) && link.getSrcPort() == endpointAlpha1.getPortNumber() && link.getDestSwitchId().equals(endpointBeta2.getDatapath()) && link.getDestPort() == endpointBeta2.getPortNumber() && link.getActualStatus() == IslStatus.INACTIVE && link.getStatus() == IslStatus.INACTIVE)); verify(islRepository).add(argThat( link -> link.getSrcSwitchId().equals(endpointBeta2.getDatapath()) && link.getSrcPort() == endpointBeta2.getPortNumber() && link.getDestSwitchId().equals(endpointAlpha1.getDatapath()) && link.getDestPort() == endpointAlpha1.getPortNumber() && link.getActualStatus() == IslStatus.INACTIVE && link.getStatus() == IslStatus.INACTIVE)); verifyNoMoreInteractions(carrier); }
|
NetworkIslService { public void islDown(Endpoint endpoint, IslReference reference, IslDownReason reason) { log.debug("ISL service receive FAIL notification for {} (on {})", reference, endpoint); IslFsm islFsm = locateController(reference).fsm; IslFsmContext context = IslFsmContext.builder(carrier, endpoint) .downReason(reason) .build(); controllerExecutor.fire(islFsm, IslFsmEvent.ISL_DOWN, context); } NetworkIslService(IIslCarrier carrier, PersistenceManager persistenceManager, NetworkOptions options); @VisibleForTesting NetworkIslService(IIslCarrier carrier, PersistenceManager persistenceManager, NetworkOptions options,
NetworkTopologyDashboardLogger.Builder dashboardLoggerBuilder, Clock clock); void islSetupFromHistory(Endpoint endpoint, IslReference reference, Isl history); void islUp(Endpoint endpoint, IslReference reference, IslDataHolder islData); void islDown(Endpoint endpoint, IslReference reference, IslDownReason reason); void islMove(Endpoint endpoint, IslReference reference); void roundTripStatusNotification(IslReference reference, RoundTripStatus status); void bfdStatusUpdate(Endpoint endpoint, IslReference reference, BfdStatusUpdate status); void bfdEnableDisable(IslReference reference, IslBfdFlagUpdated payload); void islDefaultRuleInstalled(IslReference reference, InstallIslDefaultRulesResult payload); void islDefaultRuleDeleted(IslReference reference, RemoveIslDefaultRulesResult payload); void islDefaultTimeout(IslReference reference, Endpoint endpoint); void remove(IslReference reference); }
|
@Test public void setIslUnstableTimeOnPortDown() { setupIslStorageStub(); IslReference reference = prepareActiveIsl(); Instant updateTime = clock.adjust(Duration.ofSeconds(1)); service.islDown(endpointAlpha1, reference, IslDownReason.PORT_DOWN); Isl forward = lookupIsl(reference.getSource(), reference.getDest()); Assert.assertEquals(updateTime, forward.getTimeUnstable()); Isl reverse = lookupIsl(reference.getDest(), reference.getSource()); Assert.assertEquals(updateTime, reverse.getTimeUnstable()); }
@Test public void portDownOverriderBfdUp() { setupIslStorageStub(); IslReference reference = prepareBfdEnabledIsl(); reset(dashboardLogger); service.islDown(reference.getSource(), reference, IslDownReason.PORT_DOWN); verify(dashboardLogger).onIslDown(reference); }
|
NetworkBfdPortService { public void updateLinkStatus(Endpoint logicalEndpoint, LinkStatus linkStatus) { log.debug("BFD-port service receive logical port status update for {} (logical) status:{}", logicalEndpoint, linkStatus); BfdPortFsm controller = lookupControllerByLogicalEndpoint(logicalEndpoint); controller.updateLinkStatus(carrier, linkStatus); } NetworkBfdPortService(IBfdPortCarrier carrier, PersistenceManager persistenceManager); void setup(Endpoint endpoint, int physicalPortNumber); Endpoint remove(Endpoint logicalEndpoint); void updateLinkStatus(Endpoint logicalEndpoint, LinkStatus linkStatus); void updateOnlineMode(Endpoint endpoint, boolean mode); void enable(Endpoint physicalEndpoint, IslReference reference); void disable(Endpoint physicalEndpoint); void speakerResponse(String key, Endpoint logicalEndpoint, BfdSessionResponse response); void speakerTimeout(String key, Endpoint logicalEndpoint); }
|
@Test public void upDownUp() { setupAndEnable(); service.updateLinkStatus(alphaLogicalEndpoint, LinkStatus.DOWN); verify(carrier).bfdDownNotification(alphaEndpoint); verifyNoMoreInteractions(carrier); reset(carrier); service.updateLinkStatus(alphaLogicalEndpoint, LinkStatus.UP); verify(carrier).bfdUpNotification(alphaEndpoint); verifyNoMoreInteractions(carrier); }
|
NetworkBfdPortService { public Endpoint remove(Endpoint logicalEndpoint) { log.info("BFD-port service receive REMOVE request for {} (logical)", logicalEndpoint); BfdPortFsm controller = controllerByLogicalPort.remove(logicalEndpoint); if (controller == null) { throw BfdPortControllerNotFoundException.ofLogical(logicalEndpoint); } controllerByPhysicalPort.remove(controller.getPhysicalEndpoint()); remove(controller); return controller.getPhysicalEndpoint(); } NetworkBfdPortService(IBfdPortCarrier carrier, PersistenceManager persistenceManager); void setup(Endpoint endpoint, int physicalPortNumber); Endpoint remove(Endpoint logicalEndpoint); void updateLinkStatus(Endpoint logicalEndpoint, LinkStatus linkStatus); void updateOnlineMode(Endpoint endpoint, boolean mode); void enable(Endpoint physicalEndpoint, IslReference reference); void disable(Endpoint physicalEndpoint); void speakerResponse(String key, Endpoint logicalEndpoint, BfdSessionResponse response); void speakerTimeout(String key, Endpoint logicalEndpoint); }
|
@Test public void killDuringInstalling() { setupController(); doAnswer(invocation -> invocation.getArgument(0)) .when(bfdSessionRepository).add(any()); NoviBfdSession session = doEnable(); when(carrier.removeBfdSession(any(NoviBfdSession.class))).thenReturn(removeRequestKey); service.remove(alphaLogicalEndpoint); verifyTerminateSequence(session); }
@Test public void killDuringActiveUp() { NoviBfdSession session = setupAndEnable(); when(carrier.removeBfdSession(any(NoviBfdSession.class))).thenReturn(removeRequestKey); service.remove(alphaLogicalEndpoint); verify(carrier).bfdKillNotification(alphaEndpoint); verifyTerminateSequence(session); }
|
NetworkBfdPortService { public void setup(Endpoint endpoint, int physicalPortNumber) { log.info("BFD-port service receive SETUP request for {} (physical-port:{})", endpoint, physicalPortNumber); BfdPortFsm controller = controllerFactory.produce(persistenceManager, endpoint, physicalPortNumber); BfdPortFsmContext context = BfdPortFsmContext.builder(carrier).build(); handle(controller, BfdPortFsmEvent.HISTORY, context); controllerByLogicalPort.put(controller.getLogicalEndpoint(), controller); controllerByPhysicalPort.put(controller.getPhysicalEndpoint(), controller); IslReference autostartData = autostart.remove(controller.getPhysicalEndpoint()); if (autostartData != null) { context = BfdPortFsmContext.builder(carrier) .islReference(autostartData) .build(); handle(controller, BfdPortFsmEvent.ENABLE, context); } } NetworkBfdPortService(IBfdPortCarrier carrier, PersistenceManager persistenceManager); void setup(Endpoint endpoint, int physicalPortNumber); Endpoint remove(Endpoint logicalEndpoint); void updateLinkStatus(Endpoint logicalEndpoint, LinkStatus linkStatus); void updateOnlineMode(Endpoint endpoint, boolean mode); void enable(Endpoint physicalEndpoint, IslReference reference); void disable(Endpoint physicalEndpoint); void speakerResponse(String key, Endpoint logicalEndpoint, BfdSessionResponse response); void speakerTimeout(String key, Endpoint logicalEndpoint); }
|
@Test public void enableBeforeSetup() { IslReference reference = new IslReference(alphaEndpoint, betaEndpoint); doEnableBeforeSetup(reference); doAnswer(invocation -> invocation.getArgument(0)) .when(bfdSessionRepository).add(any()); mockSwitchLookup(alphaSwitch); mockSwitchLookup(betaSwitch); mockMissingBfdSession(alphaLogicalEndpoint); when(carrier.setupBfdSession(any(NoviBfdSession.class))).thenReturn(setupRequestKey); service.setup(alphaLogicalEndpoint, alphaEndpoint.getPortNumber()); verify(bfdSessionRepository).add(any(BfdSession.class)); verify(carrier).setupBfdSession(argThat( arg -> arg.getTarget().getDatapath().equals(alphaEndpoint.getDatapath()) && arg.getPhysicalPortNumber() == alphaEndpoint.getPortNumber() && arg.getLogicalPortNumber() == alphaLogicalEndpoint.getPortNumber() && arg.getRemote().getDatapath().equals(betaEndpoint.getDatapath()))); verifyNoMoreInteractions(carrier); }
|
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 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)); }
|
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 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)); }
|
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 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)); }
|
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 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)); }
|
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 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)); }
|
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 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)); }
|
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 colonSeparatedBytesIllegalArgumentExceptionNegativeOffset() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", -1)); new SwitchId("00").colonSeparatedBytes(new char[]{'t', 'e', 's', 't'}, -1); }
@Test public void colonSeparatedBytesIllegalArgumentExceptionOddOffset() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", 3)); new SwitchId("00").colonSeparatedBytes(new char[]{'t', 'e', 's', 't'}, 3); }
@Test public void colonSeparatedBytesIllegalArgumentExceptionMoreThenHexLength() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(String.format( "Illegal offset value %d (expect offset > 0 and offset %% 2 == 0 and offset < hex.length)", 6)); new SwitchId("00").colonSeparatedBytes(new char[]{'t', 'e', 's', 't'}, 6); }
|
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 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()); }
|
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 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")); }
|
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 convertRateToKiloBitsTest() { assertEquals(800, Meter.convertRateToKiloBits(100, 1024)); assertEquals(64, Meter.convertRateToKiloBits(1, 1)); assertEquals(64, Meter.convertRateToKiloBits(8, 16)); }
|
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 convertBurstSizeToKiloBitsTest() { assertEquals(800, Meter.convertBurstSizeToKiloBits(100, 1024)); assertEquals(1, Meter.convertBurstSizeToKiloBits(8, 16)); }
|
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 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)); }
|
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 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()); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.