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