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