BUG-3919: Support for non-MP advertisement
[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
89     public BGPPeer(final String name, final RIB rib) {
90         this(name, rib, PeerRole.Ibgp);
91     }
92
93     public BGPPeer(final String name, final RIB rib, final PeerRole role) {
94         this.rib = Preconditions.checkNotNull(rib);
95         this.name = name;
96         this.chain = rib.createPeerChain(this);
97         this.ribWriter = AdjRibInWriter.create(rib.getYangRibId(), role, this.chain);
98     }
99
100     @Override
101     public synchronized void close() {
102         dropConnection();
103         this.chain.close();
104         // TODO should this perform cleanup ?
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         for (final BgpTableType t : session.getAdvertisedTableTypes()) {
202             final TablesKey key = new TablesKey(t.getAfi(), t.getSafi());
203             if (this.tables.add(key)) {
204                 createAdjRibOutListener(peerId, key, true);
205             }
206         }
207
208         addBgp4Support(peerId);
209
210         this.ribWriter = this.ribWriter.transform(peerId, this.rib.getRibSupportContext(), this.tables, false);
211         this.sessionEstablishedCounter++;
212         if (this.registrator != null) {
213             this.runtimeReg = this.registrator.register(this);
214         }
215     }
216
217     //try to add a support for old-school BGP-4, if peer did not advertise IPv4-Unicast MP capability
218     private void addBgp4Support(final PeerId peerId) {
219         final TablesKey key = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
220         if (this.tables.add(key)) {
221             createAdjRibOutListener(peerId, key, false);
222         }
223     }
224
225     private void createAdjRibOutListener(final PeerId peerId, final TablesKey key, final boolean mpSupport) {
226         final RIBSupportContext context = this.rib.getRibSupportContext().getRIBSupportContext(key);
227
228         // not particularly nice
229         if (context != null && this.session instanceof BGPSessionImpl) {
230             AdjRibOutListener.create(peerId, key, this.rib.getYangRibId(), this.rib.getCodecsRegistry(), context.getRibSupport(), ((RIBImpl) this.rib).getService(),
231                 ((BGPSessionImpl) this.session).getLimiter(), mpSupport);
232         }
233     }
234
235     private synchronized void cleanup() {
236         // FIXME: BUG-196: support graceful restart
237         this.ribWriter.cleanTables(this.tables);
238         this.tables.clear();
239     }
240
241     @Override
242     public void onSessionDown(final BGPSession session, final Exception e) {
243         LOG.info("Session with peer {} went down", this.name, e);
244         releaseConnection();
245     }
246
247     @Override
248     public void onSessionTerminated(final BGPSession session, final BGPTerminationReason cause) {
249         LOG.info("Session with peer {} terminated: {}", this.name, cause);
250         releaseConnection();
251     }
252
253     @Override
254     public String toString() {
255         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
256     }
257
258     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
259         toStringHelper.add("name", this.name);
260         toStringHelper.add("tables", this.tables);
261         return toStringHelper;
262     }
263
264     @Override
265     public String getName() {
266         return this.name;
267     }
268
269     @Override
270     public void releaseConnection() {
271         dropConnection();
272         cleanup();
273     }
274
275     @GuardedBy("this")
276     private void dropConnection() {
277         if (this.runtimeReg != null) {
278             this.runtimeReg.close();
279             this.runtimeReg = null;
280         }
281         if (this.session != null) {
282             try {
283                 this.session.close();
284             } catch (final Exception e) {
285                 LOG.warn("Error closing session with peer", e);
286             }
287             this.session = null;
288         }
289     }
290
291     @Override
292     public boolean isSessionActive() {
293         return this.session != null;
294     }
295
296     @Override
297     public synchronized byte[] getRawIdentifier() {
298         return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
299     }
300
301     @Override
302     public void resetSession() {
303         releaseConnection();
304     }
305
306     @Override
307     public void resetStats() {
308         if (this.session instanceof BGPSessionStatistics) {
309             ((BGPSessionStatistics) this.session).resetSessionStats();
310         }
311     }
312
313     public synchronized void registerRootRuntimeBean(final BGPPeerRuntimeRegistrator registrator) {
314         this.registrator = registrator;
315     }
316
317     @Override
318     public BgpSessionState getBgpSessionState() {
319         if (this.session instanceof BGPSessionStatistics) {
320             return ((BGPSessionStatistics) this.session).getBgpSesionState();
321         }
322         return new BgpSessionState();
323     }
324
325     @Override
326     public synchronized BgpPeerState getBgpPeerState() {
327         final BgpPeerState peerState = new BgpPeerState();
328         final List<RouteTable> routes = Lists.newArrayList();
329         for (final TablesKey tablesKey : this.tables) {
330             final RouteTable routeTable = new RouteTable();
331             routeTable.setTableType("afi=" + tablesKey.getAfi().getSimpleName() + ",safi=" + tablesKey.getSafi().getSimpleName());
332             routeTable.setRoutesCount(this.rib.getRoutesCount(tablesKey));
333             routes.add(routeTable);
334         }
335         peerState.setRouteTable(routes);
336         peerState.setSessionEstablishedCount(this.sessionEstablishedCounter);
337         return peerState;
338     }
339
340     @Override
341     public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
342         LOG.error("Transaction chain failed.", cause);
343         dropConnection();
344         this.chain.close();
345         this.chain = this.rib.createPeerChain(this);
346     }
347
348     @Override
349     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
350         LOG.debug("Transaction chain {} successfull.", chain);
351     }
352
353     @Override
354     public void markUptodate(final TablesKey tablesKey) {
355         this.ribWriter.markTableUptodate(tablesKey);
356     }
357 }