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