Bug 5558 - Closing session after a large RIB is sent kills BGPCEP
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / BGPPeer.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 package org.opendaylight.protocol.bgp.rib.impl;
9
10 import com.google.common.base.MoreObjects;
11 import com.google.common.base.MoreObjects.ToStringHelper;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Lists;
14 import com.google.common.net.InetAddresses;
15 import java.util.ArrayList;
16 import java.util.Arrays;
17 import java.util.HashMap;
18 import java.util.HashSet;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Set;
22 import javax.annotation.concurrent.GuardedBy;
23 import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeMXBean;
24 import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeRegistration;
25 import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeRegistrator;
26 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpPeerState;
27 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
28 import org.opendaylight.controller.config.yang.bgp.rib.impl.RouteTable;
29 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
30 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
31 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
32 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
33 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
34 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
35 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionStatistics;
36 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
37 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContext;
38 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
39 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
40 import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason;
41 import org.opendaylight.protocol.bgp.rib.spi.Peer;
42 import org.opendaylight.protocol.bgp.rib.spi.RouterIds;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.DestinationIpv4Builder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.destination.ipv4.Ipv4Prefixes;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.destination.ipv4.Ipv4PrefixesBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.update.attributes.mp.reach.nlri.advertized.routes.destination.type.DestinationIpv4CaseBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.Attributes;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.AttributesBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.Attributes1;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.Attributes2;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.RouteRefresh;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.add.path.capability.AddressFamilies;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpReachNlri;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpReachNlriBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpUnreachNlri;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpUnreachNlriBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.mp.reach.nlri.AdvertizedRoutesBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.mp.unreach.nlri.WithdrawnRoutesBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.peer.rpc.rev160322.BgpPeerRpcService;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.peer.rpc.rev160322.PeerContext;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.PeerKey;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.AddressFamily;
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.SubsequentAddressFamily;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.UnicastSubsequentAddressFamily;
72 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
73 import org.opendaylight.yangtools.yang.binding.Notification;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
76
77 /**
78  * Class representing a peer. We have a single instance for each peer, which provides translation from BGP events into
79  * RIB actions.
80  */
81 public class BGPPeer implements BGPSessionListener, Peer, AutoCloseable, BGPPeerRuntimeMXBean, TransactionChainListener {
82
83     private static final Logger LOG = LoggerFactory.getLogger(BGPPeer.class);
84
85     @GuardedBy("this")
86     private final Set<TablesKey> tables = new HashSet<>();
87     @GuardedBy("this")
88     private BGPSession session;
89     @GuardedBy("this")
90     private byte[] rawIdentifier;
91     @GuardedBy("this")
92     private DOMTransactionChain chain;
93     @GuardedBy("this")
94     private AdjRibInWriter ribWriter;
95
96     private final RIB rib;
97     private final String name;
98     private BGPPeerRuntimeRegistrator registrator;
99     private BGPPeerRuntimeRegistration runtimeReg;
100     private long sessionEstablishedCounter = 0L;
101     private final Map<TablesKey, AdjRibOutListener> adjRibOutListenerSet = new HashMap();
102     private final RpcProviderRegistry rpcRegistry;
103     private RoutedRpcRegistration<BgpPeerRpcService> rpcRegistration;
104     private final PeerRole peerRole;
105
106     public BGPPeer(final String name, final RIB rib, final PeerRole role, final RpcProviderRegistry rpcRegistry) {
107         this.peerRole = role;
108         this.rib = Preconditions.checkNotNull(rib);
109         this.name = name;
110         this.chain = rib.createPeerChain(this);
111         this.ribWriter = AdjRibInWriter.create(rib.getYangRibId(), role, this.chain);
112         this.rpcRegistry = rpcRegistry;
113     }
114
115     @Override
116     public synchronized void close() {
117         releaseConnection();
118         this.chain.close();
119     }
120
121     @Override
122     public void onMessage(final BGPSession session, final Notification msg) {
123         if (!(msg instanceof Update) && !(msg instanceof RouteRefresh)) {
124             LOG.info("Ignoring unhandled message class {}", msg.getClass());
125             return;
126         }
127         if (msg instanceof Update) {
128             onUpdateMessage((Update) msg);
129         } else {
130             onRouteRefreshMessage((RouteRefresh) msg, session);
131         }
132     }
133
134     private void onRouteRefreshMessage(final RouteRefresh message, final BGPSession session) {
135         final Class<? extends AddressFamily> rrAfi = message.getAfi();
136         final Class<? extends SubsequentAddressFamily> rrSafi = message.getSafi();
137
138         final TablesKey key = new TablesKey(rrAfi, rrSafi);
139         final AdjRibOutListener listener = this.adjRibOutListenerSet.get(key);
140         if (listener != null) {
141             listener.close();
142             this.adjRibOutListenerSet.remove(listener);
143             createAdjRibOutListener(RouterIds.createPeerId(session.getBgpId()), key, true);
144         } else {
145             LOG.info("Ignoring RouteRefresh message. Afi/Safi is not supported: {}, {}.", rrAfi, rrSafi);
146         }
147     }
148
149     private void onUpdateMessage(final Update message) {
150         // update AdjRibs
151         final Attributes attrs = message.getAttributes();
152         MpReachNlri mpReach = null;
153         final boolean isAnyNlriAnnounced = message.getNlri() != null;
154         if (isAnyNlriAnnounced) {
155             mpReach = prefixesToMpReach(message);
156         } else if (attrs != null && attrs.getAugmentation(Attributes1.class) != null) {
157             mpReach = attrs.getAugmentation(Attributes1.class).getMpReachNlri();
158         }
159         if (mpReach != null) {
160             this.ribWriter.updateRoutes(mpReach, nextHopToAttribute(attrs, mpReach));
161         }
162         MpUnreachNlri mpUnreach = null;
163         if (message.getWithdrawnRoutes() != null) {
164             mpUnreach = prefixesToMpUnreach(message, isAnyNlriAnnounced);
165         } else if (attrs != null && attrs.getAugmentation(Attributes2.class) != null) {
166             mpUnreach = attrs.getAugmentation(Attributes2.class).getMpUnreachNlri();
167         }
168         if (mpUnreach != null) {
169             this.ribWriter.removeRoutes(mpUnreach);
170         }
171     }
172
173     private static Attributes nextHopToAttribute(final Attributes attrs, final MpReachNlri mpReach) {
174         if (attrs.getCNextHop() == null && mpReach.getCNextHop() != null) {
175             final AttributesBuilder attributesBuilder = new AttributesBuilder(attrs);
176             attributesBuilder.setCNextHop(mpReach.getCNextHop());
177             return attributesBuilder.build();
178         }
179         return attrs;
180     }
181
182     /**
183      * Creates MPReach for the prefixes to be handled in the same way as linkstate routes
184      *
185      * @param message Update message containing prefixes in NLRI
186      * @return MpReachNlri with prefixes from the nlri field
187      */
188     private static MpReachNlri prefixesToMpReach(final Update message) {
189         final List<Ipv4Prefixes> prefixes = new ArrayList<>();
190         for (final Ipv4Prefix p : message.getNlri().getNlri()) {
191             prefixes.add(new Ipv4PrefixesBuilder().setPrefix(p).build());
192         }
193         final MpReachNlriBuilder b = new MpReachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi(
194             UnicastSubsequentAddressFamily.class).setAdvertizedRoutes(
195                 new AdvertizedRoutesBuilder().setDestinationType(
196                     new DestinationIpv4CaseBuilder().setDestinationIpv4(
197                         new DestinationIpv4Builder().setIpv4Prefixes(prefixes).build()).build()).build());
198         if (message.getAttributes() != null) {
199             b.setCNextHop(message.getAttributes().getCNextHop());
200         }
201         return b.build();
202     }
203
204     /**
205      * Create MPUnreach for the prefixes to be handled in the same way as linkstate routes
206      *
207      * @param message Update message containing withdrawn routes
208      * @param isAnyNlriAnnounced
209      * @return MpUnreachNlri with prefixes from the withdrawn routes field
210      */
211     private static MpUnreachNlri prefixesToMpUnreach(final Update message, final boolean isAnyNlriAnnounced) {
212         final List<Ipv4Prefixes> prefixes = new ArrayList<>();
213         for (final Ipv4Prefix p : message.getWithdrawnRoutes().getWithdrawnRoutes()) {
214             boolean nlriAnounced = false;
215             if(isAnyNlriAnnounced) {
216                 nlriAnounced = message.getNlri().getNlri().contains(p);
217             }
218
219             if(!nlriAnounced) {
220                 prefixes.add(new Ipv4PrefixesBuilder().setPrefix(p).build());
221             }
222         }
223         return new MpUnreachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi(UnicastSubsequentAddressFamily.class).setWithdrawnRoutes(
224                 new WithdrawnRoutesBuilder().setDestinationType(
225                     new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.update.attributes.mp.unreach.nlri.withdrawn.routes.destination.type.DestinationIpv4CaseBuilder().setDestinationIpv4(
226                         new DestinationIpv4Builder().setIpv4Prefixes(prefixes).build()).build()).build()).build();
227     }
228
229     @Override
230     public synchronized void onSessionUp(final BGPSession session) {
231         final List<AddressFamilies> addPathTablesType = session.getAdvertisedAddPathTableTypes();
232         LOG.info("Session with peer {} went up with tables {} and Add Path tables {}", this.name, addPathTablesType,
233             session.getAdvertisedAddPathTableTypes());
234         this.session = session;
235
236         this.rawIdentifier = InetAddresses.forString(session.getBgpId().getValue()).getAddress();
237         final PeerId peerId = RouterIds.createPeerId(session.getBgpId());
238         createAdjRibOutListener(peerId);
239
240         this.ribWriter = this.ribWriter.transform(peerId, this.rib.getRibSupportContext(), this.tables, addPathTablesType, false);
241         this.sessionEstablishedCounter++;
242         if (this.registrator != null) {
243             this.runtimeReg = this.registrator.register(this);
244         }
245
246         if (this.rpcRegistry != null) {
247             this.rpcRegistration = this.rpcRegistry.addRoutedRpcImplementation(BgpPeerRpcService.class, new BgpPeerRpc(session, this.tables));
248             final KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer, PeerKey> path =
249                 this.rib.getInstanceIdentifier().child(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer.class, new PeerKey(peerId));
250             this.rpcRegistration.registerPath(PeerContext.class, path);
251         }
252     }
253
254     private void createAdjRibOutListener(final PeerId peerId) {
255         for (final BgpTableType t : this.session.getAdvertisedTableTypes()) {
256             final TablesKey key = new TablesKey(t.getAfi(), t.getSafi());
257             if (this.tables.add(key)) {
258                 createAdjRibOutListener(peerId, key, true);
259             }
260         }
261
262         addBgp4Support(peerId);
263     }
264
265     //try to add a support for old-school BGP-4, if peer did not advertise IPv4-Unicast MP capability
266     private void addBgp4Support(final PeerId peerId) {
267         final TablesKey key = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
268         if (this.tables.add(key)) {
269             createAdjRibOutListener(peerId, key, false);
270         }
271     }
272
273     private void createAdjRibOutListener(final PeerId peerId, final TablesKey key, final boolean mpSupport) {
274         final RIBSupportContext context = this.rib.getRibSupportContext().getRIBSupportContext(key);
275
276         // not particularly nice
277         if (context != null && this.session instanceof BGPSessionImpl) {
278             this.adjRibOutListenerSet.put(key, AdjRibOutListener.create(peerId, key, this.rib.getYangRibId(), this.rib.getCodecsRegistry(),
279                 context.getRibSupport(), ((RIBImpl) this.rib).getService(), ((BGPSessionImpl) this.session).getLimiter(), mpSupport));
280         }
281     }
282
283     private synchronized void cleanup() {
284         // FIXME: BUG-196: support graceful
285         for (final AdjRibOutListener adjRibOutListener : this.adjRibOutListenerSet.values()) {
286             adjRibOutListener.close();
287         }
288         this.adjRibOutListenerSet.clear();
289         this.ribWriter.removePeer();
290         this.tables.clear();
291     }
292
293     @Override
294     public void onSessionDown(final BGPSession session, final Exception e) {
295         if(e.getMessage().equals(BGPSessionImpl.END_OF_INPUT)) {
296             LOG.info("Session with peer {} went down", this.name);
297         } else {
298             LOG.info("Session with peer {} went down", this.name, e);
299         }
300         releaseConnection();
301     }
302
303     @Override
304     public void onSessionTerminated(final BGPSession session, final BGPTerminationReason cause) {
305         LOG.info("Session with peer {} terminated: {}", this.name, cause);
306         releaseConnection();
307     }
308
309     @Override
310     public String toString() {
311         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
312     }
313
314     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
315         toStringHelper.add("name", this.name);
316         toStringHelper.add("tables", this.tables);
317         return toStringHelper;
318     }
319
320     @Override
321     public String getName() {
322         return this.name;
323     }
324
325     @Override
326     public void releaseConnection() {
327         if (this.rpcRegistration != null) {
328             this.rpcRegistration.close();
329         }
330         addPeerToDisconnectedSharedList();
331         cleanup();
332         dropConnection();
333     }
334
335     private void addPeerToDisconnectedSharedList() {
336         if(this.session != null) {
337             this.rib.getCacheDisconnectedPeers().insertDesconectedPeer(this.session.getBgpId());
338         }
339     }
340
341     @GuardedBy("this")
342     private void dropConnection() {
343         if (this.runtimeReg != null) {
344             this.runtimeReg.close();
345             this.runtimeReg = null;
346         }
347         if (this.session != null) {
348             try {
349                 this.session.close();
350             } catch (final Exception e) {
351                 LOG.warn("Error closing session with peer", e);
352             }
353             this.session = null;
354         }
355     }
356
357     @Override
358     public boolean isSessionActive() {
359         return this.session != null;
360     }
361
362     @Override
363     public synchronized byte[] getRawIdentifier() {
364         return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
365     }
366
367     @Override
368     public void resetSession() {
369         releaseConnection();
370     }
371
372     @Override
373     public void resetStats() {
374         if (this.session instanceof BGPSessionStatistics) {
375             ((BGPSessionStatistics) this.session).resetSessionStats();
376         }
377     }
378
379     public synchronized void registerRootRuntimeBean(final BGPPeerRuntimeRegistrator registrator) {
380         this.registrator = registrator;
381     }
382
383     @Override
384     public BgpSessionState getBgpSessionState() {
385         if (this.session instanceof BGPSessionStatistics) {
386             return ((BGPSessionStatistics) this.session).getBgpSesionState();
387         }
388         return new BgpSessionState();
389     }
390
391     @Override
392     public synchronized BgpPeerState getBgpPeerState() {
393         final BgpPeerState peerState = new BgpPeerState();
394         final List<RouteTable> routes = Lists.newArrayList();
395         for (final TablesKey tablesKey : this.tables) {
396             final RouteTable routeTable = new RouteTable();
397             routeTable.setTableType("afi=" + tablesKey.getAfi().getSimpleName() + ",safi=" + tablesKey.getSafi().getSimpleName());
398             routeTable.setRoutesCount(this.rib.getRoutesCount(tablesKey));
399             routes.add(routeTable);
400         }
401         peerState.setRouteTable(routes);
402         peerState.setSessionEstablishedCount(this.sessionEstablishedCounter);
403         return peerState;
404     }
405
406     @Override
407     public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
408         LOG.error("Transaction chain failed.", cause);
409         this.chain.close();
410         this.chain = this.rib.createPeerChain(this);
411         this.ribWriter = AdjRibInWriter.create(this.rib.getYangRibId(), this.peerRole, this.chain);
412         releaseConnection();
413     }
414
415     @Override
416     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
417         LOG.debug("Transaction chain {} successfull.", chain);
418     }
419
420     @Override
421     public void markUptodate(final TablesKey tablesKey) {
422         this.ribWriter.markTableUptodate(tablesKey);
423     }
424 }