Create client dispatcher for testing. 31/14831/5
authorMilos Fabian <milfabia@cisco.com>
Wed, 4 Feb 2015 15:10:35 +0000 (16:10 +0100)
committerMilos Fabian <milfabia@cisco.com>
Mon, 9 Feb 2015 08:04:02 +0000 (08:04 +0000)
-allows client to be binded to specified IP address

Change-Id: I1f665e30ed452ec672f16c7b3a39ca9a2e42706a
Signed-off-by: Milos Fabian <milfabia@cisco.com>
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/BGPDispatcherImplTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/SimpleSessionListener.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/TestClientDispatcher.java [new file with mode: 0644]

index a32416645d6db9f2cf8fa61e037a291b862d8506..1bbaf276f8b84c459659053ba4b64654000c7f9f 100644 (file)
@@ -8,6 +8,7 @@
 
 package org.opendaylight.protocol.bgp.rib.impl;
 
+import com.google.common.base.Optional;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
 import io.netty.channel.Channel;
@@ -24,9 +25,6 @@ import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
 import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
 import org.opendaylight.protocol.bgp.parser.spi.pojo.ServiceLoaderBGPExtensionProviderContext;
@@ -52,45 +50,34 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.type
 
 public class BGPDispatcherImplTest {
 
-    private static final Ipv4Address IPV4 = new Ipv4Address("127.0.10.0");
-    private static final InetSocketAddress ADDRESS = new InetSocketAddress(IPV4.getValue(), 1790);
+    private static final InetSocketAddress ADDRESS = new InetSocketAddress("127.0.10.0", 1790);
+    private static final InetSocketAddress CLIENT_ADDRESS = new InetSocketAddress("127.0.11.0", 1791);
+    private static final InetSocketAddress CLIENT_ADDRESS2 = new InetSocketAddress("127.0.12.0", 1792);
     private static final AsNumber AS_NUMBER = new AsNumber(30L);
     private static final int TIMEOUT = 5000;
 
     private final BgpTableType ipv4tt = new BgpTableTypeImpl(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
 
     private BGPDispatcherImpl dispatcher;
+    private TestClientDispatcher clientDispatcher;
 
-    @Mock
     private BGPPeerRegistry registry;
 
     private Channel channel;
 
-    private SimpleSessionListener sessionListener;
-
     @Before
     public void setUp() throws BGPDocumentedException {
-        MockitoAnnotations.initMocks(this);
-        this.sessionListener = new SimpleSessionListener();
         final EventLoopGroup group = new NioEventLoopGroup();
-
-        final List<BgpParameters> tlvs = Lists.newArrayList();
-        final List<OptionalCapabilities> capas = Lists.newArrayList();
-        capas.add(new OptionalCapabilitiesBuilder().setCParameters(
-            new MultiprotocolCaseBuilder().setMultiprotocolCapability(
-                new MultiprotocolCapabilityBuilder().setAfi(this.ipv4tt.getAfi()).setSafi(this.ipv4tt.getSafi()).build()).build()).build());
-        capas.add(new OptionalCapabilitiesBuilder().setCParameters(new As4BytesCaseBuilder().setAs4BytesCapability(new As4BytesCapabilityBuilder().setAsNumber(
-                new AsNumber(30L)).build()).build()).build());
-        tlvs.add(new BgpParametersBuilder().setOptionalCapabilities(capas).build());
-        final BGPSessionPreferences prefs = new BGPSessionPreferences(AS_NUMBER, (short) 90, new Ipv4Address(ADDRESS.getAddress().getHostAddress()), tlvs);
-        Mockito.doReturn(true).when(this.registry).isPeerConfigured(Mockito.any(IpAddress.class));
-        Mockito.doReturn(prefs).when(this.registry).getPeerPreferences(Mockito.any(IpAddress.class));
-        Mockito.doNothing().when(this.registry).removePeerSession(Mockito.any(IpAddress.class));
-        Mockito.doReturn(this.sessionListener).when(this.registry).getPeer(Mockito.any(IpAddress.class), Mockito.any(Ipv4Address.class), Mockito.any(Ipv4Address.class));
-
+        this.registry = new StrictBGPPeerRegistry();
+        this.registry.addPeer(new IpAddress(new Ipv4Address(CLIENT_ADDRESS.getAddress().getHostAddress())),
+                new SimpleSessionListener(), createPreferences(CLIENT_ADDRESS));
+        this.registry.addPeer(new IpAddress(new Ipv4Address(ADDRESS.getAddress().getHostAddress())),
+                new SimpleSessionListener(), createPreferences(ADDRESS));
         this.dispatcher = new BGPDispatcherImpl(ServiceLoaderBGPExtensionProviderContext.getSingletonInstance().getMessageRegistry(), group, group);
+        this.clientDispatcher = new TestClientDispatcher(group, group, ServiceLoaderBGPExtensionProviderContext.getSingletonInstance().getMessageRegistry(),
+                CLIENT_ADDRESS);
 
-        final ChannelFuture future = dispatcher.createServer(this.registry, new InetSocketAddress("0.0.0.0", 1790), new BGPServerSessionValidator());
+        final ChannelFuture future = this.dispatcher.createServer(this.registry, ADDRESS, new BGPServerSessionValidator());
         future.addListener(new GenericFutureListener<Future<Void>>() {
             @Override
             public void operationComplete(Future<Void> future) {
@@ -101,28 +88,36 @@ public class BGPDispatcherImplTest {
         });
         this.channel = future.channel();
     }
+
     @Test
     public void testCreateClient() throws InterruptedException, ExecutionException {
-        final BGPSessionImpl session = this.dispatcher.createClient(ADDRESS, AS_NUMBER, this.registry, new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, TIMEOUT)).get();
-        Assert.assertTrue(this.sessionListener.up);
+        final BGPSessionImpl session = this.clientDispatcher.createClient(ADDRESS, AS_NUMBER, this.registry,
+                new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, TIMEOUT), Optional.<InetSocketAddress>absent()).get();
         Assert.assertEquals(BGPSessionImpl.State.UP, session.getState());
         Assert.assertEquals(AS_NUMBER, session.getAsNumber());
-        Assert.assertEquals(IPV4, session.getBgpId());
         Assert.assertEquals(Sets.newHashSet(this.ipv4tt), session.getAdvertisedTableTypes());
         session.close();
     }
 
     @After
-    public void tearDown() {
-        this.channel.close();
+    public void tearDown() throws Exception {
+        this.channel.close().get();
         this.dispatcher.close();
+        this.registry.close();
     }
 
     @Test
     public void testCreateReconnectingClient() throws InterruptedException, ExecutionException {
-        final Future<Void> cf = this.dispatcher.createReconnectingClient(ADDRESS, AS_NUMBER, this.registry, new ReconnectStrategyFctImpl(), new ReconnectStrategyFctImpl());
-        cf.await(500);
-        Assert.assertTrue(this.sessionListener.up);
+        final SimpleSessionListener listener = new SimpleSessionListener();
+        this.registry.addPeer(new IpAddress(new Ipv4Address(CLIENT_ADDRESS2.getAddress().getHostAddress())), listener, createPreferences(CLIENT_ADDRESS2));
+        final Future<Void> cf = this.clientDispatcher.createReconnectingClient(CLIENT_ADDRESS2, AS_NUMBER, this.registry,
+                new ReconnectStrategyFctImpl(), Optional.<InetSocketAddress>absent());
+        final Channel channel2 = this.dispatcher.createServer(this.registry, CLIENT_ADDRESS2, new BGPServerSessionValidator()).channel();
+        Thread.sleep(1000);
+        Assert.assertTrue(listener.up);
+        Assert.assertTrue(channel2.isActive());
+        cf.cancel(true);
+        listener.releaseConnection();
     }
 
     private static final class ReconnectStrategyFctImpl implements ReconnectStrategyFactory {
@@ -133,4 +128,16 @@ public class BGPDispatcherImplTest {
 
     }
 
+    private BGPSessionPreferences createPreferences(final InetSocketAddress socketAddress) {
+        final List<BgpParameters> tlvs = Lists.newArrayList();
+        final List<OptionalCapabilities> capas = Lists.newArrayList();
+        capas.add(new OptionalCapabilitiesBuilder().setCParameters(
+            new MultiprotocolCaseBuilder().setMultiprotocolCapability(
+                new MultiprotocolCapabilityBuilder().setAfi(this.ipv4tt.getAfi()).setSafi(this.ipv4tt.getSafi()).build()).build()).build());
+        capas.add(new OptionalCapabilitiesBuilder().setCParameters(new As4BytesCaseBuilder().setAs4BytesCapability(new As4BytesCapabilityBuilder().setAsNumber(
+                new AsNumber(30L)).build()).build()).build());
+        tlvs.add(new BgpParametersBuilder().setOptionalCapabilities(capas).build());
+        return new BGPSessionPreferences(AS_NUMBER, (short) 4, new Ipv4Address(socketAddress.getAddress().getHostAddress()), tlvs);
+    }
+
 }
index c6e3029252484bf7b1b10c047ba10fd5c40c99e6..4db0248b46766450a2b0672bfc68f6e3450556fc 100644 (file)
@@ -29,6 +29,8 @@ public class SimpleSessionListener implements ReusableBGPPeer {
 
     public boolean down = false;
 
+    private BGPSession session;
+
     public List<Notification> getListMsg() {
         return this.listMsg;
     }
@@ -42,6 +44,7 @@ public class SimpleSessionListener implements ReusableBGPPeer {
     @Override
     public void onSessionUp(final BGPSession session) {
         LOG.debug("Session Up");
+        this.session = session;
         this.up = true;
     }
 
@@ -59,6 +62,9 @@ public class SimpleSessionListener implements ReusableBGPPeer {
     @Override
     public void releaseConnection() {
         LOG.debug("Releasing connection");
+        if (this.session != null) {
+            this.session.close();
+        }
     }
 
     @Override
diff --git a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/TestClientDispatcher.java b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/TestClientDispatcher.java
new file mode 100644 (file)
index 0000000..72b50d3
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. 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.bgp.rib.impl;
+
+import com.google.common.base.Optional;
+import io.netty.bootstrap.Bootstrap;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.Promise;
+import java.net.InetSocketAddress;
+import org.opendaylight.protocol.bgp.parser.spi.MessageRegistry;
+import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
+import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
+import org.opendaylight.protocol.framework.AbstractDispatcher;
+import org.opendaylight.protocol.framework.ReconnectStrategy;
+import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
+
+public class TestClientDispatcher extends AbstractDispatcher<BGPSessionImpl, BGPSessionListener> {
+
+    private static final String NEGOTIATOR = "negotiator";
+
+    private final BGPHandlerFactory hf;
+    private InetSocketAddress localAddress;
+    private final InetSocketAddress defaulAddress;
+
+    protected TestClientDispatcher(final EventLoopGroup bossGroup, final EventLoopGroup workerGroup, final MessageRegistry messageRegistry,
+            final InetSocketAddress locaAddress) {
+        super(bossGroup, workerGroup);
+        this.hf = new BGPHandlerFactory(messageRegistry);
+        this.localAddress = locaAddress;
+        this.defaulAddress = locaAddress;
+    }
+
+    public synchronized Future<BGPSessionImpl> createClient(final InetSocketAddress remoteAddress,
+            final AsNumber remoteAs, final BGPPeerRegistry listener, final ReconnectStrategy strategy, final Optional<InetSocketAddress> localAddress) {
+        setLocalAddress(localAddress);
+        final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(remoteAs, listener);
+        return super.createClient(remoteAddress, strategy, new PipelineInitializer<BGPSessionImpl>() {
+
+            @Override
+            public void initializeChannel(SocketChannel ch, Promise<BGPSessionImpl> promise) {
+                ch.pipeline().addLast(TestClientDispatcher.this.hf.getDecoders());
+                ch.pipeline().addLast(NEGOTIATOR, snf.getSessionNegotiator(null, ch, promise));
+                ch.pipeline().addLast(TestClientDispatcher.this.hf.getEncoders());
+            }
+        });
+    }
+
+    public synchronized Future<Void> createReconnectingClient(final InetSocketAddress address,
+        final AsNumber remoteAs, final BGPPeerRegistry peerRegistry, final ReconnectStrategyFactory reconnectStrategyFactory,
+        final Optional<InetSocketAddress> localAddress) {
+        setLocalAddress(localAddress);
+        final BGPClientSessionNegotiatorFactory snf = new BGPClientSessionNegotiatorFactory(remoteAs, peerRegistry);
+        final Future<Void> ret = super.createReconnectingClient(address, reconnectStrategyFactory, new PipelineInitializer<BGPSessionImpl>() {
+            @Override
+            public void initializeChannel(final SocketChannel ch, final Promise<BGPSessionImpl> promise) {
+                ch.pipeline().addLast(TestClientDispatcher.this.hf.getDecoders());
+                ch.pipeline().addLast(NEGOTIATOR, snf.getSessionNegotiator(null, ch, promise));
+                ch.pipeline().addLast(TestClientDispatcher.this.hf.getEncoders());
+            }
+        });
+
+        return ret;
+    }
+
+    @Override
+    protected void customizeBootstrap(Bootstrap b) {
+        b.localAddress(this.localAddress);
+        super.customizeBootstrap(b);
+    }
+
+    private synchronized void setLocalAddress(final Optional<InetSocketAddress> localAddress) {
+        if (localAddress.isPresent()) {
+            this.localAddress = localAddress.get();
+        } else {
+            this.localAddress = defaulAddress;
+        }
+    }
+}