import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.security.AccessControlException;
+import java.util.HashMap;
+import java.util.Map;
import org.opendaylight.protocol.bgp.rib.impl.spi.BGPDispatcher;
import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
import org.opendaylight.protocol.bgp.rib.impl.spi.PeerRegistryListener;
-import org.opendaylight.protocol.concepts.KeyMapping;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressNoZone;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
public BGPPeerAcceptorImpl(final IpAddressNoZone bindingAddress, final PortNumber portNumber,
final BGPDispatcher bgpDispatcher) {
this.bgpDispatcher = requireNonNull(bgpDispatcher);
- this.address = getAddress(requireNonNull(bindingAddress), requireNonNull(portNumber));
+ address = getAddress(requireNonNull(bindingAddress), requireNonNull(portNumber));
if (!PlatformDependent.isWindows() && !PlatformDependent.maybeSuperUser()
&& portNumber.getValue().toJava() < PRIVILEGED_PORTS) {
throw new AccessControlException("Unable to bind port " + portNumber.getValue()
}
public void start() {
- LOG.debug("Instantiating BGP Peer Acceptor : {}", this.address);
+ LOG.debug("Instantiating BGP Peer Acceptor : {}", address);
- this.futureChannel = this.bgpDispatcher.createServer(this.address);
+ futureChannel = bgpDispatcher.createServer(address);
// Validate future success
- this.futureChannel.addListener(future -> {
+ futureChannel.addListener(future -> {
Preconditions.checkArgument(future.isSuccess(), "Unable to start bgp server on %s",
- this.address, future.cause());
- final Channel channel = this.futureChannel.channel();
+ address, future.cause());
+ final Channel channel = futureChannel.channel();
if (Epoll.isAvailable()) {
- this.listenerRegistration = this.bgpDispatcher.getBGPPeerRegistry().registerPeerRegisterListener(
+ listenerRegistration = bgpDispatcher.getBGPPeerRegistry().registerPeerRegisterListener(
new BGPPeerAcceptorImpl.PeerRegistryListenerImpl(channel.config()));
}
});
**/
@Override
public void close() throws Exception {
- this.futureChannel.cancel(true);
- this.futureChannel.channel().close();
- if (this.listenerRegistration != null) {
- this.listenerRegistration.close();
+ futureChannel.cancel(true);
+ futureChannel.channel().close();
+ if (listenerRegistration != null) {
+ listenerRegistration.close();
}
}
private static final class PeerRegistryListenerImpl implements PeerRegistryListener {
+ private final Map<InetAddress, byte[]> keys = new HashMap<>();
private final ChannelConfig channelConfig;
- private final KeyMapping keys;
PeerRegistryListenerImpl(final ChannelConfig channelConfig) {
this.channelConfig = channelConfig;
- this.keys = KeyMapping.getKeyMapping();
}
@Override
public void onPeerAdded(final IpAddressNoZone ip, final BGPSessionPreferences prefs) {
- if (prefs.getMd5Password().isPresent()) {
- this.keys.put(IetfInetUtil.INSTANCE.inetAddressForNoZone(ip), prefs.getMd5Password().get());
- this.channelConfig.setOption(EpollChannelOption.TCP_MD5SIG, this.keys);
- }
+ prefs.getMd5Password().ifPresent(password -> {
+ keys.put(IetfInetUtil.INSTANCE.inetAddressForNoZone(ip), password);
+ channelConfig.setOption(EpollChannelOption.TCP_MD5SIG, keys);
+ });
}
@Override
public void onPeerRemoved(final IpAddressNoZone ip) {
- if (this.keys.remove(IetfInetUtil.INSTANCE.inetAddressForNoZone(ip)) != null) {
- this.channelConfig.setOption(EpollChannelOption.TCP_MD5SIG, this.keys);
+ if (keys.remove(IetfInetUtil.INSTANCE.inetAddressForNoZone(ip)) != null) {
+ channelConfig.setOption(EpollChannelOption.TCP_MD5SIG, keys);
}
}
}
this.workerGroup = requireNonNull(workerGroup);
}
this.bgpPeerRegistry = requireNonNull(bgpPeerRegistry);
- this.handlerFactory = new BGPHandlerFactory(extensions.getMessageRegistry());
+ handlerFactory = new BGPHandlerFactory(extensions.getMessageRegistry());
}
@VisibleForTesting
public synchronized Future<BGPSessionImpl> createClient(final InetSocketAddress localAddress,
final InetSocketAddress remoteAddress, final int retryTimer, final boolean reuseAddress) {
- final Bootstrap clientBootStrap = createClientBootStrap(KeyMapping.getKeyMapping(), reuseAddress, localAddress);
- final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(this.bgpPeerRegistry);
+ final Bootstrap clientBootStrap = createClientBootStrap(KeyMapping.of(), reuseAddress, localAddress);
+ final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(bgpPeerRegistry);
final ChannelPipelineInitializer<BGPSessionImpl> initializer = BGPChannel.createChannelPipelineInitializer(
- this.handlerFactory, snf);
+ handlerFactory, snf);
final BGPProtocolSessionPromise<BGPSessionImpl> sessionPromise = new BGPProtocolSessionPromise<>(remoteAddress,
- retryTimer, clientBootStrap, this.bgpPeerRegistry);
+ retryTimer, clientBootStrap, bgpPeerRegistry);
clientBootStrap.handler(BGPChannel.createClientChannelHandler(initializer, sessionPromise));
sessionPromise.connect();
LOG.debug("Client created.");
}
if (keys != null && !keys.isEmpty()) {
if (Epoll.isAvailable()) {
- bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys);
+ bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys.asMap());
} else {
throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
}
bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
if (bootstrap.config().group() == null) {
- bootstrap.group(this.workerGroup);
+ bootstrap.group(workerGroup);
}
bootstrap.localAddress(localAddress);
public synchronized void close() {
if (Epoll.isAvailable()) {
LOG.debug("Closing Dispatcher");
- this.workerGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
- this.bossGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
+ workerGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
+ bossGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
}
}
synchronized Future<Void> createReconnectingClient(final InetSocketAddress remoteAddress,
final int retryTimer, final KeyMapping keys, final InetSocketAddress localAddress,
final boolean reuseAddress) {
- final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(this.bgpPeerRegistry);
+ final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(bgpPeerRegistry);
final Bootstrap bootstrap = createClientBootStrap(keys, reuseAddress, localAddress);
final BGPReconnectPromise<?> reconnectPromise = new BGPReconnectPromise<>(GlobalEventExecutor.INSTANCE,
- remoteAddress, retryTimer, bootstrap, this.bgpPeerRegistry,
- BGPChannel.createChannelPipelineInitializer(this.handlerFactory, snf));
+ remoteAddress, retryTimer, bootstrap, bgpPeerRegistry,
+ BGPChannel.createChannelPipelineInitializer(handlerFactory, snf));
reconnectPromise.connect();
return reconnectPromise;
}
@Override
public synchronized ChannelFuture createServer(final InetSocketAddress serverAddress) {
- final BGPServerSessionNegotiatorFactory snf = new BGPServerSessionNegotiatorFactory(this.bgpPeerRegistry);
+ final BGPServerSessionNegotiatorFactory snf = new BGPServerSessionNegotiatorFactory(bgpPeerRegistry);
final ChannelPipelineInitializer<?> initializer = BGPChannel.createChannelPipelineInitializer(
- this.handlerFactory, snf);
+ handlerFactory, snf);
final ServerBootstrap serverBootstrap = createServerBootstrap(initializer);
final ChannelFuture channelFuture = serverBootstrap.bind(serverAddress);
LOG.debug("Initiated server {} at {}.", channelFuture, serverAddress);
@Override
public BGPPeerRegistry getBGPPeerRegistry() {
- return this.bgpPeerRegistry;
+ return bgpPeerRegistry;
}
private synchronized ServerBootstrap createServerBootstrap(final ChannelPipelineInitializer<?> initializer) {
serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, RECV_ALLOCATOR);
if (serverBootstrap.config().group() == null) {
- serverBootstrap.group(this.bossGroup, this.workerGroup);
+ serverBootstrap.group(bossGroup, workerGroup);
}
return serverBootstrap;
}
return caps;
}
- @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
- justification = "https://github.com/spotbugs/spotbugs/issues/811")
- private static Optional<byte[]> getPassword(final KeyMapping key) {
- if (key != null) {
- return Optional.of(Iterables.getOnlyElement(key.values()));
- }
- return Optional.empty();
- }
-
@Override
public synchronized void start(final RIB rib, final Neighbor neighbor, final InstanceIdentifier<Bgp> bgpIid,
final PeerGroupConfigLoader peerGroupLoader, final BGPTableTypeRegistryConsumer tableTypeRegistry) {
- Preconditions.checkState(this.bgpPeerSingletonService == null,
+ Preconditions.checkState(bgpPeerSingletonService == null,
"Previous peer instance was not closed.");
- this.bgpPeerSingletonService = new BgpPeerSingletonService(rib, neighbor, bgpIid, peerGroupLoader,
+ bgpPeerSingletonService = new BgpPeerSingletonService(rib, neighbor, bgpIid, peerGroupLoader,
tableTypeRegistry);
- this.currentConfiguration = neighbor;
- this.stateProviderRegistration = this.stateProviderRegistry.register(this);
+ currentConfiguration = neighbor;
+ stateProviderRegistration = stateProviderRegistry.register(this);
}
@Override
public synchronized void restart(final RIB rib, final InstanceIdentifier<Bgp> bgpIid,
final PeerGroupConfigLoader peerGroupLoader, final BGPTableTypeRegistryConsumer tableTypeRegistry) {
- Preconditions.checkState(this.currentConfiguration != null);
- if (this.bgpPeerSingletonService != null) {
- this.bgpPeerSingletonService.closeServiceInstance();
- this.bgpPeerSingletonService = null;
+ Preconditions.checkState(currentConfiguration != null);
+ if (bgpPeerSingletonService != null) {
+ bgpPeerSingletonService.closeServiceInstance();
+ bgpPeerSingletonService = null;
}
- start(rib, this.currentConfiguration, bgpIid, peerGroupLoader, tableTypeRegistry);
+ start(rib, currentConfiguration, bgpIid, peerGroupLoader, tableTypeRegistry);
}
@Override
public synchronized void close() {
- if (this.bgpPeerSingletonService != null) {
- this.bgpPeerSingletonService.closeServiceInstance();
- this.bgpPeerSingletonService = null;
+ if (bgpPeerSingletonService != null) {
+ bgpPeerSingletonService.closeServiceInstance();
+ bgpPeerSingletonService = null;
}
- if (this.stateProviderRegistration != null) {
- this.stateProviderRegistration.close();
- this.stateProviderRegistration = null;
+ if (stateProviderRegistration != null) {
+ stateProviderRegistration.close();
+ stateProviderRegistration = null;
}
}
@Override
public synchronized void instantiateServiceInstance() {
- if (this.bgpPeerSingletonService != null) {
- this.bgpPeerSingletonService.instantiateServiceInstance();
+ if (bgpPeerSingletonService != null) {
+ bgpPeerSingletonService.instantiateServiceInstance();
}
}
@Override
public synchronized FluentFuture<? extends CommitInfo> closeServiceInstance() {
- if (this.bgpPeerSingletonService != null) {
- return this.bgpPeerSingletonService.closeServiceInstance();
+ if (bgpPeerSingletonService != null) {
+ return bgpPeerSingletonService.closeServiceInstance();
}
return CommitInfo.emptyFluentFuture();
}
@Override
public synchronized Boolean containsEqualConfiguration(final Neighbor neighbor) {
- if (this.currentConfiguration == null) {
+ if (currentConfiguration == null) {
return false;
}
- final AfiSafis actAfiSafi = this.currentConfiguration.getAfiSafis();
+ final AfiSafis actAfiSafi = currentConfiguration.getAfiSafis();
final AfiSafis extAfiSafi = neighbor.getAfiSafis();
final Collection<AfiSafi> actualSafi = actAfiSafi != null ? actAfiSafi.nonnullAfiSafi().values()
: Collections.emptyList();
final Collection<AfiSafi> extSafi = extAfiSafi != null ? extAfiSafi.nonnullAfiSafi().values()
: Collections.emptyList();
return actualSafi.containsAll(extSafi) && extSafi.containsAll(actualSafi)
- && Objects.equals(this.currentConfiguration.getConfig(), neighbor.getConfig())
- && Objects.equals(this.currentConfiguration.getNeighborAddress(), neighbor.getNeighborAddress())
- && Objects.equals(this.currentConfiguration.getAddPaths(), neighbor.getAddPaths())
- && Objects.equals(this.currentConfiguration.getApplyPolicy(), neighbor.getApplyPolicy())
- && Objects.equals(this.currentConfiguration.getAsPathOptions(), neighbor.getAsPathOptions())
- && Objects.equals(this.currentConfiguration.getEbgpMultihop(), neighbor.getEbgpMultihop())
- && Objects.equals(this.currentConfiguration.getGracefulRestart(), neighbor.getGracefulRestart())
- && Objects.equals(this.currentConfiguration.getErrorHandling(), neighbor.getErrorHandling())
- && Objects.equals(this.currentConfiguration.getLoggingOptions(), neighbor.getLoggingOptions())
- && Objects.equals(this.currentConfiguration.getRouteReflector(), neighbor.getRouteReflector())
- && Objects.equals(this.currentConfiguration.getState(), neighbor.getState())
- && Objects.equals(this.currentConfiguration.getTimers(), neighbor.getTimers())
- && Objects.equals(this.currentConfiguration.getTransport(), neighbor.getTransport());
+ && Objects.equals(currentConfiguration.getConfig(), neighbor.getConfig())
+ && Objects.equals(currentConfiguration.getNeighborAddress(), neighbor.getNeighborAddress())
+ && Objects.equals(currentConfiguration.getAddPaths(), neighbor.getAddPaths())
+ && Objects.equals(currentConfiguration.getApplyPolicy(), neighbor.getApplyPolicy())
+ && Objects.equals(currentConfiguration.getAsPathOptions(), neighbor.getAsPathOptions())
+ && Objects.equals(currentConfiguration.getEbgpMultihop(), neighbor.getEbgpMultihop())
+ && Objects.equals(currentConfiguration.getGracefulRestart(), neighbor.getGracefulRestart())
+ && Objects.equals(currentConfiguration.getErrorHandling(), neighbor.getErrorHandling())
+ && Objects.equals(currentConfiguration.getLoggingOptions(), neighbor.getLoggingOptions())
+ && Objects.equals(currentConfiguration.getRouteReflector(), neighbor.getRouteReflector())
+ && Objects.equals(currentConfiguration.getState(), neighbor.getState())
+ && Objects.equals(currentConfiguration.getTimers(), neighbor.getTimers())
+ && Objects.equals(currentConfiguration.getTransport(), neighbor.getTransport());
}
@Override
public synchronized BGPPeerState getPeerState() {
- if (this.bgpPeerSingletonService == null) {
+ if (bgpPeerSingletonService == null) {
return null;
}
- return this.bgpPeerSingletonService.getPeerState();
+ return bgpPeerSingletonService.getPeerState();
}
synchronized void removePeer(final BGPPeerRegistry bgpPeerRegistry) {
- if (this.currentConfiguration != null) {
+ if (currentConfiguration != null) {
bgpPeerRegistry.removePeer(OpenConfigMappingUtil.convertIpAddress(
- this.currentConfiguration.getNeighborAddress()));
+ currentConfiguration.getNeighborAddress()));
}
}
private BgpPeerSingletonService(final RIB rib, final Neighbor neighbor, final InstanceIdentifier<Bgp> bgpIid,
final PeerGroupConfigLoader peerGroupLoader, final BGPTableTypeRegistryConsumer tableTypeRegistry) {
- this.neighborAddress = OpenConfigMappingUtil.convertIpAddress(neighbor.getNeighborAddress());
+ neighborAddress = OpenConfigMappingUtil.convertIpAddress(neighbor.getNeighborAddress());
PeerGroup peerGroup = null;
String peerGroupName = null;
final ClusterIdentifier clusterId = OpenConfigMappingUtil
.getNeighborClusterIdentifier(neighbor.getRouteReflector(), peerGroup);
final int hold = OpenConfigMappingUtil.getHoldTimer(neighbor, peerGroup);
- this.gracefulRestartTimer = OpenConfigMappingUtil.getGracefulRestartTimer(neighbor,
- peerGroup, hold);
+ gracefulRestartTimer = OpenConfigMappingUtil.getGracefulRestartTimer(neighbor, peerGroup, hold);
final Set<TablesKey> gracefulTables = GracefulRestartUtil.getGracefulTables(
afisSafis.nonnullAfiSafi().values(), tableTypeRegistry);
final Map<TablesKey, Integer> llGracefulTimers = GracefulRestartUtil.getLlGracefulTimers(
afisSafis.nonnullAfiSafi().values(), tableTypeRegistry);
- this.finalCapabilities = getBgpCapabilities(afisSafis, rib, tableTypeRegistry);
+ finalCapabilities = getBgpCapabilities(afisSafis, rib, tableTypeRegistry);
final List<BgpParameters> bgpParameters = getInitialBgpParameters(gracefulTables, llGracefulTimers);
final KeyMapping keyMapping = OpenConfigMappingUtil.getNeighborKey(neighbor);
final IpAddressNoZone neighborLocalAddress = OpenConfigMappingUtil.getLocalAddress(neighbor.getTransport());
neighborLocalAs = globalAs;
}
- this.errorHandling = OpenConfigMappingUtil.getRevisedErrorHandling(role, peerGroup, neighbor);
- this.bgpPeer = new BGPPeer(tableTypeRegistry, this.neighborAddress, peerGroupName, rib, role, clusterId,
- neighborLocalAs, BgpPeer.this.rpcRegistry, afiSafisAdvertized, gracefulTables, llGracefulTimers,
+ errorHandling = OpenConfigMappingUtil.getRevisedErrorHandling(role, peerGroup, neighbor);
+ bgpPeer = new BGPPeer(tableTypeRegistry, neighborAddress, peerGroupName, rib, role, clusterId,
+ neighborLocalAs, rpcRegistry, afiSafisAdvertized, gracefulTables, llGracefulTimers,
BgpPeer.this);
- this.prefs = new BGPSessionPreferences(neighborLocalAs, hold, rib.getBgpIdentifier(),
- neighborRemoteAs, bgpParameters, getPassword(keyMapping));
- this.activeConnection = OpenConfigMappingUtil.isActive(neighbor, peerGroup);
- this.retryTimer = OpenConfigMappingUtil.getRetryTimer(neighbor, peerGroup);
- this.dispatcher = rib.getDispatcher();
+ prefs = new BGPSessionPreferences(neighborLocalAs, hold, rib.getBgpIdentifier(),
+ neighborRemoteAs, bgpParameters,
+ keyMapping == null ? Optional.empty()
+ : Optional.of(Iterables.getOnlyElement(keyMapping.asMap().values())));
+ activeConnection = OpenConfigMappingUtil.isActive(neighbor, peerGroup);
+ retryTimer = OpenConfigMappingUtil.getRetryTimer(neighbor, peerGroup);
+ dispatcher = rib.getDispatcher();
final PortNumber port = OpenConfigMappingUtil.getPort(neighbor, peerGroup);
- this.inetAddress = Ipv4Util.toInetSocketAddress(this.neighborAddress, port);
+ inetAddress = Ipv4Util.toInetSocketAddress(neighborAddress, port);
if (neighborLocalAddress != null) {
- this.localAddress = Ipv4Util.toInetSocketAddress(neighborLocalAddress, port);
+ localAddress = Ipv4Util.toInetSocketAddress(neighborLocalAddress, port);
} else {
- this.localAddress = null;
+ localAddress = null;
}
- this.keys = keyMapping;
+ keys = keyMapping;
}
private List<BgpParameters> getInitialBgpParameters(final Set<TablesKey> gracefulTables,
.map(entry -> new BgpPeerUtil.LlGracefulRestartDTO(entry.getKey(), entry.getValue(), false))
.collect(Collectors.toSet());
return Collections.singletonList(
- GracefulRestartUtil.getGracefulBgpParameters(this.finalCapabilities, gracefulTables,
+ GracefulRestartUtil.getGracefulBgpParameters(finalCapabilities, gracefulTables,
Collections.emptySet(), gracefulRestartTimer, false, llGracefulRestarts));
}
synchronized void instantiateServiceInstance() {
if (isServiceInstantiated) {
- LOG.warn("Peer {} has already been instantiated", this.neighborAddress);
+ LOG.warn("Peer {} has already been instantiated", neighborAddress);
return;
}
- this.isServiceInstantiated = true;
- LOG.info("Peer instantiated {}", this.neighborAddress);
- this.bgpPeer.instantiateServiceInstance();
- this.dispatcher.getBGPPeerRegistry().addPeer(this.neighborAddress, this.bgpPeer, this.prefs);
- if (this.activeConnection) {
- this.connection = this.dispatcher.createReconnectingClient(this.inetAddress, this.localAddress,
- this.retryTimer, this.keys);
+ isServiceInstantiated = true;
+ LOG.info("Peer instantiated {}", neighborAddress);
+ bgpPeer.instantiateServiceInstance();
+ dispatcher.getBGPPeerRegistry().addPeer(neighborAddress, bgpPeer, prefs);
+ if (activeConnection) {
+ connection = dispatcher.createReconnectingClient(inetAddress, localAddress, retryTimer, keys);
}
}
synchronized FluentFuture<? extends CommitInfo> closeServiceInstance() {
- if (!this.isServiceInstantiated) {
- LOG.info("Peer {} already closed", this.neighborAddress);
+ if (!isServiceInstantiated) {
+ LOG.info("Peer {} already closed", neighborAddress);
return CommitInfo.emptyFluentFuture();
}
- LOG.info("Close Peer {}", this.neighborAddress);
- this.isServiceInstantiated = false;
- if (this.connection != null) {
- this.connection.cancel(true);
- this.connection = null;
+ LOG.info("Close Peer {}", neighborAddress);
+ isServiceInstantiated = false;
+ if (connection != null) {
+ connection.cancel(true);
+ connection = null;
}
- final FluentFuture<? extends CommitInfo> future = this.bgpPeer.close();
- removePeer(this.dispatcher.getBGPPeerRegistry());
+ final FluentFuture<? extends CommitInfo> future = bgpPeer.close();
+ removePeer(dispatcher.getBGPPeerRegistry());
return future;
}
@Override
public BGPPeerState getPeerState() {
- return this.bgpPeer.getPeerState();
+ return bgpPeer.getPeerState();
}
}
public synchronized List<OptionalCapabilities> getBgpFixedCapabilities() {
- return this.bgpPeerSingletonService.finalCapabilities;
+ return bgpPeerSingletonService.finalCapabilities;
}
public synchronized int getGracefulRestartTimer() {
- return this.bgpPeerSingletonService.gracefulRestartTimer;
+ return bgpPeerSingletonService.gracefulRestartTimer;
}
public synchronized Optional<RevisedErrorHandlingSupport> getErrorHandling() {
- return Optional.ofNullable(this.bgpPeerSingletonService.errorHandling);
+ return Optional.ofNullable(bgpPeerSingletonService.errorHandling);
}
}
}
static KeyMapping getNeighborKey(final Neighbor neighbor) {
- if (neighbor.getConfig() != null) {
- final String authPassword = neighbor.getConfig().getAuthPassword();
+ final var config = neighbor.getConfig();
+ if (config != null) {
+ final String authPassword = config.getAuthPassword();
if (authPassword != null) {
- return KeyMapping.getKeyMapping(INSTANCE.inetAddressFor(neighbor.getNeighborAddress()), authPassword);
+ return KeyMapping.of(INSTANCE.inetAddressFor(neighbor.getNeighborAddress()), authPassword);
}
}
return null;
*/
package org.opendaylight.protocol.bgp.rib.impl;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.checkIdleState;
import com.google.common.collect.Sets;
import io.netty.util.concurrent.Future;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutionException;
-import org.junit.Assert;
import org.junit.Test;
import org.opendaylight.protocol.bgp.rib.spi.State;
import org.opendaylight.protocol.concepts.KeyMapping;
public void testCreateClient() throws InterruptedException, ExecutionException {
final InetSocketAddress serverAddress = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress();
final Channel serverChannel = createServer(serverAddress);
- final Future<BGPSessionImpl> futureClient = this.clientDispatcher.createClient(this.clientAddress,
- serverAddress, 2, true);
+ final Future<BGPSessionImpl> futureClient = clientDispatcher.createClient(clientAddress, serverAddress, 2,
+ true);
futureClient.sync();
final BGPSessionImpl session = futureClient.get();
- Assert.assertEquals(State.UP, this.clientListener.getState());
- Assert.assertEquals(State.UP, this.serverListener.getState());
- Assert.assertEquals(AS_NUMBER, session.getAsNumber());
- Assert.assertEquals(Sets.newHashSet(IPV_4_TT), session.getAdvertisedTableTypes());
- Assert.assertTrue(serverChannel.isWritable());
+ assertEquals(State.UP, clientListener.getState());
+ assertEquals(State.UP, serverListener.getState());
+ assertEquals(AS_NUMBER, session.getAsNumber());
+ assertEquals(Sets.newHashSet(IPV_4_TT), session.getAdvertisedTableTypes());
+ assertTrue(serverChannel.isWritable());
session.close();
- this.serverListener.releaseConnection();
- checkIdleState(this.clientListener);
- checkIdleState(this.serverListener);
+ serverListener.releaseConnection();
+ checkIdleState(clientListener);
+ checkIdleState(serverListener);
}
@Test
public void testCreateReconnectingClient() throws Exception {
final InetSocketAddress serverAddress = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress();
- final Future<Void> future = this.clientDispatcher.createReconnectingClient(serverAddress, RETRY_TIMER,
- KeyMapping.getKeyMapping(), this.clientAddress, true);
+ final Future<Void> future = clientDispatcher.createReconnectingClient(serverAddress, RETRY_TIMER,
+ KeyMapping.of(), clientAddress, true);
final Channel serverChannel = createServer(serverAddress);
- Assert.assertEquals(State.UP, this.serverListener.getState());
- Assert.assertTrue(serverChannel.isWritable());
+ assertEquals(State.UP, serverListener.getState());
+ assertTrue(serverChannel.isWritable());
future.cancel(true);
- this.serverListener.releaseConnection();
- checkIdleState(this.serverListener);
+ serverListener.releaseConnection();
+ checkIdleState(serverListener);
}
}
@Before
public void setUp() {
- doReturn(BGP_TABLE_TYPE_IPV4).when(this.tableTypeRegistry).getTableType(IPV4UNICAST.class);
- doReturn(BGP_TABLE_TYPE_IPV6).when(this.tableTypeRegistry).getTableType(IPV6UNICAST.class);
+ doReturn(BGP_TABLE_TYPE_IPV4).when(tableTypeRegistry).getTableType(IPV4UNICAST.class);
+ doReturn(BGP_TABLE_TYPE_IPV6).when(tableTypeRegistry).getTableType(IPV6UNICAST.class);
doReturn(new BgpTableTypeImpl(Ipv6AddressFamily.class, MplsLabeledVpnSubsequentAddressFamily.class))
- .when(this.tableTypeRegistry).getTableType(IPV6LABELLEDUNICAST.class);
- doReturn(AS).when(this.rib).getLocalAs();
+ .when(tableTypeRegistry).getTableType(IPV6LABELLEDUNICAST.class);
+ doReturn(AS).when(rib).getLocalAs();
}
@Test
public void testGetRemotePeerAs() {
final ConfigBuilder configBuilder = new ConfigBuilder();
assertEquals(AS, OpenConfigMappingUtil.getRemotePeerAs(NEIGHBOR.getConfig(), null, null));
- assertEquals(AS, OpenConfigMappingUtil.getRemotePeerAs(configBuilder.build(), null,
- this.rib.getLocalAs()));
+ assertEquals(AS, OpenConfigMappingUtil.getRemotePeerAs(configBuilder.build(), null, rib.getLocalAs()));
assertEquals(AS, OpenConfigMappingUtil.getRemotePeerAs(NEIGHBOR.getConfig(), EMPTY_PEERGROUP, null));
assertEquals(AS, OpenConfigMappingUtil.getRemotePeerAs(configBuilder.build(), EMPTY_PEERGROUP,
- this.rib.getLocalAs()));
+ rib.getLocalAs()));
assertEquals(AS, OpenConfigMappingUtil.getRemotePeerAs(null, new PeerGroupBuilder().setPeerGroupName("foo")
.setConfig(new ConfigBuilder().setPeerAs(AS).build()).build(), null));
@Test
public void testGetNeighborKey() {
assertArrayEquals(MD5_PASSWORD.getBytes(StandardCharsets.US_ASCII),
- OpenConfigMappingUtil.getNeighborKey(NEIGHBOR).get(INSTANCE.inetAddressFor(NEIGHBOR_ADDRESS)));
+ OpenConfigMappingUtil.getNeighborKey(NEIGHBOR).asMap().get(INSTANCE.inetAddressFor(NEIGHBOR_ADDRESS)));
assertNull(OpenConfigMappingUtil.getNeighborKey(EMPTY_NEIGHBOR));
assertNull(OpenConfigMappingUtil.getNeighborKey(new NeighborBuilder().setNeighborAddress(NEIGHBOR_ADDRESS)
.setConfig(new ConfigBuilder().build()).build()));
families.add(new AfiSafiBuilder().setAfiSafiName(IPV6UNICAST.class)
.addAugmentation(new GlobalAddPathsConfigBuilder().setSendMax(ALL_PATHS).build()).build());
final Map<BgpTableType, PathSelectionMode> result = OpenConfigMappingUtil
- .toPathSelectionMode(families, this.tableTypeRegistry);
+ .toPathSelectionMode(families, tableTypeRegistry);
final Map<BgpTableType, PathSelectionMode> expected = new HashMap<>();
expected.put(new BgpTableTypeImpl(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class),
ADD_PATH_BEST_N_PATH_SELECTION);
.setReceive(Boolean.FALSE).setSendMax(N_PATHS).build()).build());
families.add(new AfiSafiBuilder().setAfiSafiName(IPV6LABELLEDUNICAST.class)
.addAugmentation(new NeighborAddPathsConfigBuilder().setReceive(Boolean.FALSE).build()).build());
- final List<AddressFamilies> result = OpenConfigMappingUtil
- .toAddPathCapability(families, this.tableTypeRegistry);
+ final List<AddressFamilies> result = OpenConfigMappingUtil .toAddPathCapability(families, tableTypeRegistry);
assertEquals(FAMILIES, result);
}
assertEquals(RevisedErrorHandlingSupportImpl.forExternalPeer(),
OpenConfigMappingUtil.getRevisedErrorHandling(PeerRole.Ebgp, peerGroup.build(), neighbor.build()));
}
-}
\ No newline at end of file
+}
if (!keys.isEmpty()) {
if (Epoll.isAvailable()) {
- serverBootstrap.option(EpollChannelOption.TCP_MD5SIG, keys);
+ serverBootstrap.option(EpollChannelOption.TCP_MD5SIG, keys.asMap());
} else {
throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
}
}
if (!keys.isEmpty()) {
if (Epoll.isAvailable()) {
- bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys);
+ bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys.asMap());
} else {
throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
}
package org.opendaylight.protocol.bmp.impl.app;
import static java.util.Objects.requireNonNull;
-import static org.opendaylight.protocol.bmp.impl.app.KeyConstructorUtil.constructKeys;
import com.google.common.base.Preconditions;
import com.google.common.net.InetAddresses;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTree;
import org.opendaylight.mdsal.common.api.CommitInfo;
import org.opendaylight.protocol.bmp.impl.spi.BmpMonitoringStation;
import org.opendaylight.protocol.concepts.KeyMapping;
import org.opendaylight.protocol.util.Ipv4Util;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.monitor.config.rev200120.odl.bmp.monitors.bmp.monitor.config.MonitoredRouter;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.monitor.rev200120.BmpMonitor;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.monitor.rev200120.MonitorId;
this.domDataBroker = requireNonNull(domDataBroker);
this.dispatcher = requireNonNull(dispatcher);
this.monitorId = monitorId;
- this.monitoredRouters = mrs;
+ monitoredRouters = mrs;
this.address = requireNonNull(address);
- this.yangMonitorId = YangInstanceIdentifier.builder()
+ yangMonitorId = YangInstanceIdentifier.builder()
.node(BmpMonitor.QNAME).node(Monitor.QNAME)
.nodeWithKey(Monitor.QNAME, MONITOR_ID_QNAME, monitorId.getValue()).build();
- this.sessionManager = new RouterSessionManager(this.yangMonitorId, this.domDataBroker, extensions, codecTree);
+ sessionManager = new RouterSessionManager(yangMonitorId, this.domDataBroker, extensions, codecTree);
LOG.info("BMP Monitor Singleton Service {} registered, Monitor Id {}",
getIdentifier().getName(), this.monitorId.getValue());
- this.singletonServiceRegistration = singletonProvider.registerClusterSingletonService(this);
+ singletonServiceRegistration = singletonProvider.registerClusterSingletonService(this);
}
@Override
public synchronized void instantiateServiceInstance() {
LOG.info("BMP Monitor Singleton Service {} instantiated, Monitor Id {}",
- getIdentifier().getName(), this.monitorId.getValue());
+ getIdentifier().getName(), monitorId.getValue());
- final ChannelFuture channelFuture = this.dispatcher.createServer(this.address, this.sessionManager,
- constructKeys(this.monitoredRouters));
+ final ChannelFuture channelFuture = dispatcher.createServer(address, sessionManager,
+ constructKeys(monitoredRouters));
try {
- this.channel = channelFuture.sync().channel();
+ channel = channelFuture.sync().channel();
createEmptyMonitor();
- LOG.info("BMP Monitoring station {} started", this.monitorId.getValue());
+ LOG.info("BMP Monitoring station {} started", monitorId.getValue());
- connectMonitoredRouters(this.dispatcher);
+ connectMonitoredRouters(dispatcher);
LOG.info("Connecting to monitored routers completed.");
} catch (final InterruptedException e) {
- LOG.error("Failed to instantiate BMP Monitor Singleton {}", this.monitorId.getValue(), e);
+ LOG.error("Failed to instantiate BMP Monitor Singleton {}", monitorId.getValue(), e);
+ }
+
+ }
+
+ private static KeyMapping constructKeys(final Collection<MonitoredRouter> mrs) {
+ if (mrs == null || mrs.isEmpty()) {
+ return KeyMapping.of();
}
+ final Map<InetAddress, String> passwords = new HashMap<>();
+ for (MonitoredRouter mr : mrs) {
+ if (mr != null) {
+ final Rfc2385Key password = mr.getPassword();
+ if (password != null && !password.getValue().isEmpty()) {
+ passwords.put(IetfInetUtil.INSTANCE.inetAddressForNoZone(mr.getAddress()), password.getValue());
+ }
+ }
+ }
+
+ return KeyMapping.of(passwords);
}
@Override
public synchronized FluentFuture<? extends CommitInfo> closeServiceInstance() {
LOG.info("BMP Monitor Singleton Service {} instance closed, Monitor Id {}",
- getIdentifier().getName(), this.monitorId.getValue());
- if (this.channel != null) {
- this.channel.close().addListener((ChannelFutureListener) future -> {
+ getIdentifier().getName(), monitorId.getValue());
+ if (channel != null) {
+ channel.close().addListener((ChannelFutureListener) future -> {
Preconditions.checkArgument(future.isSuccess(),
"Channel failed to close: %s", future.cause());
BmpMonitoringStationImpl.this.sessionManager.close();
});
}
- final DOMDataTreeWriteTransaction wTx = this.domDataBroker.newWriteOnlyTransaction();
- wTx.delete(LogicalDatastoreType.OPERATIONAL, this.yangMonitorId);
- LOG.info("BMP monitoring station {} closed.", this.monitorId.getValue());
+ final DOMDataTreeWriteTransaction wTx = domDataBroker.newWriteOnlyTransaction();
+ wTx.delete(LogicalDatastoreType.OPERATIONAL, yangMonitorId);
+ LOG.info("BMP monitoring station {} closed.", monitorId.getValue());
return wTx.commit();
}
}
private void connectMonitoredRouters(final BmpDispatcher pdispatcher) {
- if (this.monitoredRouters != null) {
- for (final MonitoredRouter mr : this.monitoredRouters) {
+ if (monitoredRouters != null) {
+ for (final MonitoredRouter mr : monitoredRouters) {
if (mr.getActive()) {
requireNonNull(mr.getAddress());
requireNonNull(mr.getPort());
final InetAddress addr = InetAddresses.forString(s);
final KeyMapping ret;
final Rfc2385Key rfc2385KeyPassword = mr.getPassword();
- ret = KeyMapping.getKeyMapping(addr, rfc2385KeyPassword.getValue());
+ ret = KeyMapping.of(addr, rfc2385KeyPassword.getValue());
pdispatcher.createClient(Ipv4Util.toInetSocketAddress(mr.getAddress(), mr.getPort()),
- this.sessionManager, ret);
+ sessionManager, ret);
}
}
}
}
private synchronized void createEmptyMonitor() {
- final DOMDataTreeWriteTransaction wTx = this.domDataBroker.newWriteOnlyTransaction();
+ final DOMDataTreeWriteTransaction wTx = domDataBroker.newWriteOnlyTransaction();
wTx.put(LogicalDatastoreType.OPERATIONAL,
YangInstanceIdentifier.builder().node(BmpMonitor.QNAME).node(Monitor.QNAME)
- .nodeWithKey(Monitor.QNAME, MONITOR_ID_QNAME, this.monitorId.getValue()).build(),
- ImmutableNodes.mapEntryBuilder(Monitor.QNAME, MONITOR_ID_QNAME, this.monitorId.getValue())
- .addChild(ImmutableNodes.leafNode(MONITOR_ID_QNAME, this.monitorId.getValue()))
+ .nodeWithKey(Monitor.QNAME, MONITOR_ID_QNAME, monitorId.getValue()).build(),
+ ImmutableNodes.mapEntryBuilder(Monitor.QNAME, MONITOR_ID_QNAME, monitorId.getValue())
+ .addChild(ImmutableNodes.leafNode(MONITOR_ID_QNAME, monitorId.getValue()))
.addChild(ImmutableNodes.mapNodeBuilder(Router.QNAME).build())
.build());
try {
wTx.commit().get();
} catch (final ExecutionException | InterruptedException e) {
- LOG.error("Failed to initiate BMP Monitor {}.", this.monitorId.getValue(), e);
+ LOG.error("Failed to initiate BMP Monitor {}.", monitorId.getValue(), e);
}
}
@Override
public synchronized void close() throws Exception {
- if (this.singletonServiceRegistration != null) {
- this.singletonServiceRegistration.close();
- this.singletonServiceRegistration = null;
+ if (singletonServiceRegistration != null) {
+ singletonServiceRegistration.close();
+ singletonServiceRegistration = null;
}
}
}
+++ /dev/null
-/*
- * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.bmp.impl.app;
-
-import java.nio.charset.StandardCharsets;
-import java.util.Collection;
-import java.util.Objects;
-import org.opendaylight.protocol.concepts.KeyMapping;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.monitor.config.rev200120.odl.bmp.monitors.bmp.monitor.config.MonitoredRouter;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.rfc2385.cfg.rev160324.Rfc2385Key;
-
-public final class KeyConstructorUtil {
- private KeyConstructorUtil() {
- // Hidden on purpose
- }
-
- public static KeyMapping constructKeys(final Collection<MonitoredRouter> mrs) {
- final KeyMapping ret = KeyMapping.getKeyMapping();
- if (mrs != null) {
- mrs.stream().filter(Objects::nonNull).filter(KeyConstructorUtil::isNotNullorEmpty)
- .forEach(mr -> {
- final Rfc2385Key rfc2385KeyPassword = mr.getPassword();
- ret.put(IetfInetUtil.INSTANCE.inetAddressForNoZone(mr.getAddress()),
- rfc2385KeyPassword.getValue().getBytes(StandardCharsets.US_ASCII));
- });
- }
-
- return ret;
- }
-
- private static boolean isNotNullorEmpty(final MonitoredRouter mr) {
- final Rfc2385Key password = mr.getPassword();
- return password != null && !password.getValue().isEmpty();
- }
-}
@Test
public void testCreateServer() throws Exception {
- final ChannelFuture futureServer = dispatcher.createServer(SERVER, mockedListenerFactory,
- KeyMapping.getKeyMapping());
+ final ChannelFuture futureServer = dispatcher.createServer(SERVER, mockedListenerFactory, KeyMapping.of());
waitFutureSuccess(futureServer);
final Channel serverChannel = futureServer.channel();
checkEquals(() -> assertTrue(serverChannel.isActive()));
-
final ChannelFuture futureClient = dispatcher.createClient(CLIENT_REMOTE, mockedListenerFactory,
- KeyMapping.getKeyMapping());
+ KeyMapping.of());
waitFutureSuccess(futureClient);
final Channel clientChannel = futureClient.channel();
private static final Logger LOG = LoggerFactory.getLogger(BmpMockDispatcher.class);
private static final int CONNECT_TIMEOUT = 2000;
private static final int INITIAL_BACKOFF = 15_000;
- private static final KeyMapping KEY_MAPPING = KeyMapping.getKeyMapping();
+
private final BmpHandlerFactory hf;
private final BmpSessionFactory sessionFactory;
BmpMockDispatcher(final BmpMessageRegistry registry, final BmpSessionFactory sessionFactory) {
this.sessionFactory = requireNonNull(sessionFactory);
- this.slf = new BmpMockSessionListenerFactory();
+ slf = new BmpMockSessionListenerFactory();
requireNonNull(registry);
- this.hf = new BmpHandlerFactory(registry);
+ hf = new BmpHandlerFactory(registry);
}
ChannelFuture createClient(final @NonNull SocketAddress localAddress,
final @NonNull InetSocketAddress remoteAddress) {
- final Bootstrap bootstrap = BmpDispatcherUtil.createClientBootstrap(this.sessionFactory, this.hf,
- BmpDispatcherUtil::createChannelWithEncoder, this.slf, remoteAddress, localAddress, this.workerGroup,
- CONNECT_TIMEOUT, KEY_MAPPING, true, false);
+ final Bootstrap bootstrap = BmpDispatcherUtil.createClientBootstrap(sessionFactory, hf,
+ BmpDispatcherUtil::createChannelWithEncoder, slf, remoteAddress, localAddress, workerGroup,
+ CONNECT_TIMEOUT, KeyMapping.of(), true, false);
final ChannelFuture channelFuture = bootstrap.connect(remoteAddress);
LOG.info("BMP client {} <--> {} deployed", localAddress, remoteAddress);
channelFuture.addListener(new BootstrapListener(bootstrap, localAddress, remoteAddress));
ChannelFuture createServer(final InetSocketAddress localAddress) {
requireNonNull(localAddress);
- final ServerBootstrap serverBootstrap = BmpDispatcherUtil.createServerBootstrap(this.sessionFactory,
- this.hf, this.slf, BmpDispatcherUtil::createChannelWithEncoder,
- this.bossGroup, this.workerGroup, KEY_MAPPING, false);
+ final ServerBootstrap serverBootstrap = BmpDispatcherUtil.createServerBootstrap(sessionFactory,
+ hf, slf, BmpDispatcherUtil::createChannelWithEncoder,
+ bossGroup, workerGroup, KeyMapping.of(), false);
final ChannelFuture channelFuture = serverBootstrap.bind(localAddress);
LOG.info("Initiated BMP server at {}.", localAddress);
return channelFuture;
@Override
public synchronized void close() {
- this.close = true;
+ close = true;
}
private class BootstrapListener implements ChannelFutureListener {
this.bootstrap = bootstrap;
this.remoteAddress = remoteAddress;
this.localAddress = localAddress;
- this.delay = INITIAL_BACKOFF;
+ delay = INITIAL_BACKOFF;
}
@Override
future.channel().closeFuture().addListener((ChannelFutureListener) channelFuture -> scheduleConnect());
} else {
final EventLoop loop = future.channel().eventLoop();
- loop.schedule(() -> this.bootstrap.connect().addListener(this), this.delay, TimeUnit.MILLISECONDS);
+ loop.schedule(() -> bootstrap.connect().addListener(this), delay, TimeUnit.MILLISECONDS);
LOG.info("The connection try to BMP router {} failed. Next reconnection attempt in {} milliseconds.",
- this.remoteAddress, this.delay);
+ remoteAddress, delay);
}
}
private void scheduleConnect() {
- if (!BmpMockDispatcher.this.close) {
-
+ if (!close) {
timer.schedule(new TimerTask() {
@Override
public void run() {
- createClient(BootstrapListener.this.localAddress,
- BmpMockDispatcher.BootstrapListener.this.remoteAddress);
+ createClient(localAddress, remoteAddress);
}
}, 5);
}
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
- doReturn(this.sl).when(this.slf).getSessionListener();
- doReturn(this.registry).when(this.ctx).getBmpMessageRegistry();
- this.bmpMockDispatcher = new BmpMockDispatcher(this.registry, this.sessionFactory);
+ doReturn(sl).when(slf).getSessionListener();
+ doReturn(registry).when(ctx).getBmpMessageRegistry();
+ bmpMockDispatcher = new BmpMockDispatcher(registry, sessionFactory);
}
@Test(timeout = 20000)
final InetSocketAddress serverAddr = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
final BmpDispatcherImpl bmpDispatcher = new BmpDispatcherImpl(
- new NioEventLoopGroup(), new NioEventLoopGroup(), this.ctx, this.sessionFactory);
+ new NioEventLoopGroup(), new NioEventLoopGroup(), ctx, sessionFactory);
final ChannelFuture futureServer = bmpDispatcher
- .createServer(serverAddr, this.slf, KeyMapping.getKeyMapping());
+ .createServer(serverAddr, slf, KeyMapping.of());
waitFutureSuccess(futureServer);
- final ChannelFuture channelFuture = this.bmpMockDispatcher.createClient(InetSocketAddressUtil
+ final ChannelFuture channelFuture = bmpMockDispatcher.createClient(InetSocketAddressUtil
.getRandomLoopbackInetSocketAddress(0), serverAddr);
final Channel channel = channelFuture.sync().channel();
assertTrue(channel.isActive());
- checkEquals(() -> assertTrue(this.sl.getStatus()));
+ checkEquals(() -> assertTrue(sl.getStatus()));
channel.close();
bmpDispatcher.close();
- checkEquals(() -> assertFalse(this.sl.getStatus()));
+ checkEquals(() -> assertFalse(sl.getStatus()));
final BmpDispatcherImpl bmpDispatcher2 = new BmpDispatcherImpl(
- new NioEventLoopGroup(), new NioEventLoopGroup(), this.ctx, this.sessionFactory);
- final ChannelFuture futureServer2 = bmpDispatcher2
- .createServer(serverAddr, this.slf, KeyMapping.getKeyMapping());
+ new NioEventLoopGroup(), new NioEventLoopGroup(), ctx, sessionFactory);
+ final ChannelFuture futureServer2 = bmpDispatcher2.createServer(serverAddr, slf, KeyMapping.of());
futureServer2.sync();
- checkEquals(() -> assertTrue(this.sl.getStatus()));
+ checkEquals(() -> assertTrue(sl.getStatus()));
bmpDispatcher2.close();
- this.bmpMockDispatcher.close();
- checkEquals(() -> assertFalse(this.sl.getStatus()));
+ bmpMockDispatcher.close();
+ checkEquals(() -> assertFalse(sl.getStatus()));
}
@Test(timeout = 20000)
public void testCreateServer() throws Exception {
final int port = InetSocketAddressUtil.getRandomPort();
final BmpDispatcherImpl bmpDispatcher = new BmpDispatcherImpl(
- new NioEventLoopGroup(), new NioEventLoopGroup(), this.ctx, this.sessionFactory);
- final ChannelFuture futureServer = this.bmpMockDispatcher.createServer(
+ new NioEventLoopGroup(), new NioEventLoopGroup(), ctx, sessionFactory);
+ final ChannelFuture futureServer = bmpMockDispatcher.createServer(
new InetSocketAddress(InetAddresses.forString("0.0.0.0"), port));
futureServer.sync();
final ChannelFuture channelFuture = bmpDispatcher.createClient(
- InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port), this.slf, KeyMapping.getKeyMapping());
+ InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port), slf, KeyMapping.of());
final Channel channel = channelFuture.sync().channel();
assertTrue(channel.isActive());
- checkEquals(() -> assertTrue(this.sl.getStatus()));
+ checkEquals(() -> assertTrue(sl.getStatus()));
assertTrue(futureServer.channel().isActive());
channel.close();
bmpDispatcher.close();
- this.bmpMockDispatcher.close();
- checkEquals(() -> assertFalse(this.sl.getStatus()));
+ bmpMockDispatcher.close();
+ checkEquals(() -> assertFalse(sl.getStatus()));
}
}
@Before
public void setUp() {
final BmpExtensionProviderContext ctx = new SimpleBmpExtensionProviderContext();
- this.bmpActivator = new BmpActivator(
+ bmpActivator = new BmpActivator(
ServiceLoader.load(BGPExtensionConsumerContext.class).findFirst().orElseThrow());
- this.bmpActivator.start(ctx);
- this.bmpDispatcher = new BmpDispatcherImpl(new NioEventLoopGroup(), new NioEventLoopGroup(), ctx,
+ bmpActivator.start(ctx);
+ bmpDispatcher = new BmpDispatcherImpl(new NioEventLoopGroup(), new NioEventLoopGroup(), ctx,
new DefaultBmpSessionFactory());
}
@After
public void tearDown() throws Exception {
- this.bmpDispatcher.close();
+ bmpDispatcher.close();
}
@Test(timeout = 20000)
public void testMain() throws Exception {
final InetSocketAddress serverAddr = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress();
final BmpSessionListenerFactory bmpSessionListenerFactory = () -> BmpMockTest.this.sessionListener;
- final ChannelFuture futureServer = this.bmpDispatcher.createServer(serverAddr,
- bmpSessionListenerFactory, KeyMapping.getKeyMapping());
+ final ChannelFuture futureServer = bmpDispatcher.createServer(serverAddr,
+ bmpSessionListenerFactory, KeyMapping.of());
final Channel serverChannel;
final int sessionUpWait;
if (futureServer.isSuccess()) {
"--pre_policy_routes",
"3"});
- verify(this.sessionListener, timeout(TimeUnit.SECONDS.toMillis(sessionUpWait)))
+ verify(sessionListener, timeout(TimeUnit.SECONDS.toMillis(sessionUpWait)))
.onSessionUp(any(BmpSession.class));
//1 * Initiate message + 3 * PeerUp Notification + 9 * Route Monitoring message
- verify(this.sessionListener, timeout(TimeUnit.SECONDS.toMillis(10))
+ verify(sessionListener, timeout(TimeUnit.SECONDS.toMillis(10))
.times(13))
.onMessage(any(Notification.class));
"--peers_count", "3", "--pre_policy_routes", "3", "--passive"});
Assert.assertEquals(1, futureServers.size());
futureServers.get(0).sync();
- final ChannelFuture futureClient = this.bmpDispatcher.createClient(serverAddr,
- bmpSessionListenerFactory, KeyMapping.getKeyMapping());
+ final ChannelFuture futureClient = bmpDispatcher.createClient(serverAddr,
+ bmpSessionListenerFactory, KeyMapping.of());
futureClient.sync();
final Channel serverChannel;
final int sessionUpWait;
sessionUpWait = 40;
}
- verify(this.sessionListener, timeout(TimeUnit.SECONDS.toMillis(sessionUpWait)))
+ verify(sessionListener, timeout(TimeUnit.SECONDS.toMillis(sessionUpWait)))
.onSessionUp(any(BmpSession.class));
//1 * Initiate message + 3 * PeerUp Notification + 9 * Route Monitoring message
- verify(this.sessionListener, timeout(TimeUnit.SECONDS.toMillis(10))
+ verify(sessionListener, timeout(TimeUnit.SECONDS.toMillis(10))
.times(13))
.onMessage(any(Notification.class));
*/
package org.opendaylight.protocol.concepts;
-import static com.google.common.base.Strings.isNullOrEmpty;
-
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Maps;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
-import java.util.HashMap;
+import java.util.Map;
import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.jdt.annotation.Nullable;
+import org.opendaylight.yangtools.concepts.Immutable;
+
+public final class KeyMapping implements Immutable {
+ private static final @NonNull KeyMapping EMPTY = new KeyMapping(ImmutableMap.of());
+
+ private final ImmutableMap<InetAddress, byte[]> map;
+
+ private KeyMapping(final Map<InetAddress, byte[]> map) {
+ this.map = ImmutableMap.copyOf(map);
+ }
+
+ public static @NonNull KeyMapping of() {
+ return EMPTY;
+ }
-public final class KeyMapping extends HashMap<InetAddress, byte[]> {
- private static final long serialVersionUID = 1L;
+ public static @NonNull KeyMapping of(final @NonNull InetAddress inetAddress, final @NonNull String password) {
+ return new KeyMapping(ImmutableMap.of(inetAddress, password.getBytes(StandardCharsets.US_ASCII)));
+ }
- private KeyMapping() {
- super();
+ public static @NonNull KeyMapping of(final Map<InetAddress, String> passwords) {
+ return passwords.isEmpty() ? of()
+ : new KeyMapping(Maps.transformValues(passwords, password -> password.getBytes(StandardCharsets.US_ASCII)));
}
- public static @NonNull KeyMapping getKeyMapping(final @NonNull InetAddress inetAddress,
- final @Nullable String password) {
- final KeyMapping keyMapping = new KeyMapping();
- if (!isNullOrEmpty(password)) {
- keyMapping.put(inetAddress, password.getBytes(StandardCharsets.US_ASCII));
- }
- return keyMapping;
+ public boolean isEmpty() {
+ return map.isEmpty();
}
- public static KeyMapping getKeyMapping() {
- return new KeyMapping();
+ public @NonNull Map<InetAddress, byte[]> asMap() {
+ // Careful: do not leak our byte[]s
+ return Maps.transformValues(map, byte[]::clone);
}
}
public PCEPDispatcherImpl(final @NonNull MessageRegistry registry,
final @NonNull PCEPSessionNegotiatorFactory<PCEPSessionImpl> negotiatorFactory,
final @NonNull EventLoopGroup bossGroup, final @NonNull EventLoopGroup workerGroup) {
- this.snf = requireNonNull(negotiatorFactory);
- this.hf = new PCEPHandlerFactory(registry);
+ snf = requireNonNull(negotiatorFactory);
+ hf = new PCEPHandlerFactory(registry);
if (Epoll.isAvailable()) {
this.bossGroup = new EpollEventLoopGroup();
this.workerGroup = new EpollEventLoopGroup();
this.bossGroup = requireNonNull(bossGroup);
this.workerGroup = requireNonNull(workerGroup);
}
- this.executor = requireNonNull(GlobalEventExecutor.INSTANCE);
+ executor = requireNonNull(GlobalEventExecutor.INSTANCE);
}
@Override
public final synchronized ChannelFuture createServer(final PCEPDispatcherDependencies dispatcherDependencies) {
- this.keys = dispatcherDependencies.getKeys();
+ keys = dispatcherDependencies.getKeys();
final ChannelPipelineInitializer initializer = (ch, promise) -> {
- ch.pipeline().addLast(this.hf.getDecoders());
- ch.pipeline().addLast("negotiator", this.snf
+ ch.pipeline().addLast(hf.getDecoders());
+ ch.pipeline().addLast("negotiator", snf
.getSessionNegotiator(dispatcherDependencies, ch, promise));
- ch.pipeline().addLast(this.hf.getEncoders());
+ ch.pipeline().addLast(hf.getEncoders());
};
final ServerBootstrap b = createServerBootstrap(initializer);
final ChannelFuture f = b.bind(address);
LOG.debug("Initiated server {} at {}.", f, address);
- this.keys = KeyMapping.getKeyMapping();
+ // FIXME: err, why are we resetting this?
+ keys = KeyMapping.of();
return f;
}
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(final SocketChannel ch) {
- initializer.initializeChannel(ch, new DefaultPromise<>(PCEPDispatcherImpl.this.executor));
+ initializer.initializeChannel(ch, new DefaultPromise<>(executor));
}
});
b.option(ChannelOption.SO_BACKLOG, SOCKET_BACKLOG_SIZE);
} else {
b.channel(NioServerSocketChannel.class);
}
- if (!this.keys.isEmpty()) {
+ if (!keys.isEmpty()) {
if (Epoll.isAvailable()) {
- b.option(EpollChannelOption.TCP_MD5SIG, this.keys);
+ b.option(EpollChannelOption.TCP_MD5SIG, keys.asMap());
} else {
throw new UnsupportedOperationException("Setting TCP-MD5 signatures is not supported",
Epoll.unavailabilityCause().getCause());
b.childOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1));
if (b.config().group() == null) {
- b.group(this.bossGroup, this.workerGroup);
+ b.group(bossGroup, workerGroup);
}
return b;
@Override
public final void close() {
if (Epoll.isAvailable()) {
- this.workerGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
- this.bossGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
+ workerGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
+ bossGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS);
}
}
@Override
public final PCEPSessionNegotiatorFactory<PCEPSessionImpl> getPCEPSessionNegotiatorFactory() {
- return this.snf;
+ return snf;
}
protected interface ChannelPipelineInitializer {
import java.net.InetSocketAddress;
import java.nio.channels.Channel;
import java.util.List;
+import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.junit.After;
import org.junit.Assert;
eventLoopGroup = new NioEventLoopGroup();
}
final MessageRegistry msgReg = new DefaultPCEPExtensionConsumerContext().getMessageHandlerRegistry();
- this.dispatcher = new PCEPDispatcherImpl(msgReg,
+ dispatcher = new PCEPDispatcherImpl(msgReg,
new DefaultPCEPSessionNegotiatorFactory(sessionProposal, 0),
eventLoopGroup, eventLoopGroup);
- doReturn(KeyMapping.getKeyMapping()).when(this.dispatcherDependencies).getKeys();
- doReturn(null).when(this.dispatcherDependencies).getPeerProposal();
+ doReturn(KeyMapping.of()).when(dispatcherDependencies).getKeys();
+ doReturn(null).when(dispatcherDependencies).getPeerProposal();
final PCEPDispatcherImpl dispatcher2 = new PCEPDispatcherImpl(msgReg,
new DefaultPCEPSessionNegotiatorFactory(sessionProposal, 0),
eventLoopGroup, eventLoopGroup);
- this.disp2Spy = spy(dispatcher2);
+ disp2Spy = spy(dispatcher2);
- this.pccMock = new PCCMock(new DefaultPCEPSessionNegotiatorFactory(sessionProposal, 0),
+ pccMock = new PCCMock(new DefaultPCEPSessionNegotiatorFactory(sessionProposal, 0),
new PCEPHandlerFactory(msgReg));
}
final InetSocketAddress clientAddr1 = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
final InetSocketAddress clientAddr2 = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
- doReturn(serverAddr).when(this.dispatcherDependencies).getAddress();
- doReturn(this.listenerFactory).when(this.dispatcherDependencies).getListenerFactory();
- doReturn(new SimpleSessionListener()).when(this.listenerFactory).getSessionListener();
- final ChannelFuture futureChannel = this.dispatcher.createServer(this.dispatcherDependencies);
+ doReturn(serverAddr).when(dispatcherDependencies).getAddress();
+ doReturn(listenerFactory).when(dispatcherDependencies).getListenerFactory();
+ doReturn(new SimpleSessionListener()).when(listenerFactory).getSessionListener();
+ final ChannelFuture futureChannel = dispatcher.createServer(dispatcherDependencies);
futureChannel.sync();
- final PCEPSessionImpl session1 = this.pccMock.createClient(clientAddr1,
+ final PCEPSessionImpl session1 = pccMock.createClient(clientAddr1,
RETRY_TIMER, CONNECT_TIMEOUT, SimpleSessionListener::new).get();
- final PCEPSessionImpl session2 = this.pccMock.createClient(clientAddr2,
+ final PCEPSessionImpl session2 = pccMock.createClient(clientAddr2,
RETRY_TIMER, CONNECT_TIMEOUT, SimpleSessionListener::new).get();
Assert.assertTrue(futureChannel.channel().isActive());
final InetSocketAddress serverAddr = new InetSocketAddress("0.0.0.0", port);
final InetSocketAddress clientAddr = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
- doReturn(serverAddr).when(this.dispatcherDependencies).getAddress();
- doReturn(this.listenerFactory).when(this.dispatcherDependencies).getListenerFactory();
- doReturn(new SimpleSessionListener()).when(this.listenerFactory).getSessionListener();
+ doReturn(serverAddr).when(dispatcherDependencies).getAddress();
+ doReturn(listenerFactory).when(dispatcherDependencies).getListenerFactory();
+ doReturn(new SimpleSessionListener()).when(listenerFactory).getSessionListener();
- this.dispatcher.createServer(this.dispatcherDependencies).sync();
- final Future<PCEPSessionImpl> futureClient = this.pccMock.createClient(clientAddr, RETRY_TIMER, CONNECT_TIMEOUT,
+ dispatcher.createServer(dispatcherDependencies).sync();
+ final Future<PCEPSessionImpl> futureClient = pccMock.createClient(clientAddr, RETRY_TIMER, CONNECT_TIMEOUT,
SimpleSessionListener::new);
futureClient.sync();
try (PCEPSessionImpl ignored = futureClient.get()) {
- this.pccMock.createClient(clientAddr, RETRY_TIMER, CONNECT_TIMEOUT,
+ pccMock.createClient(clientAddr, RETRY_TIMER, CONNECT_TIMEOUT,
SimpleSessionListener::new).get();
Assert.fail();
} catch (final ExecutionException e) {
final int port = InetSocketAddressUtil.getRandomPort();
final InetSocketAddress clientAddr = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
- doReturn(new InetSocketAddress("0.0.0.0", port)).when(this.dispatcherDependencies).getAddress();
- doReturn(this.listenerFactory).when(this.dispatcherDependencies).getListenerFactory();
- doReturn(new SimpleSessionListener()).when(this.listenerFactory).getSessionListener();
- this.dispatcher.createServer(this.dispatcherDependencies).sync();
- final PCEPSessionImpl session1 = this.pccMock.createClient(clientAddr,
+ doReturn(new InetSocketAddress("0.0.0.0", port)).when(dispatcherDependencies).getAddress();
+ doReturn(listenerFactory).when(dispatcherDependencies).getListenerFactory();
+ doReturn(new SimpleSessionListener()).when(listenerFactory).getSessionListener();
+ dispatcher.createServer(dispatcherDependencies).sync();
+ final PCEPSessionImpl session1 = pccMock.createClient(clientAddr,
RETRY_TIMER, CONNECT_TIMEOUT, SimpleSessionListener::new).get();
assertEquals(clientAddr.getAddress(), session1.getRemoteAddress());
assertEquals(KEEP_ALIVE, session1.getKeepAliveTimerValue().shortValue());
session1.closeChannel().sync();
- final PCEPSessionImpl session2 = this.pccMock.createClient(clientAddr,
+ final PCEPSessionImpl session2 = pccMock.createClient(clientAddr,
RETRY_TIMER, CONNECT_TIMEOUT, SimpleSessionListener::new).get();
assertEquals(clientAddr.getAddress(), session1.getRemoteAddress());
final int port = InetSocketAddressUtil.getRandomPort();
final InetSocketAddress clientAddr1 = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
final InetSocketAddress clientAddr2 = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
- final KeyMapping keys = KeyMapping.getKeyMapping(clientAddr1.getAddress(), "CLIENT1_ADDRESS");
- keys.put(clientAddr2.getAddress(), "CLIENT2_ADDRESS".getBytes());
+ final KeyMapping keys = KeyMapping.of(Map.of(
+ clientAddr1.getAddress(), "CLIENT1_ADDRESS",
+ clientAddr2.getAddress(), "CLIENT2_ADDRESS"));
- doReturn(new InetSocketAddress("0.0.0.0", port)).when(this.dispatcherDependencies).getAddress();
+ doReturn(new InetSocketAddress("0.0.0.0", port)).when(dispatcherDependencies).getAddress();
- final ChannelFuture futureChannel = this.disp2Spy.createServer(this.dispatcherDependencies);
+ final ChannelFuture futureChannel = disp2Spy.createServer(dispatcherDependencies);
futureChannel.sync();
- verify(this.disp2Spy).createServerBootstrap(any(PCEPDispatcherImpl.ChannelPipelineInitializer.class));
+ verify(disp2Spy).createServerBootstrap(any(PCEPDispatcherImpl.ChannelPipelineInitializer.class));
}
@After
public void tearDown() {
- this.dispatcher.close();
- this.disp2Spy.close();
+ dispatcher.close();
+ disp2Spy.close();
}
private static class PCCMock {
PCCMock(final PCEPSessionNegotiatorFactory<PCEPSessionImpl> negotiatorFactory,
final PCEPHandlerFactory factory) {
- this.workerGroup = new NioEventLoopGroup();
+ workerGroup = new NioEventLoopGroup();
this.negotiatorFactory = requireNonNull(negotiatorFactory);
this.factory = requireNonNull(factory);
- this.executor = requireNonNull(GlobalEventExecutor.INSTANCE);
+ executor = requireNonNull(GlobalEventExecutor.INSTANCE);
}
Future<PCEPSessionImpl> createClient(final InetSocketAddress address, final int retryTimer,
final int connectTimeout, final PCEPSessionListenerFactory listenerFactory) {
return createClient(address, retryTimer, connectTimeout, (ch, promise) -> {
- ch.pipeline().addLast(this.factory.getDecoders());
- ch.pipeline().addLast("negotiator", this.negotiatorFactory.getSessionNegotiator(
+ ch.pipeline().addLast(factory.getDecoders());
+ ch.pipeline().addLast("negotiator", negotiatorFactory.getSessionNegotiator(
() -> listenerFactory, ch, promise));
- ch.pipeline().addLast(this.factory.getEncoders());
+ ch.pipeline().addLast(factory.getEncoders());
});
}
Future<PCEPSessionImpl> createClient(final InetSocketAddress address, final int retryTimer,
final int connectTimeout, final PCEPDispatcherImpl.ChannelPipelineInitializer initializer) {
final Bootstrap b = new Bootstrap();
- final PCEPProtocolSessionPromise<PCEPSessionImpl> p = new PCEPProtocolSessionPromise<>(this.executor,
+ final PCEPProtocolSessionPromise<PCEPSessionImpl> p = new PCEPProtocolSessionPromise<>(executor,
address, retryTimer, connectTimeout, b);
b.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE).handler(new ChannelInitializer<SocketChannel>() {
@Override
private void setWorkerGroup(final Bootstrap bootstrap) {
if (bootstrap.config().group() == null) {
- bootstrap.group(this.workerGroup);
+ bootstrap.group(workerGroup);
}
}
}
private final Timer timer = new HashedWheelTimer();
private final MessageRegistry registry;
- private PCCDispatcherImpl pccDispatcher;
-
PCCsBuilder(final int lsps, final boolean pcError, final int pccCount,
final @NonNull InetSocketAddress localAddress, final @NonNull List<InetSocketAddress> remoteAddress,
final short keepAlive, final short deadTimer, final @Nullable String password, final long reconnectTime,
this.stateTimeout = stateTimeout;
this.pcepCapabilities = pcepCapabilities;
- this.registry = new DefaultPCEPExtensionConsumerContext().getMessageHandlerRegistry();
+ registry = new DefaultPCEPExtensionConsumerContext().getMessageHandlerRegistry();
}
void createPCCs(final Uint64 initialDBVersion, final Optional<TimerHandler> timerHandler) {
- InetAddress currentAddress = this.localAddress.getAddress();
- this.pccDispatcher = new PCCDispatcherImpl(registry);
+ InetAddress currentAddress = localAddress.getAddress();
+ PCCDispatcherImpl pccDispatcher = new PCCDispatcherImpl(registry);
+
if (timerHandler.isPresent()) {
- timerHandler.get().setPCCDispatcher(this.pccDispatcher);
+ timerHandler.get().setPCCDispatcher(pccDispatcher);
}
- for (int i = 0; i < this.pccCount; i++) {
- final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(this.lsps, currentAddress,
- this.redelegationTimeout, this.stateTimeout, this.timer, timerHandler);
- createPCC(new InetSocketAddress(currentAddress, this.localAddress.getPort()), tunnelManager,
- initialDBVersion);
+ for (int i = 0; i < pccCount; i++) {
+ final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(lsps, currentAddress,
+ redelegationTimeout, stateTimeout, timer, timerHandler);
+ createPCC(pccDispatcher, new InetSocketAddress(currentAddress, localAddress.getPort()), tunnelManager,
+ initialDBVersion);
currentAddress = InetAddresses.increment(currentAddress);
}
}
- private void createPCC(final @NonNull InetSocketAddress plocalAddress,
+ private void createPCC(final PCCDispatcherImpl pccDispatcher, final @NonNull InetSocketAddress plocalAddress,
final PCCTunnelManager tunnelManager, final Uint64 initialDBVersion) {
final PCEPSessionNegotiatorFactory<PCEPSessionImpl> snf = getSessionNegotiatorFactory();
- for (final InetSocketAddress pceAddress : this.remoteAddress) {
- this.pccDispatcher.createClient(pceAddress, this.reconnectTime, () -> new PCCSessionListener(
- this.remoteAddress.indexOf(pceAddress), tunnelManager, this.pcError), snf,
- KeyMapping.getKeyMapping(pceAddress.getAddress(), this.password), plocalAddress, initialDBVersion);
+ for (final InetSocketAddress pceAddress : remoteAddress) {
+ pccDispatcher.createClient(pceAddress, reconnectTime,
+ () -> new PCCSessionListener(remoteAddress.indexOf(pceAddress), tunnelManager, pcError), snf,
+ password == null ? KeyMapping.of() : KeyMapping.of(pceAddress.getAddress(), password),
+ plocalAddress, initialDBVersion);
}
}
private PCEPSessionNegotiatorFactory<PCEPSessionImpl> getSessionNegotiatorFactory() {
- final List<PCEPCapability> capabilities = Lists.newArrayList(this.pcepCapabilities);
- return new DefaultPCEPSessionNegotiatorFactory(new BasePCEPSessionProposalFactory(this.deadTimer,
- this.keepAlive, capabilities), 0);
+ final List<PCEPCapability> capabilities = Lists.newArrayList(pcepCapabilities);
+ return new DefaultPCEPSessionNegotiatorFactory(new BasePCEPSessionProposalFactory(deadTimer,
+ keepAlive, capabilities), 0);
}
}
public PCCDispatcherImpl(final @NonNull MessageRegistry registry) {
if (Epoll.isAvailable()) {
- this.workerGroup = new EpollEventLoopGroup();
+ workerGroup = new EpollEventLoopGroup();
} else {
- this.workerGroup = new NioEventLoopGroup();
+ workerGroup = new NioEventLoopGroup();
}
- this.factory = new PCEPHandlerFactory(registry);
+ factory = new PCEPHandlerFactory(registry);
}
@Override
final PCEPSessionListenerFactory listenerFactory, final PCEPSessionNegotiatorFactory negotiatorFactory,
final KeyMapping keys, final InetSocketAddress localAddress, final Uint64 dbVersion) {
final Bootstrap b = new Bootstrap();
- b.group(this.workerGroup);
+ b.group(workerGroup);
b.localAddress(localAddress);
setChannelFactory(b, keys);
b.option(ChannelOption.SO_KEEPALIVE, true);
final ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<>() {
@Override
protected void initChannel(final SocketChannel ch) {
- ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getDecoders());
+ ch.pipeline().addLast(factory.getDecoders());
ch.pipeline().addLast("negotiator", negotiatorFactory.getSessionNegotiator(
new PCEPSessionNegotiatorFactoryDependencies() {
@Override
return new PCCPeerProposal(dbVersion);
}
}, ch, promise));
- ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getEncoders());
+ ch.pipeline().addLast(factory.getEncoders());
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelInactive(final ChannelHandlerContext ctx) {
}
if (!keys.isEmpty()) {
if (Epoll.isAvailable()) {
- bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys);
+ bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys.asMap());
} else {
throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
}
@Override
public void close() {
try {
- this.workerGroup.shutdownGracefully().get();
+ workerGroup.shutdownGracefully().get();
} catch (final InterruptedException | ExecutionException e) {
LOG.warn("Failed to properly close dispatcher.", e);
}
pcepDispatcher = new PCEPDispatcherImpl(registry, nf, bossGroup, workerGroup);
serverAddress = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress();
clientAddress = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(0);
- doReturn(KeyMapping.getKeyMapping()).when(dispatcherDependencies).getKeys();
+ doReturn(KeyMapping.of()).when(dispatcherDependencies).getKeys();
doReturn(serverAddress).when(dispatcherDependencies).getAddress();
doReturn(null).when(dispatcherDependencies).getPeerProposal();
}
@Test(timeout = 20000)
public void testClientReconnect() throws Exception {
final Future<PCEPSession> futureSession = dispatcher.createClient(serverAddress, 1,
- new TestingSessionListenerFactory(), nf, KeyMapping.getKeyMapping(), clientAddress);
+ new TestingSessionListenerFactory(), nf, KeyMapping.of(), clientAddress);
final TestingSessionListenerFactory slf = new TestingSessionListenerFactory();
doReturn(slf).when(dispatcherDependencies).getListenerFactory();
return pccDispatcher.createClient(remoteAddress, -1, () -> {
pccSessionListener = new PCCSessionListener(1, tunnelManager, false);
return pccSessionListener;
- }, snf, KeyMapping.getKeyMapping(), localAddress, dbVersion);
+ }, snf, KeyMapping.of(), localAddress, dbVersion);
}
private PCEPSessionNegotiatorFactory<PCEPSessionImpl> getSessionNegotiatorFactory() {
}
private static class DispatcherDependencies implements PCEPDispatcherDependencies {
- final KeyMapping keys = KeyMapping.getKeyMapping();
+ private final KeyMapping keys = KeyMapping.of();
private final InetSocketAddress address;
private final TestingSessionListenerFactory listenerFactory;
private final PCEPPeerProposal peerProposal;
public final class TestToolPCEPDispatcherDependencies implements PCEPDispatcherDependencies {
private final PCEPSessionListenerFactory listenerFactory = new TestingSessionListenerFactory();
private final InetSocketAddress address;
- private final KeyMapping keys = KeyMapping.getKeyMapping();
TestToolPCEPDispatcherDependencies(final InetSocketAddress address) {
this.address = address;
@Override
public KeyMapping getKeys() {
- return keys;
+ return KeyMapping.of();
}
@Override
try (PCCDispatcherImpl pccDispatcher = new PCCDispatcherImpl(
new DefaultPCEPExtensionConsumerContext().getMessageHandlerRegistry())) {
- pccDispatcher.createClient(serverAddr, -1, SimpleSessionListener::new, snf,
- KeyMapping.getKeyMapping(), clientAddr).get();
+ pccDispatcher.createClient(serverAddr, -1, SimpleSessionListener::new, snf, KeyMapping.of(), clientAddr)
+ .get();
}
}
}
import com.google.common.net.InetAddresses;
import java.net.InetAddress;
import java.net.InetSocketAddress;
+import java.util.HashMap;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.opendaylight.protocol.concepts.KeyMapping;
import org.opendaylight.protocol.pcep.SpeakerIdMapping;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressNoZone;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.config.rev200120.pcep.config.SessionConfig;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.config.rev181109.PcepNodeConfig;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.sync.optimizations.config.rev181109.PcepNodeSyncConfig;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
+import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
-public final class PCEPTopologyConfiguration {
- private final InetSocketAddress address;
- private final KeyMapping keys;
- private final TopologyId topologyId;
+public final class PCEPTopologyConfiguration implements Immutable {
+ private final @NonNull InetSocketAddress address;
+ private final @NonNull KeyMapping keys;
private final short rpcTimeout;
private final @NonNull SpeakerIdMapping speakerIds;
- private final InstanceIdentifier<Topology> topology;
+ private final @NonNull KeyedInstanceIdentifier<Topology, TopologyKey> topology;
public PCEPTopologyConfiguration(final @NonNull SessionConfig config, final @NonNull Topology topology) {
- requireNonNull(topology);
- address = PCEPTopologyProviderUtil.getInetSocketAddress(requireNonNull(config.getListenAddress()),
- requireNonNull(config.getListenPort()));
- keys = requireNonNull(PCEPTopologyProviderUtil.contructKeys(topology));
+ this.topology = InstanceIdentifier.create(NetworkTopology.class).child(Topology.class, topology.key());
+ address = getInetSocketAddress(config.getListenAddress(), config.getListenPort());
+ keys = constructKeys(topology.getNode());
speakerIds = contructSpeakersId(topology.getNode());
- topologyId = requireNonNull(topology.getTopologyId());
rpcTimeout = config.getRpcTimeout();
- this.topology = InstanceIdentifier.builder(NetworkTopology.class)
- .child(Topology.class, new TopologyKey(topologyId)).build();
}
public @NonNull TopologyId getTopologyId() {
- return topologyId;
+ return topology.getKey().getTopologyId();
}
- public @NonNull InstanceIdentifier<Topology> getTopology() {
+ public @NonNull KeyedInstanceIdentifier<Topology, TopologyKey> getTopology() {
return topology;
}
return speakerIds;
}
+ private static @NonNull KeyMapping constructKeys(final @Nullable Map<NodeKey, Node> nodes) {
+ if (nodes == null) {
+ return KeyMapping.of();
+ }
+
+ final var passwords = new HashMap<InetAddress, String>();
+ for (var node : nodes.values()) {
+ if (node != null) {
+ final var nodeConfig = node.augmentation(PcepNodeConfig.class);
+ if (nodeConfig != null) {
+ final var sessionConfig = nodeConfig.getSessionConfig();
+ if (sessionConfig != null) {
+ final var rfc2385KeyPassword = sessionConfig.getPassword();
+ if (rfc2385KeyPassword != null) {
+ final String password = rfc2385KeyPassword.getValue();
+ if (!password.isEmpty()) {
+ passwords.put(nodeAddress(node), password);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return KeyMapping.of(passwords);
+ }
+
private static @NonNull SpeakerIdMapping contructSpeakersId(final @Nullable Map<NodeKey, Node> nodes) {
if (nodes == null) {
return SpeakerIdMapping.of();
if (nodeSyncConfig != null) {
final var speakerEntityId = nodeSyncConfig.getSpeakerEntityIdValue();
if (speakerEntityId != null) {
- builder.put(InetAddresses.forString(node.getNodeId().getValue()), speakerEntityId);
+ builder.put(nodeAddress(node), speakerEntityId);
}
}
}
return SpeakerIdMapping.copyOf(builder.build());
}
+
+ private static InetAddress nodeAddress(final Node node) {
+ return InetAddresses.forString(node.getNodeId().getValue());
+ }
+
+ private static @NonNull InetSocketAddress getInetSocketAddress(final IpAddressNoZone address,
+ final PortNumber port) {
+ return new InetSocketAddress(IetfInetUtil.INSTANCE.inetAddressForNoZone(requireNonNull(address)),
+ port.getValue().toJava());
+ }
}
+++ /dev/null
-/*
- * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.bgpcep.pcep.topology.provider.config;
-
-import com.google.common.net.InetAddresses;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.nio.charset.StandardCharsets;
-import java.util.Objects;
-import org.eclipse.jdt.annotation.NonNull;
-import org.opendaylight.protocol.concepts.KeyMapping;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressNoZone;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.rfc2385.cfg.rev160324.Rfc2385Key;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.config.rev181109.PcepNodeConfig;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
-
-final class PCEPTopologyProviderUtil {
- private PCEPTopologyProviderUtil() {
- // Hidden on purpose
- }
-
- static KeyMapping contructKeys(final @NonNull Topology topology) {
- final KeyMapping ret = KeyMapping.getKeyMapping();
- if (topology.getNode() == null) {
- return ret;
- }
- topology.nonnullNode().values().stream()
- .filter(Objects::nonNull)
- .filter(node -> node.augmentation(PcepNodeConfig.class) != null)
- .filter(node -> node.augmentation(PcepNodeConfig.class).getSessionConfig() != null)
- .filter(node -> node.augmentation(PcepNodeConfig.class)
- .getSessionConfig().getPassword() != null)
- .filter(node -> !node.augmentation(PcepNodeConfig.class)
- .getSessionConfig().getPassword().getValue().isEmpty())
- .forEach(node -> {
- final PcepNodeConfig config = node.augmentation(PcepNodeConfig.class);
- final Rfc2385Key rfc2385KeyPassword = config.getSessionConfig().getPassword();
- final InetAddress address = InetAddresses.forString(node.getNodeId().getValue());
- ret.put(address, rfc2385KeyPassword.getValue().getBytes(StandardCharsets.US_ASCII));
- });
-
- return ret;
- }
-
- static InetSocketAddress getInetSocketAddress(final @NonNull IpAddressNoZone address,
- final @NonNull PortNumber port) {
- return new InetSocketAddress(IetfInetUtil.INSTANCE.inetAddressForNoZone(address), port.getValue().toJava());
- }
-}
import java.lang.reflect.ParameterizedType;
import java.net.InetSocketAddress;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
+import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
static final short DEAD_TIMER = 30;
static final short KEEP_ALIVE = 10;
static final short RPC_TIMEOUT = 4;
- private static final TopologyId TEST_TOPOLOGY_ID = new TopologyId("testtopo");
+ private static final TopologyKey TEST_TOPOLOGY_ID = new TopologyKey(new TopologyId("testtopo"));
static final InstanceIdentifier<Topology> TOPO_IID = InstanceIdentifier.builder(NetworkTopology.class)
- .child(Topology.class, new TopologyKey(TEST_TOPOLOGY_ID)).build();
+ .child(Topology.class, TEST_TOPOLOGY_ID).build();
private static final String IPV4_MASK = "/32";
final String testAddress = InetSocketAddressUtil.getRandomLoopbackIpAddress();
final NodeId nodeId = new NodeId("pcc://" + this.testAddress);
.getListenAddress();
doReturn(new PortNumber(Uint16.valueOf(4189))).when(this.sessionConfig).getListenPort();
doReturn(RPC_TIMEOUT).when(this.sessionConfig).getRpcTimeout();
- doReturn(TEST_TOPOLOGY_ID).when(this.topology).getTopologyId();
+ doReturn(TEST_TOPOLOGY_ID).when(this.topology).key();
doCallRealMethod().when(this.topology).nonnullNode();
- doReturn(Collections.emptyMap()).when(this.topology).getNode();
+ doReturn(Map.of()).when(this.topology).getNode();
doReturn(null).when(this.topologyDependencies).getPceServerProvider();
final PCEPTopologyConfiguration configDep = new PCEPTopologyConfiguration(this.sessionConfig, this.topology);