Do not use JdkFutureAdapters in BgpPeerRpc
[bgpcep.git] / bgp / rib-impl / src / test / java / org / opendaylight / protocol / bgp / rib / impl / GracefulRestartTest.java
1 /*
2  * Copyright (c) 2018 AT&T Intellectual Property. 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 package org.opendaylight.protocol.bgp.rib.impl;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertFalse;
12 import static org.junit.Assert.assertTrue;
13 import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.checkIdleState;
14 import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.checkStateIsNotRestarting;
15 import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.checkUpState;
16 import static org.opendaylight.protocol.util.CheckUtil.checkReceivedMessages;
17 import static org.opendaylight.protocol.util.CheckUtil.readDataOperational;
18 import static org.opendaylight.protocol.util.CheckUtil.waitFutureSuccess;
19
20 import com.google.common.collect.ImmutableMap;
21 import io.netty.channel.Channel;
22 import io.netty.channel.ChannelFuture;
23 import java.net.InetSocketAddress;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Optional;
32 import java.util.Set;
33 import java.util.stream.Collectors;
34 import org.junit.After;
35 import org.junit.Before;
36 import org.junit.Test;
37 import org.mockito.Mockito;
38 import org.opendaylight.protocol.bgp.mode.api.PathSelectionMode;
39 import org.opendaylight.protocol.bgp.mode.impl.add.all.paths.AllPathSelection;
40 import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
41 import org.opendaylight.protocol.bgp.rib.impl.config.BgpPeer;
42 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Address;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Prefix;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev180329.bgp.rib.rib.loc.rib.tables.routes.Ipv4RoutesCase;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev180329.bgp.rib.rib.loc.rib.tables.routes.Ipv6RoutesCase;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Open;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.OpenBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.ProtocolVersion;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Update;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.open.message.BgpParameters;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.BgpTableType;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpReachNlri;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.BgpRib;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.PeerRole;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.RibId;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.Rib;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.RibKey;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.LocRib;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.Tables;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.BgpOrigin;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.Ipv4AddressFamily;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.Ipv6AddressFamily;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.UnicastSubsequentAddressFamily;
69 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
70 import org.opendaylight.yangtools.yang.binding.Notification;
71
72 public class GracefulRestartTest extends AbstractAddPathTest {
73
74     private BGPSessionImpl session;
75     private BGPPeer peer;
76     private final Set<TablesKey> afiSafiAdvertised = new HashSet<>();
77     private final Set<TablesKey> gracefulAfiSafiAdvertised = new HashSet<>();
78     private RIBImpl ribImpl;
79     private Channel serverChannel;
80     private final SimpleSessionListener listener = new SimpleSessionListener();
81     private final BgpParameters parameters = createParameter(false, true, Collections.singletonMap(TABLES_KEY, true));
82     private static final int DEFERRAL_TIMER = 5;
83     private static final RibId RIBID = new RibId("test-rib");
84     private static final Ipv4Prefix PREFIX2 = new Ipv4Prefix("2.2.2.2/32");
85     private static final Ipv6Prefix PREFIX3 = new Ipv6Prefix("dead:beef::/64");
86     private static final Ipv6Address IPV6_NEXT_HOP = new Ipv6Address("dead:beef::1");
87     private static final TablesKey IPV6_TABLES_KEY = new TablesKey(Ipv6AddressFamily.class,
88             UnicastSubsequentAddressFamily.class);
89
90     private static final InstanceIdentifier<LocRib> LOC_RIB_IID = InstanceIdentifier.builder(BgpRib.class)
91             .child(Rib.class, new RibKey(RIBID))
92             .child(LocRib.class)
93             .build();
94     private static final InstanceIdentifier<Tables> IPV4_IID = LOC_RIB_IID.builder()
95             .child(Tables.class,TABLES_KEY)
96             .build();
97     private static final InstanceIdentifier<Tables> IPV6_IID = LOC_RIB_IID.builder()
98             .child(Tables.class, IPV6_TABLES_KEY)
99             .build();
100
101     @Override
102     @Before
103     public void setUp() throws Exception {
104         super.setUp();
105         final Map<TablesKey, PathSelectionMode> pathTables
106                 = ImmutableMap.of(TABLES_KEY, new AllPathSelection());
107         final ArrayList<BgpTableType> tableTypes = new ArrayList<>(TABLES_TYPE);
108         tableTypes.add(new BgpTableTypeImpl(Ipv6AddressFamily.class, UnicastSubsequentAddressFamily.class));
109         this.ribImpl = new RIBImpl(this.tableRegistry, RIBID, AS_NUMBER, BGP_ID, this.ribExtension,
110                 this.serverDispatcher, this.codecsRegistry,
111                 getDomBroker(), getDataBroker(), this.policies, tableTypes, pathTables);
112
113         this.ribImpl.instantiateServiceInstance();
114         this.ribImpl.onGlobalContextUpdated(this.schemaService.getGlobalContext());
115         final ChannelFuture channelFuture = this.serverDispatcher.createServer(new InetSocketAddress(RIB_ID, PORT));
116         waitFutureSuccess(channelFuture);
117         this.serverChannel = channelFuture.channel();
118
119         gracefulAfiSafiAdvertised.add(TABLES_KEY);
120         afiSafiAdvertised.add(TABLES_KEY);
121         afiSafiAdvertised.add(IPV6_TABLES_KEY);
122         final BgpPeer bgpPeer = Mockito.mock(BgpPeer.class);
123         Mockito.doReturn(GRACEFUL_RESTART_TIME).when(bgpPeer).getGracefulRestartTimer();
124         Mockito.doReturn(Optional.empty()).when(bgpPeer).getErrorHandling();
125         Mockito.doReturn(createParameter(false, true, Collections.singletonMap(TABLES_KEY, false))
126                 .getOptionalCapabilities()).when(bgpPeer).getBgpFixedCapabilities();
127         this.peer = configurePeer(this.tableRegistry, PEER1, this.ribImpl, parameters, PeerRole.Ibgp,
128                 this.serverRegistry, afiSafiAdvertised, gracefulAfiSafiAdvertised, Collections.emptyMap(), bgpPeer);
129         this.session = createPeerSession(PEER1, parameters, this.listener);
130     }
131
132     @Override
133     @After
134     public void tearDown() throws Exception {
135         waitFutureSuccess(this.serverChannel.close());
136         this.session.close();
137         super.tearDown();
138     }
139
140     /**
141      * Test correct behavior when connection restart is unnoticed.
142      * "Correct" means that the previous TCP session MUST be closed, and the new one retained.
143      * Since the previous connection is considered to be terminated, no NOTIFICATION message should be sent.
144      */
145     @Test
146     public void resetConnectionOnOpenTest() {
147
148         checkReceivedMessages(this.listener, 2);
149         final Open open = createClassicOpen(true);
150         this.session.writeAndFlush(open);
151         checkIdleState(this.peer);
152         checkReceivedMessages(this.listener, 2);
153     }
154
155     /**
156      * Test that routes from peer that has advertised the Graceful Restart Capability MUST be retained
157      * for all the address families that were previously received in the Graceful Restart Capability.
158      *
159      * @throws Exception on reading Rib failure
160      */
161     @Test
162     public void retainRoutesOnPeerRestartTest() throws Exception {
163         final List<Ipv4Prefix> ipv4Prefixes = Arrays.asList(new Ipv4Prefix(PREFIX1), new Ipv4Prefix(PREFIX2));
164         final List<Ipv6Prefix> ipv6Prefixes = Collections.singletonList(new Ipv6Prefix(PREFIX3));
165         insertRoutes(ipv4Prefixes, ipv6Prefixes);
166         checkLocRibIpv4Routes(2);
167         checkLocRibIpv6Routes(1);
168
169         this.session.close();
170         checkIdleState(this.peer);
171         checkLocRibIpv4Routes(2);
172         checkLocRibIpv6Routes(0);
173     }
174
175     /**
176      * If the session does not get re-established within the "Restart Time"
177      * that the peer advertised previously, the Receiving Speaker MUST
178      * delete all the stale routes from the peer that it is retaining.
179      *
180      * @throws Exception on reading Rib failure
181      */
182     @Test
183     public void removeRoutesOnHoldTimeExpireTest() throws Exception {
184         retainRoutesOnPeerRestartTest();
185         checkStateIsNotRestarting(peer, GRACEFUL_RESTART_TIME);
186         checkLocRibIpv4Routes(0);
187         checkLocRibIpv6Routes(0);
188     }
189
190     /**
191      * Once the session is re-established, if the Graceful
192      * Restart Capability is not received in the re-established session at
193      * all, then the Receiving Speaker MUST immediately remove all the stale
194      * routes from the peer that it is retaining for that address family.
195      *
196      * @throws Exception on reading Rib failure
197      */
198     @Test
199     public void removeRoutesOnMissingGracefulRestartTest() throws Exception {
200         retainRoutesOnPeerRestartTest();
201         this.session = createPeerSession(PEER1, createParameter(false, true, null), this.listener);
202         checkUpState(listener);
203         checkLocRibIpv4Routes(0);
204         checkLocRibIpv6Routes(0);
205     }
206
207     /**
208      * Once the session is re-established, if a specific address family is not included
209      * in the newly received Graceful Restart Capability, then the Receiving Speaker
210      * MUST immediately remove all the stale routes from the peer that it is retaining
211      * for that address family.
212      *
213      *
214      * @throws Exception on reading Rib failure
215      */
216     @Test
217     public void removeRoutesOnMissingGracefulRestartAfiSafiTest() throws Exception {
218         retainRoutesOnPeerRestartTest();
219         this.session = createPeerSession(PEER1, createParameter(false, true,
220                 Collections.singletonMap(TABLES_KEY, false)), this.listener);
221         checkUpState(listener);
222         checkUpState(this.peer);
223         checkLocRibIpv4Routes(0);
224         checkLocRibIpv6Routes(0);
225     }
226
227     /**
228      * Once the End-of-RIB marker for an address family is received from the peer, it MUST
229      * immediately remove any routes from the peer that are still marked as stale for that
230      * address family.
231      *
232      * @throws Exception on reading Rib failure
233      */
234     @Test
235     public void removeStaleRoutesAfterRestartTest() throws Exception {
236         retainRoutesOnPeerRestartTest();
237         this.session = createPeerSession(PEER1, createParameter(false, true,
238                 Collections.singletonMap(TABLES_KEY, true)), this.listener);
239         checkUpState(this.listener);
240         final List<Ipv4Prefix> ipv4prefixes = Arrays.asList(new Ipv4Prefix(PREFIX1));
241         insertRoutes(ipv4prefixes, null);
242         insertRoutes(null, null);
243         checkLocRibIpv4Routes(1);
244         checkLocRibIpv6Routes(0);
245     }
246
247     /**
248      * Perform local graceful restart and verify routes are preserved.
249      *
250      * @throws Exception on reading Rib failure
251      */
252     @Test
253     public void performLocalGracefulRestart() throws Exception {
254         final List<Ipv4Prefix> ipv4prefixes = Arrays.asList(new Ipv4Prefix(PREFIX1), new Ipv4Prefix(PREFIX2));
255         final List<Ipv6Prefix> ipv6prefixes = Arrays.asList(new Ipv6Prefix(PREFIX3));
256         insertRoutes(ipv4prefixes, ipv6prefixes);
257         checkLocRibIpv4Routes(2);
258         checkLocRibIpv6Routes(1);
259
260         this.peer.restartGracefully(DEFERRAL_TIMER).get();
261         this.session = createPeerSession(PEER1, this.parameters, this.listener);
262         checkUpState(this.listener);
263         checkUpState(this.peer);
264         checkLocRibIpv4Routes(2);
265         checkLocRibIpv6Routes(0);
266     }
267
268     /**
269      * Wait with route selection until EOT is received.
270      *
271      * @throws Exception on reading Rib failure
272      */
273     @Test
274     public void waitForEORonLocalGracefulRestart() throws Exception {
275         performLocalGracefulRestart();
276         final List<Ipv4Prefix> ipv4prefixes = Arrays.asList(new Ipv4Prefix(PREFIX1));
277         final List<Ipv6Prefix> ipv6prefixes = Arrays.asList(new Ipv6Prefix(PREFIX3));
278         insertRoutes(ipv4prefixes, ipv6prefixes);
279         checkLocRibIpv4Routes(2);
280         checkLocRibIpv6Routes(0);
281         insertRoutes(null, null);
282         checkLocRibIpv4Routes(2);
283         checkLocRibIpv6Routes(1);
284     }
285
286     /**
287      * Wait with route selection until deferral time is expired.
288      *
289      * @throws Exception on reading Rib failure
290      */
291     @Test
292     public void waitForDeferralTimerOnLocalGracefulRestart() throws Exception {
293         performLocalGracefulRestart();
294         final List<Ipv4Prefix> ipv4prefixes = Arrays.asList(new Ipv4Prefix(PREFIX1));
295         final List<Ipv6Prefix> ipv6prefixes = Arrays.asList(new Ipv6Prefix(PREFIX3));
296         insertRoutes(ipv4prefixes, ipv6prefixes);
297         checkLocRibIpv4Routes(2);
298         checkLocRibIpv6Routes(0);
299         checkStateIsNotRestarting(this.peer, DEFERRAL_TIMER);
300         checkLocRibIpv4Routes(2);
301         checkLocRibIpv6Routes(1);
302     }
303
304     /**
305      * After graceful restart is performed from peer side we have to re-advertise routes followed by
306      * End-of-RIB marker.
307      *
308      * @throws Exception on reading Rib failure
309      */
310     @Test
311     public void verifySendEORafterRestartTest() throws Exception {
312         final SimpleSessionListener listener2 = new SimpleSessionListener();
313         configurePeer(this.tableRegistry, PEER2, this.ribImpl, this.parameters, PeerRole.Ebgp,
314                 this.serverRegistry, afiSafiAdvertised, gracefulAfiSafiAdvertised);
315         final BGPSessionImpl session2 = createPeerSession(PEER2, this.parameters, listener2);
316         final List<Ipv4Prefix> ipv4Prefixes = Arrays.asList(new Ipv4Prefix(PREFIX1));
317         final List<Ipv4Prefix> ipv4Prefixes2 = Arrays.asList(new Ipv4Prefix(PREFIX2));
318         final List<Ipv6Prefix> ipv6Prefixes = Collections.singletonList(new Ipv6Prefix(PREFIX3));
319         insertRoutes(ipv4Prefixes, ipv6Prefixes);
320         insertRoutes(ipv4Prefixes2, PEER2, null, null, session2, BgpOrigin.Egp);
321         checkLocRibIpv4Routes(2);
322         checkLocRibIpv6Routes(1);
323         org.opendaylight.protocol.util.CheckUtil.checkReceivedMessages(this.listener, 3);
324         // verify sending of Ipv4 EOT, Ipv6 EOT and Ipv4 update with route
325         checkReceivedMessages(this.listener, 3);
326         assertTrue(this.listener.getListMsg().get(0) instanceof Update);
327         assertTrue(BgpPeerUtil.isEndOfRib((Update)this.listener.getListMsg().get(0)));
328         assertTrue(this.listener.getListMsg().get(1) instanceof Update);
329         assertTrue(BgpPeerUtil.isEndOfRib((Update)this.listener.getListMsg().get(1)));
330         assertTrue(this.listener.getListMsg().get(2) instanceof Update);
331         assertFalse(BgpPeerUtil.isEndOfRib((Update)this.listener.getListMsg().get(2)));
332
333         this.session.close();
334         checkIdleState(this.peer);
335         checkLocRibIpv4Routes(2);
336         checkLocRibIpv6Routes(0);
337         // verify nothing new was sent
338         checkReceivedMessages(this.listener, 3);
339
340         this.session = createPeerSession(PEER1, createParameter(false, true,
341                 Collections.singletonMap(TABLES_KEY, true)), this.listener);
342         checkUpState(listener);
343         checkUpState(this.peer);
344         org.opendaylight.protocol.util.CheckUtil.checkReceivedMessages(this.listener, 6);
345         // verify sending of Ipv4 update with route, Ipv4 EOT and Ipv6 EOT; order can vary based on ODTC order
346         final List<Notification> subList = this.listener.getListMsg().subList(3, 6);
347         int eotCount = 0;
348         int routeUpdateCount = 0;
349         for (Notification message : subList) {
350             if (BgpPeerUtil.isEndOfRib((Update) message)) {
351                 eotCount++;
352             } else {
353                 routeUpdateCount++;
354             }
355         }
356         assertEquals(2, eotCount);
357         assertEquals(1, routeUpdateCount);
358     }
359
360     private void checkLocRibIpv4Routes(final int expectedRoutesOnDS) throws Exception {
361         readDataOperational(getDataBroker(), IPV4_IID, table -> {
362             int size = 0;
363             final Ipv4RoutesCase routesCase = (Ipv4RoutesCase) table.getRoutes();
364             if (routesCase != null && routesCase.getIpv4Routes() != null
365                     && routesCase.getIpv4Routes().getIpv4Route() != null) {
366                 size = routesCase.getIpv4Routes().getIpv4Route().size();
367             }
368             assertEquals(expectedRoutesOnDS, size);
369             return table;
370         });
371     }
372
373     private void checkLocRibIpv6Routes(final int expectedRoutesOnDS) throws Exception {
374         readDataOperational(getDataBroker(), IPV6_IID, table -> {
375             int size = 0;
376             final Ipv6RoutesCase routesCase = (Ipv6RoutesCase) table.getRoutes();
377             if (routesCase != null && routesCase.getIpv6Routes() != null
378                     && routesCase.getIpv6Routes().getIpv6Route() != null) {
379                 size = routesCase.getIpv6Routes().getIpv6Route().size();
380             }
381             assertEquals(expectedRoutesOnDS, size);
382             return table;
383         });
384     }
385
386     private void insertRoutes(final List<Ipv4Prefix> ipv4prefixes, final List<Ipv6Prefix> ipv6prefixes) {
387         insertRoutes(ipv4prefixes, PEER1, ipv6prefixes, IPV6_NEXT_HOP, this.session, BgpOrigin.Igp);
388     }
389
390     private static void insertRoutes(final List<Ipv4Prefix> ipv4prefixes, final Ipv4Address ipv4NeighborAddress,
391                               final List<Ipv6Prefix> ipv6prefixes, final Ipv6Address ipv6NeighborAddress,
392                               final BGPSessionImpl session, final BgpOrigin peerRole) {
393         if (ipv4prefixes == null && ipv6prefixes == null) {
394             waitFutureSuccess(session.writeAndFlush(BgpPeerUtil.createEndOfRib(TABLES_KEY)));
395             waitFutureSuccess(session.writeAndFlush(BgpPeerUtil.createEndOfRib(IPV6_TABLES_KEY)));
396             return;
397         }
398
399         if (ipv4prefixes != null && !ipv4prefixes.isEmpty()) {
400             final MpReachNlri reachIpv4 = PeerUtil.createMpReachNlri(new IpAddress(ipv4NeighborAddress),
401                     ipv4prefixes.stream()
402                             .map(IpPrefix::new)
403                             .collect(Collectors.toList()));
404             final Update update1 = PeerUtil.createUpdate(peerRole, Collections.emptyList(), 100, reachIpv4, null);
405             waitFutureSuccess(session.writeAndFlush(update1));
406         }
407
408         if (ipv6prefixes != null && !ipv4prefixes.isEmpty()) {
409             final MpReachNlri reachIpv6 = PeerUtil.createMpReachNlri(new IpAddress(ipv6NeighborAddress),
410                     ipv6prefixes.stream()
411                             .map(IpPrefix::new)
412                             .collect(Collectors.toList()));
413             final Update update2 = PeerUtil.createUpdate(peerRole, Collections.emptyList(), 100, reachIpv6, null);
414             waitFutureSuccess(session.writeAndFlush(update2));
415         }
416     }
417
418     private static Open createClassicOpen(final boolean addGraceful) {
419         final Map<TablesKey, Boolean> graceful = new HashMap<>();
420         if (addGraceful) {
421             graceful.put(new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class), true);
422         }
423         return new OpenBuilder()
424                 .setMyAsNumber((int) AS)
425                 .setHoldTimer(HOLDTIMER)
426                 .setVersion(new ProtocolVersion((short) 4))
427                 .setBgpParameters(Collections.singletonList(createParameter(false, true, graceful)))
428                 .setBgpIdentifier(PEER1)
429                 .build();
430     }
431 }