BUG: 4831
[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.Matchers.any;
14 import static org.mockito.Mockito.doAnswer;
15 import static org.mockito.Mockito.doReturn;
16 import static org.mockito.Mockito.mock;
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.util.concurrent.Future;
25 import io.netty.util.concurrent.GenericFutureListener;
26 import io.netty.util.concurrent.GlobalEventExecutor;
27 import java.net.InetAddress;
28 import java.net.InetSocketAddress;
29 import java.net.UnknownHostException;
30 import java.util.List;
31 import java.util.concurrent.TimeUnit;
32 import org.junit.Assert;
33 import org.junit.Before;
34 import org.junit.Test;
35 import org.mockito.Matchers;
36 import org.mockito.Mock;
37 import org.mockito.Mockito;
38 import org.mockito.MockitoAnnotations;
39 import org.mockito.invocation.InvocationOnMock;
40 import org.mockito.stubbing.Answer;
41 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
42 import org.opendaylight.protocol.bgp.parser.BGPError;
43 import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.OpenBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.ProtocolVersion;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.UpdateBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParameters;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParametersBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.OptionalCapabilities;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.OptionalCapabilitiesBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.CParametersBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.c.parameters.As4BytesCapabilityBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.c.parameters.BgpExtendedMessageCapabilityBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.CParameters1;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.CParameters1Builder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.GracefulRestartCapabilityBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.MultiprotocolCapabilityBuilder;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.Ipv4AddressFamily;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.UnicastSubsequentAddressFamily;
68 import org.opendaylight.yangtools.yang.binding.Notification;
69
70 public class BGPSessionImplTest {
71
72     private static final int HOLD_TIMER = 3;
73     private static final AsNumber AS_NUMBER = new AsNumber(30L);
74     private static final Ipv4Address BGP_ID = new Ipv4Address("1.1.1.2");
75     private static final String LOCAL_IP = "1.1.1.4";
76     private static final int LOCAL_PORT = 12345;
77
78     @Mock
79     private EventLoop eventLoop;
80
81     @Mock
82     private Channel speakerListener;
83
84     @Mock
85     private ChannelPipeline pipeline;
86
87     @Mock
88     private ChannelHandler channelHandler;
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         MockitoAnnotations.initMocks(this);
103         final List<BgpParameters> tlvs = Lists.newArrayList();
104         this.classicOpen = new OpenBuilder().setMyAsNumber(AS_NUMBER.getValue().intValue()).setHoldTimer(HOLD_TIMER)
105                 .setVersion(new ProtocolVersion((short) 4)).setBgpParameters(tlvs).setBgpIdentifier(BGP_ID).build();
106
107         final List<OptionalCapabilities> capa = Lists.newArrayList();
108         capa.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(CParameters1.class,
109             new CParameters1Builder().setMultiprotocolCapability(new MultiprotocolCapabilityBuilder()
110                 .setAfi(this.ipv4tt.getAfi()).setSafi(this.ipv4tt.getSafi()).build())
111                 .setGracefulRestartCapability(new GracefulRestartCapabilityBuilder().build()).build())
112                 .setAs4BytesCapability(new As4BytesCapabilityBuilder().setAsNumber(AS_NUMBER).build())
113                 .setBgpExtendedMessageCapability(new BgpExtendedMessageCapabilityBuilder().build()).build()).build()
114         );
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(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(any(Runnable.class), any(long.class), any(TimeUnit.class));
140         doReturn("TestingChannel").when(this.speakerListener).toString();
141         doReturn(new InetSocketAddress(InetAddress.getByName(BGP_ID.getValue()), 179)).when(this.speakerListener).remoteAddress();
142         doReturn(new InetSocketAddress(InetAddress.getByName(LOCAL_IP), LOCAL_PORT)).when(this.speakerListener).localAddress();
143         doReturn(this.pipeline).when(this.speakerListener).pipeline();
144         doReturn(this.pipeline).when(this.pipeline).replace(any(ChannelHandler.class), any(String.class), any(ChannelHandler.class));
145         doReturn(this.channelHandler).when(this.pipeline).replace(Matchers.<Class<ChannelHandler>>any(), any(String.class), any(ChannelHandler.class));
146         doReturn(this.pipeline).when(this.pipeline).addLast(any(ChannelHandler.class));
147         doReturn(mock(ChannelFuture.class)).when(this.speakerListener).close();
148         this.listener = new SimpleSessionListener();
149         this.bgpSession = new BGPSessionImpl(this.listener, this.speakerListener, this.classicOpen, this.classicOpen.getHoldTimer(), null);
150     }
151
152     @Test
153     public void testBGPSession() {
154         this.bgpSession.sessionUp();
155         assertEquals(BGPSessionImpl.State.UP, this.bgpSession.getState());
156         assertEquals(AS_NUMBER, this.bgpSession.getAsNumber());
157         assertEquals(BGP_ID, this.bgpSession.getBgpId());
158         assertEquals(1, this.bgpSession.getAdvertisedTableTypes().size());
159         assertTrue(this.listener.up);
160         //test stats
161         final BgpSessionState state = this.bgpSession.getBgpSesionState();
162         assertEquals(HOLD_TIMER, state.getHoldtimeCurrent().intValue());
163         assertEquals(1, state.getKeepaliveCurrent().intValue());
164         assertEquals(BGPSessionImpl.State.UP.name(), state.getSessionState());
165         assertEquals(BGP_ID.getValue(), state.getPeerPreferences().getAddress());
166         assertEquals(AS_NUMBER.getValue(), state.getPeerPreferences().getAs());
167         assertEquals(true, state.getPeerPreferences().getBgpExtendedMessageCapability());
168         assertEquals(BGP_ID.getValue(), state.getPeerPreferences().getBgpId());
169         assertEquals(1, state.getPeerPreferences().getAdvertizedTableTypes().size());
170         assertEquals(HOLD_TIMER, state.getPeerPreferences().getHoldtime().intValue());
171         assertTrue(state.getPeerPreferences().getFourOctetAsCapability().booleanValue());
172         assertTrue(state.getPeerPreferences().getBgpExtendedMessageCapability().booleanValue());
173         assertTrue(state.getPeerPreferences().getGrCapability());
174         assertEquals(LOCAL_IP, state.getSpeakerPreferences().getAddress());
175         assertEquals(LOCAL_PORT, state.getSpeakerPreferences().getPort().intValue());
176         assertEquals(0, state.getMessagesStats().getTotalMsgs().getReceived().getCount().longValue());
177         assertEquals(0, state.getMessagesStats().getTotalMsgs().getSent().getCount().longValue());
178
179         this.bgpSession.handleMessage(new UpdateBuilder().build());
180         assertEquals(1, this.listener.getListMsg().size());
181         assertTrue(this.listener.getListMsg().get(0) instanceof Update);
182         assertEquals(1, state.getMessagesStats().getTotalMsgs().getReceived().getCount().longValue());
183         assertEquals(1, state.getMessagesStats().getUpdateMsgs().getReceived().getCount().longValue());
184         assertEquals(0, state.getMessagesStats().getUpdateMsgs().getSent().getCount().longValue());
185
186         this.bgpSession.handleMessage(new KeepaliveBuilder().build());
187         this.bgpSession.handleMessage(new KeepaliveBuilder().build());
188         assertEquals(3, state.getMessagesStats().getTotalMsgs().getReceived().getCount().longValue());
189         assertEquals(2, state.getMessagesStats().getKeepAliveMsgs().getReceived().getCount().longValue());
190         assertEquals(0, state.getMessagesStats().getKeepAliveMsgs().getSent().getCount().longValue());
191
192         this.bgpSession.close();
193         assertEquals(BGPSessionImpl.State.IDLE, this.bgpSession.getState());
194         assertEquals(1, this.receivedMsgs.size());
195         assertTrue(this.receivedMsgs.get(0) instanceof Notify);
196         final Notify error = (Notify) this.receivedMsgs.get(0);
197         assertEquals(BGPError.CEASE.getCode(), error.getErrorCode().shortValue());
198         assertEquals(BGPError.CEASE.getSubcode(), error.getErrorSubcode().shortValue());
199         Mockito.verify(this.speakerListener).close();
200         assertEquals(3, state.getMessagesStats().getTotalMsgs().getReceived().getCount().longValue());
201         assertEquals(1, state.getMessagesStats().getTotalMsgs().getSent().getCount().longValue());
202         assertEquals(1, state.getMessagesStats().getErrorMsgs().getErrorSent().getCount().longValue());
203         assertEquals(BGPError.CEASE.getCode(), state.getMessagesStats().getErrorMsgs().getErrorSent().getCode().shortValue());
204         assertEquals(BGPError.CEASE.getSubcode(), state.getMessagesStats().getErrorMsgs().getErrorSent().getSubCode().shortValue());
205
206         this.bgpSession.resetSessionStats();
207         assertEquals(0, state.getMessagesStats().getTotalMsgs().getReceived().getCount().longValue());
208         assertEquals(0, state.getMessagesStats().getTotalMsgs().getSent().getCount().longValue());
209         assertEquals(0, state.getMessagesStats().getErrorMsgs().getErrorSent().getCount().longValue());
210     }
211
212     @Test
213     public void testHandleOpenMsg() {
214         this.bgpSession.handleMessage(this.classicOpen);
215         Assert.assertEquals(BGPSessionImpl.State.IDLE, this.bgpSession.getState());
216         Assert.assertEquals(1, this.receivedMsgs.size());
217         Assert.assertTrue(this.receivedMsgs.get(0) instanceof Notify);
218         final Notify error = (Notify) this.receivedMsgs.get(0);
219         Assert.assertEquals(BGPError.FSM_ERROR.getCode(), error.getErrorCode().shortValue());
220         Assert.assertEquals(BGPError.FSM_ERROR.getSubcode(), error.getErrorSubcode().shortValue());
221         Mockito.verify(this.speakerListener).close();
222     }
223
224     @Test
225     public void testHandleNotifyMsg() {
226         this.bgpSession.handleMessage(new NotifyBuilder().setErrorCode(BGPError.BAD_BGP_ID.getCode()).setErrorSubcode(BGPError.BAD_BGP_ID.getSubcode()).build());
227         assertEquals(1, this.bgpSession.getBgpSesionState().getMessagesStats().getErrorMsgs().getErrorReceived().getCount().longValue());
228         assertEquals(BGPError.BAD_BGP_ID.getCode(), this.bgpSession.getBgpSesionState().getMessagesStats().getErrorMsgs().getErrorReceived().getCode().shortValue());
229         assertEquals(BGPError.BAD_BGP_ID.getSubcode(), this.bgpSession.getBgpSesionState().getMessagesStats().getErrorMsgs().getErrorReceived().getSubCode().shortValue());
230         Assert.assertEquals(BGPSessionImpl.State.IDLE, this.bgpSession.getState());
231         Mockito.verify(this.speakerListener).close();
232     }
233
234     @Test
235     public void testEndOfInput() {
236         this.bgpSession.sessionUp();
237         Assert.assertFalse(this.listener.down);
238         this.bgpSession.endOfInput();
239         Assert.assertTrue(this.listener.down);
240     }
241
242     @Test
243     public void testHoldTimerExpire() throws InterruptedException {
244         this.bgpSession.sessionUp();
245         Thread.sleep(3500);
246         Assert.assertEquals(BGPSessionImpl.State.IDLE, this.bgpSession.getState());
247         Assert.assertEquals(3, this.receivedMsgs.size());
248         Assert.assertTrue(this.receivedMsgs.get(2) instanceof Notify);
249         final Notify error = (Notify) this.receivedMsgs.get(2);
250         Assert.assertEquals(BGPError.HOLD_TIMER_EXPIRED.getCode(), error.getErrorCode().shortValue());
251         Assert.assertEquals(BGPError.HOLD_TIMER_EXPIRED.getSubcode(), error.getErrorSubcode().shortValue());
252         Mockito.verify(this.speakerListener).close();
253     }
254 }