Bug-2064: Implementation of RFC5492 Error handling.
[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.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.BGPError;
42 import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.NotifyBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.OpenBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.ProtocolVersion;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.UpdateBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.BgpParameters;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.BgpParametersBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.bgp.parameters.OptionalCapabilities;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.bgp.parameters.OptionalCapabilitiesBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.As4BytesCaseBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.as4.bytes._case.As4BytesCapabilityBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.MultiprotocolCaseBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.multiprotocol._case.MultiprotocolCapabilityBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.Ipv4AddressFamily;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.UnicastSubsequentAddressFamily;
64 import org.opendaylight.yangtools.yang.binding.Notification;
65
66 public class BGPSessionImplTest {
67
68     private static final int HOLD_TIMER = 3;
69     private static final AsNumber AS_NUMBER = new AsNumber(30L);
70     private static final Ipv4Address BGP_ID = new Ipv4Address("1.1.1.2");
71     private static final String LOCAL_IP = "1.1.1.4";
72     private static final int LOCAL_PORT = 12345;
73
74     @Mock
75     private EventLoop eventLoop;
76
77     @Mock
78     private Channel speakerListener;
79
80     @Mock
81     private ChannelPipeline pipeline;
82
83     private final BgpTableType ipv4tt = new BgpTableTypeImpl(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
84
85     private final List<Notification> receivedMsgs = Lists.newArrayList();
86
87     private Open classicOpen;
88
89     private BGPSessionImpl bgpSession;
90
91     private SimpleSessionListener listener;
92
93     @Before
94     public void setUp() throws UnknownHostException {
95         MockitoAnnotations.initMocks(this);
96         final List<BgpParameters> tlvs = Lists.newArrayList();
97         this.classicOpen = new OpenBuilder().setMyAsNumber(AS_NUMBER.getValue().intValue()).setHoldTimer(HOLD_TIMER).setVersion(new ProtocolVersion((short) 4)).setBgpParameters(
98                 tlvs).setBgpIdentifier(BGP_ID).build();
99
100         final List<OptionalCapabilities> capa = Lists.newArrayList();
101         capa.add(new OptionalCapabilitiesBuilder().setCParameters(
102             new MultiprotocolCaseBuilder().setMultiprotocolCapability(
103                 new MultiprotocolCapabilityBuilder().setAfi(this.ipv4tt.getAfi()).setSafi(this.ipv4tt.getSafi()).build()).build()).build());
104         capa.add(new OptionalCapabilitiesBuilder().setCParameters(new As4BytesCaseBuilder().setAs4BytesCapability(new As4BytesCapabilityBuilder().setAsNumber(
105             AS_NUMBER).build()).build()).build());
106         tlvs.add(new BgpParametersBuilder().setOptionalCapabilities(capa).build());
107
108         final ChannelFuture f = mock(ChannelFuture.class);
109         doReturn(null).when(f).addListener(Mockito.<GenericFutureListener<? extends Future<? super Void>>>any());
110
111         doAnswer(new Answer<Object>() {
112             @Override
113             public Object answer(final InvocationOnMock invocation) {
114                 final Object[] args = invocation.getArguments();
115                 BGPSessionImplTest.this.receivedMsgs.add((Notification) args[0]);
116                 return f;
117             }
118         }).when(this.speakerListener).writeAndFlush(any(Notification.class));
119         doReturn(this.eventLoop).when(this.speakerListener).eventLoop();
120         doAnswer(new Answer<Void>() {
121             @Override
122             public Void answer(InvocationOnMock invocation) throws Throwable {
123                 final Runnable command = (Runnable) invocation.getArguments()[0];
124                 final long delay = (long) invocation.getArguments()[1];
125                 final TimeUnit unit = (TimeUnit) invocation.getArguments()[2];
126                 GlobalEventExecutor.INSTANCE.schedule(command, delay, unit);
127                 return null;
128             }
129         }).when(this.eventLoop).schedule(any(Runnable.class), any(long.class), any(TimeUnit.class));
130         doReturn("TestingChannel").when(this.speakerListener).toString();
131         doReturn(new InetSocketAddress(InetAddress.getByName(BGP_ID.getValue()), 179)).when(this.speakerListener).remoteAddress();
132         doReturn(new InetSocketAddress(InetAddress.getByName(LOCAL_IP), LOCAL_PORT)).when(this.speakerListener).localAddress();
133         doReturn(this.pipeline).when(this.speakerListener).pipeline();
134         doReturn(this.pipeline).when(this.pipeline).replace(any(ChannelHandler.class), any(String.class), any(ChannelHandler.class));
135         doReturn(mock(ChannelFuture.class)).when(this.speakerListener).close();
136         this.listener = new SimpleSessionListener();
137         this.bgpSession = new BGPSessionImpl(this.listener, this.speakerListener, this.classicOpen, this.classicOpen.getHoldTimer());
138     }
139
140     @Test
141     public void testBGPSession() {
142         this.bgpSession.sessionUp();
143         assertEquals(BGPSessionImpl.State.Up, this.bgpSession.getState());
144         assertEquals(AS_NUMBER, this.bgpSession.getAsNumber());
145         assertEquals(BGP_ID, this.bgpSession.getBgpId());
146         assertEquals(1, this.bgpSession.getAdvertisedTableTypes().size());
147         assertTrue(this.listener.up);
148         //test stats
149         BgpSessionState state = this.bgpSession.getBgpSesionState();
150         assertEquals(HOLD_TIMER, state.getHoldtimeCurrent().intValue());
151         assertEquals(1, state.getKeepaliveCurrent().intValue());
152         assertEquals("Up", state.getSessionState());
153         assertEquals(BGP_ID.getValue(), state.getPeerPreferences().getAddress());
154         assertEquals(AS_NUMBER.getValue(), state.getPeerPreferences().getAs());
155         assertEquals(BGP_ID.getValue(), state.getPeerPreferences().getBgpId());
156         assertEquals(1, state.getPeerPreferences().getAdvertizedTableTypes().size());
157         assertEquals(HOLD_TIMER, state.getPeerPreferences().getHoldtime().intValue());
158         assertTrue(state.getPeerPreferences().getFourOctetAsCapability());
159         assertEquals(LOCAL_IP, state.getSpeakerPreferences().getAddress());
160         assertEquals(LOCAL_PORT, state.getSpeakerPreferences().getPort().intValue());
161         assertEquals(0, state.getMessagesStats().getTotalMsgs().getReceived().getCount().longValue());
162         assertEquals(0, state.getMessagesStats().getTotalMsgs().getSent().getCount().longValue());
163
164         this.bgpSession.handleMessage(new UpdateBuilder().build());
165         assertEquals(1, this.listener.getListMsg().size());
166         assertTrue(this.listener.getListMsg().get(0) instanceof Update);
167         assertEquals(1, state.getMessagesStats().getTotalMsgs().getReceived().getCount().longValue());
168         assertEquals(1, state.getMessagesStats().getUpdateMsgs().getReceived().getCount().longValue());
169         assertEquals(0, state.getMessagesStats().getUpdateMsgs().getSent().getCount().longValue());
170
171         this.bgpSession.handleMessage(new KeepaliveBuilder().build());
172         this.bgpSession.handleMessage(new KeepaliveBuilder().build());
173         assertEquals(3, state.getMessagesStats().getTotalMsgs().getReceived().getCount().longValue());
174         assertEquals(2, state.getMessagesStats().getKeepAliveMsgs().getReceived().getCount().longValue());
175         assertEquals(0, state.getMessagesStats().getKeepAliveMsgs().getSent().getCount().longValue());
176
177         this.bgpSession.close();
178         assertEquals(BGPSessionImpl.State.Idle, this.bgpSession.getState());
179         assertEquals(1, this.receivedMsgs.size());
180         assertTrue(this.receivedMsgs.get(0) instanceof Notify);
181         final Notify error = (Notify) this.receivedMsgs.get(0);
182         assertEquals(BGPError.CEASE.getCode(), error.getErrorCode().shortValue());
183         assertEquals(BGPError.CEASE.getSubcode(), error.getErrorSubcode().shortValue());
184         Mockito.verify(this.speakerListener).close();
185         assertEquals(3, state.getMessagesStats().getTotalMsgs().getReceived().getCount().longValue());
186         assertEquals(1, state.getMessagesStats().getTotalMsgs().getSent().getCount().longValue());
187         assertEquals(1, state.getMessagesStats().getErrorMsgs().getErrorSent().getCount().longValue());
188         assertEquals(BGPError.CEASE.getCode(), state.getMessagesStats().getErrorMsgs().getErrorSent().getCode().shortValue());
189         assertEquals(BGPError.CEASE.getSubcode(), state.getMessagesStats().getErrorMsgs().getErrorSent().getSubCode().shortValue());
190
191         this.bgpSession.resetSessionStats();
192         assertEquals(0, state.getMessagesStats().getTotalMsgs().getReceived().getCount().longValue());
193         assertEquals(0, state.getMessagesStats().getTotalMsgs().getSent().getCount().longValue());
194         assertEquals(0, state.getMessagesStats().getErrorMsgs().getErrorSent().getCount().longValue());
195     }
196
197     @Test
198     public void testHandleOpenMsg() {
199         this.bgpSession.handleMessage(this.classicOpen);
200         Assert.assertEquals(BGPSessionImpl.State.Idle, this.bgpSession.getState());
201         Assert.assertEquals(1, this.receivedMsgs.size());
202         Assert.assertTrue(this.receivedMsgs.get(0) instanceof Notify);
203         final Notify error = (Notify) this.receivedMsgs.get(0);
204         Assert.assertEquals(BGPError.FSM_ERROR.getCode(), error.getErrorCode().shortValue());
205         Assert.assertEquals(BGPError.FSM_ERROR.getSubcode(), error.getErrorSubcode().shortValue());
206         Mockito.verify(this.speakerListener).close();
207     }
208
209     @Test
210     public void testHandleNotifyMsg() {
211         this.bgpSession.handleMessage(new NotifyBuilder().setErrorCode(BGPError.BAD_BGP_ID.getCode()).setErrorSubcode(BGPError.BAD_BGP_ID.getSubcode()).build());
212         assertEquals(1, this.bgpSession.getBgpSesionState().getMessagesStats().getErrorMsgs().getErrorReceived().getCount().longValue());
213         assertEquals(BGPError.BAD_BGP_ID.getCode(), this.bgpSession.getBgpSesionState().getMessagesStats().getErrorMsgs().getErrorReceived().getCode().shortValue());
214         assertEquals(BGPError.BAD_BGP_ID.getSubcode(), this.bgpSession.getBgpSesionState().getMessagesStats().getErrorMsgs().getErrorReceived().getSubCode().shortValue());
215         Assert.assertEquals(BGPSessionImpl.State.Idle, this.bgpSession.getState());
216         Mockito.verify(this.speakerListener).close();
217     }
218
219     @Test
220     public void testEndOfInput() {
221         this.bgpSession.sessionUp();
222         Assert.assertFalse(this.listener.down);
223         this.bgpSession.endOfInput();
224         Assert.assertTrue(this.listener.down);
225     }
226
227     @Test
228     public void testHoldTimerExpire() throws InterruptedException {
229         this.bgpSession.sessionUp();
230         Thread.sleep(3500);
231         Assert.assertEquals(BGPSessionImpl.State.Idle, this.bgpSession.getState());
232         Assert.assertEquals(3, this.receivedMsgs.size());
233         Assert.assertTrue(this.receivedMsgs.get(2) instanceof Notify);
234         final Notify error = (Notify) this.receivedMsgs.get(2);
235         Assert.assertEquals(BGPError.HOLD_TIMER_EXPIRED.getCode(), error.getErrorCode().shortValue());
236         Assert.assertEquals(BGPError.HOLD_TIMER_EXPIRED.getSubcode(), error.getErrorSubcode().shortValue());
237         Mockito.verify(this.speakerListener).close();
238     }
239 }