8ad8d9e38bd75c84a2a63d3ca41fc11371d541cc
[bgpcep.git] / bgp / rib-impl / src / test / java / org / opendaylight / protocol / bgp / rib / impl / BGPSessionImplTest.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.protocol.bgp.rib.impl;
10
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertTrue;
13 import static org.mockito.Mockito.doAnswer;
14 import static org.mockito.Mockito.doReturn;
15 import static org.mockito.Mockito.mock;
16 import static org.opendaylight.protocol.bgp.rib.impl.BGPDispatcherImplTest.checkIdleState;
17
18 import com.google.common.collect.Lists;
19 import io.netty.channel.Channel;
20 import io.netty.channel.ChannelFuture;
21 import io.netty.channel.ChannelHandler;
22 import io.netty.channel.ChannelPipeline;
23 import io.netty.channel.EventLoop;
24 import io.netty.channel.embedded.EmbeddedChannel;
25 import io.netty.util.concurrent.Future;
26 import io.netty.util.concurrent.GenericFutureListener;
27 import io.netty.util.concurrent.GlobalEventExecutor;
28 import java.net.InetAddress;
29 import java.net.InetSocketAddress;
30 import java.net.UnknownHostException;
31 import java.util.List;
32 import java.util.concurrent.TimeUnit;
33 import org.junit.Assert;
34 import org.junit.Before;
35 import org.junit.Test;
36 import org.mockito.Matchers;
37 import org.mockito.Mock;
38 import org.mockito.Mockito;
39 import org.mockito.MockitoAnnotations;
40 import org.mockito.invocation.InvocationOnMock;
41 import org.mockito.stubbing.Answer;
42 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
43 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
44 import org.opendaylight.protocol.bgp.parser.BGPError;
45 import org.opendaylight.protocol.bgp.parser.BgpExtendedMessageUtil;
46 import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
47 import org.opendaylight.protocol.bgp.rib.spi.State;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
49 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.OpenBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.ProtocolVersion;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.UpdateBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParameters;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParametersBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.OptionalCapabilities;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.OptionalCapabilitiesBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.CParametersBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.c.parameters.As4BytesCapabilityBuilder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.CParameters1;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.CParameters1Builder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.GracefulRestartCapabilityBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.MultiprotocolCapabilityBuilder;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.Ipv4AddressFamily;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.UnicastSubsequentAddressFamily;
71 import org.opendaylight.yangtools.yang.binding.Notification;
72
73 public class BGPSessionImplTest {
74
75     private static final int HOLD_TIMER = 3;
76     private static final AsNumber AS_NUMBER = new AsNumber(30L);
77     private static final Ipv4Address BGP_ID = new Ipv4Address("1.1.1.2");
78     private static final String LOCAL_IP = "1.1.1.4";
79     private static final int LOCAL_PORT = 12345;
80
81     @Mock
82     private EventLoop eventLoop;
83
84     @Mock
85     private Channel speakerListener;
86
87     @Mock
88     private ChannelPipeline pipeline;
89
90     private final BgpTableType ipv4tt = new BgpTableTypeImpl(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
91
92     private final List<Notification> receivedMsgs = Lists.newArrayList();
93
94     private Open classicOpen;
95
96     private BGPSessionImpl bgpSession;
97
98     private SimpleSessionListener listener;
99
100     @Before
101     public void setUp() throws UnknownHostException {
102         new EmbeddedChannel();
103         MockitoAnnotations.initMocks(this);
104         final List<BgpParameters> tlvs = Lists.newArrayList();
105         this.classicOpen = new OpenBuilder().setMyAsNumber(AS_NUMBER.getValue().intValue()).setHoldTimer(HOLD_TIMER)
106                 .setVersion(new ProtocolVersion((short) 4)).setBgpParameters(tlvs).setBgpIdentifier(BGP_ID).build();
107
108         final List<OptionalCapabilities> capa = Lists.newArrayList();
109         capa.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(CParameters1.class,
110             new CParameters1Builder().setMultiprotocolCapability(new MultiprotocolCapabilityBuilder()
111                 .setAfi(this.ipv4tt.getAfi()).setSafi(this.ipv4tt.getSafi()).build())
112                 .setGracefulRestartCapability(new GracefulRestartCapabilityBuilder().build()).build())
113                 .setAs4BytesCapability(new As4BytesCapabilityBuilder().setAsNumber(AS_NUMBER).build()).build()).build());
114         capa.add(new OptionalCapabilitiesBuilder().setCParameters(BgpExtendedMessageUtil.EXTENDED_MESSAGE_CAPABILITY).build());
115         tlvs.add(new BgpParametersBuilder().setOptionalCapabilities(capa).build());
116
117         final ChannelFuture f = mock(ChannelFuture.class);
118         doReturn(null).when(f).addListener(Mockito.<GenericFutureListener<? extends Future<? super Void>>>any());
119
120         doAnswer(new Answer<Object>() {
121             @Override
122             public Object answer(final InvocationOnMock invocation) {
123                 final Object[] args = invocation.getArguments();
124                 BGPSessionImplTest.this.receivedMsgs.add((Notification) args[0]);
125                 return f;
126             }
127         }).when(this.speakerListener).writeAndFlush(Mockito.any(Notification.class));
128         doReturn(this.eventLoop).when(this.speakerListener).eventLoop();
129         doReturn(true).when(this.speakerListener).isActive();
130         doAnswer(new Answer<Void>() {
131             @Override
132             public Void answer(final InvocationOnMock invocation) throws Throwable {
133                 final Runnable command = (Runnable) invocation.getArguments()[0];
134                 final long delay = (long) invocation.getArguments()[1];
135                 final TimeUnit unit = (TimeUnit) invocation.getArguments()[2];
136                 GlobalEventExecutor.INSTANCE.schedule(command, delay, unit);
137                 return null;
138             }
139         }).when(this.eventLoop).schedule(Mockito.any(Runnable.class), Mockito.any(long.class), Mockito.any(TimeUnit.class));
140         doReturn("TestingChannel").when(this.speakerListener).toString();
141         doReturn(true).when(this.speakerListener).isWritable();
142         doReturn(new InetSocketAddress(InetAddress.getByName(BGP_ID.getValue()), 179)).when(this.speakerListener).remoteAddress();
143         doReturn(new InetSocketAddress(InetAddress.getByName(LOCAL_IP), LOCAL_PORT)).when(this.speakerListener).localAddress();
144         doReturn(this.pipeline).when(this.speakerListener).pipeline();
145         doReturn(this.pipeline).when(this.pipeline).replace(Mockito.any(ChannelHandler.class), Mockito.any(String.class), Mockito.any(ChannelHandler.class));
146         doReturn(null).when(this.pipeline).replace(Matchers.<Class<ChannelHandler>>any(), Mockito.any(String.class), Mockito.any(ChannelHandler.class));
147         doReturn(this.pipeline).when(this.pipeline).addLast(Mockito.any(ChannelHandler.class));
148         final ChannelFuture futureChannel = mock(ChannelFuture.class);
149         doReturn(null).when(futureChannel).addListener(Mockito.<GenericFutureListener<? extends Future<? super Void>>>any());
150         doReturn(futureChannel).when(this.speakerListener).close();
151         this.listener = new SimpleSessionListener();
152         this.bgpSession = new BGPSessionImpl(this.listener, this.speakerListener, this.classicOpen, this.classicOpen.getHoldTimer(), null);
153         this.bgpSession.setChannelExtMsgCoder(this.classicOpen);
154     }
155
156     @Test
157     public void testBGPSession() throws BGPDocumentedException {
158         this.bgpSession.sessionUp();
159         assertEquals(State.UP, this.bgpSession.getState());
160         assertEquals(AS_NUMBER, this.bgpSession.getAsNumber());
161         assertEquals(BGP_ID, this.bgpSession.getBgpId());
162         assertEquals(1, this.bgpSession.getAdvertisedTableTypes().size());
163         Assert.assertEquals(State.UP, this.listener.getState());
164
165         //test stats
166         final BgpSessionState state = this.bgpSession.getBgpSessionState();
167         assertEquals(HOLD_TIMER, state.getHoldtimeCurrent().intValue());
168         assertEquals(1, state.getKeepaliveCurrent().intValue());
169         assertEquals(State.UP.name(), state.getSessionState());
170         assertEquals(BGP_ID.getValue(), new String(state.getLocalPeerPreferences().getHost().getValue()));
171         assertEquals(AS_NUMBER.getValue(), state.getLocalPeerPreferences().getAs().getValue());
172         assertTrue(state.getLocalPeerPreferences().getBgpExtendedMessageCapability());
173         assertEquals(BGP_ID.getValue(), state.getLocalPeerPreferences().getBgpId().getValue());
174         assertEquals(1, state.getLocalPeerPreferences().getAdvertizedTableTypes().size());
175         assertEquals(HOLD_TIMER, state.getLocalPeerPreferences().getHoldtimer().intValue());
176         assertTrue(state.getLocalPeerPreferences().getFourOctetAsCapability().booleanValue());
177         assertTrue(state.getLocalPeerPreferences().getBgpExtendedMessageCapability().booleanValue());
178         assertTrue(state.getLocalPeerPreferences().getGrCapability());
179         assertEquals(LOCAL_IP, new String(state.getRemotePeerPreferences().getHost().getValue()));
180         assertEquals(LOCAL_PORT, state.getRemotePeerPreferences().getPort().getValue().intValue());
181         assertEquals(0, state.getMessagesStats().getTotalMsgs().getReceived().getCount().getValue().longValue());
182         assertEquals(0, state.getMessagesStats().getTotalMsgs().getSent().getCount().getValue().longValue());
183
184         this.bgpSession.handleMessage(new UpdateBuilder().build());
185         assertEquals(1, this.listener.getListMsg().size());
186         assertTrue(this.listener.getListMsg().get(0) instanceof Update);
187         assertEquals(1, state.getMessagesStats().getTotalMsgs().getReceived().getCount().getValue().longValue());
188         assertEquals(1, state.getMessagesStats().getUpdateMsgs().getReceived().getCount().getValue().longValue());
189         assertEquals(0, state.getMessagesStats().getUpdateMsgs().getSent().getCount().getValue().longValue());
190
191         this.bgpSession.handleMessage(new KeepaliveBuilder().build());
192         this.bgpSession.handleMessage(new KeepaliveBuilder().build());
193         assertEquals(3, state.getMessagesStats().getTotalMsgs().getReceived().getCount().getValue().longValue());
194         assertEquals(2, state.getMessagesStats().getKeepAliveMsgs().getReceived().getCount().getValue().longValue());
195         assertEquals(0, state.getMessagesStats().getKeepAliveMsgs().getSent().getCount().getValue().longValue());
196
197         this.bgpSession.close();
198         assertEquals(State.IDLE, this.bgpSession.getState());
199         assertEquals(1, this.receivedMsgs.size());
200         assertTrue(this.receivedMsgs.get(0) instanceof Notify);
201         final Notify error = (Notify) this.receivedMsgs.get(0);
202         assertEquals(BGPError.CEASE.getCode(), error.getErrorCode().shortValue());
203         assertEquals(BGPError.CEASE.getSubcode(), error.getErrorSubcode().shortValue());
204         Mockito.verify(this.speakerListener).close();
205         assertEquals(3, state.getMessagesStats().getTotalMsgs().getReceived().getCount().getValue().longValue());
206         assertEquals(1, state.getMessagesStats().getTotalMsgs().getSent().getCount().getValue().longValue());
207         assertEquals(1, state.getMessagesStats().getErrorMsgs().getErrorSentTotal().getCount().getValue().longValue());
208         assertEquals(1, state.getMessagesStats().getErrorMsgs().getErrorSent().get(0).getCount().getValue().longValue());
209         assertEquals(BGPError.CEASE.getCode(), state.getMessagesStats().getErrorMsgs().getErrorSent().get(0).getErrorCode().shortValue());
210         assertEquals(BGPError.CEASE.getSubcode(), state.getMessagesStats().getErrorMsgs().getErrorSent().get(0).getErrorSubcode().shortValue());
211
212         this.bgpSession.resetBgpSessionStats();
213         assertEquals(0, state.getMessagesStats().getTotalMsgs().getReceived().getCount().getValue().longValue());
214         assertEquals(0, state.getMessagesStats().getTotalMsgs().getSent().getCount().getValue().longValue());
215         assertEquals(0, state.getMessagesStats().getErrorMsgs().getErrorSentTotal().getCount().getValue().longValue());
216     }
217
218     @Test
219     public void testHandleOpenMsg() throws BGPDocumentedException {
220         this.bgpSession.handleMessage(this.classicOpen);
221         Assert.assertEquals(State.IDLE, this.bgpSession.getState());
222         Assert.assertEquals(1, this.receivedMsgs.size());
223         Assert.assertTrue(this.receivedMsgs.get(0) instanceof Notify);
224         final Notify error = (Notify) this.receivedMsgs.get(0);
225         Assert.assertEquals(BGPError.FSM_ERROR.getCode(), error.getErrorCode().shortValue());
226         Assert.assertEquals(BGPError.FSM_ERROR.getSubcode(), error.getErrorSubcode().shortValue());
227         Mockito.verify(this.speakerListener).close();
228     }
229
230     @Test
231     public void testHandleNotifyMsg() throws BGPDocumentedException {
232         this.bgpSession.handleMessage(new NotifyBuilder().setErrorCode(BGPError.BAD_BGP_ID.getCode()).setErrorSubcode(BGPError.BAD_BGP_ID.getSubcode()).build());
233         assertEquals(1, this.bgpSession.getBgpSessionState().getMessagesStats().getErrorMsgs().getErrorReceivedTotal().getCount().getValue().longValue());
234         assertEquals(1, this.bgpSession.getBgpSessionState().getMessagesStats().getErrorMsgs().getErrorReceived().get(0).getCount().getValue().longValue());
235         assertEquals(BGPError.BAD_BGP_ID.getCode(), this.bgpSession.getBgpSessionState().getMessagesStats().getErrorMsgs().getErrorReceived().get(0).getErrorCode().shortValue());
236         assertEquals(BGPError.BAD_BGP_ID.getSubcode(), this.bgpSession.getBgpSessionState().getMessagesStats().getErrorMsgs().getErrorReceived().get(0).getErrorSubcode().shortValue());
237         Assert.assertEquals(State.IDLE, this.bgpSession.getState());
238         Mockito.verify(this.speakerListener).close();
239     }
240
241     @Test
242     public void testEndOfInput() throws InterruptedException {
243         this.bgpSession.sessionUp();
244         Assert.assertEquals(State.UP, this.listener.getState());
245         this.bgpSession.endOfInput();
246         checkIdleState(this.listener);
247     }
248
249     @Test
250     public void testHoldTimerExpire() throws InterruptedException {
251         this.bgpSession.sessionUp();
252         checkIdleState(this.listener);
253         Assert.assertEquals(3, this.receivedMsgs.size());
254         Assert.assertTrue(this.receivedMsgs.get(2) instanceof Notify);
255         final Notify error = (Notify) this.receivedMsgs.get(2);
256         Assert.assertEquals(BGPError.HOLD_TIMER_EXPIRED.getCode(), error.getErrorCode().shortValue());
257         Assert.assertEquals(BGPError.HOLD_TIMER_EXPIRED.getSubcode(), error.getErrorSubcode().shortValue());
258         Mockito.verify(this.speakerListener).close();
259     }
260 }