b33657c234edca8f539f5a70da1a737fed5b3947
[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         LOG.info("Session with peer {} went down", this.name, e);
252         releaseConnection();
253     }
254
255     @Override
256     public void onSessionTerminated(final BGPSession session, final BGPTerminationReason cause) {
257         LOG.info("Session with peer {} terminated: {}", this.name, cause);
258         releaseConnection();
259     }
260
261     @Override
262     public String toString() {
263         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
264     }
265
266     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
267         toStringHelper.add("name", this.name);
268         toStringHelper.add("tables", this.tables);
269         return toStringHelper;
270     }
271
272     @Override
273     public String getName() {
274         return this.name;
275     }
276
277     @Override
278     public void releaseConnection() {
279         cleanup();
280         dropConnection();
281     }
282
283     @GuardedBy("this")
284     private void dropConnection() {
285         if (this.runtimeReg != null) {
286             this.runtimeReg.close();
287             this.runtimeReg = null;
288         }
289         if (this.session != null) {
290             try {
291                 this.session.close();
292             } catch (final Exception e) {
293                 LOG.warn("Error closing session with peer", e);
294             }
295             this.session = null;
296         }
297     }
298
299     @Override
300     public boolean isSessionActive() {
301         return this.session != null;
302     }
303
304     @Override
305     public synchronized byte[] getRawIdentifier() {
306         return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
307     }
308
309     @Override
310     public void resetSession() {
311         releaseConnection();
312     }
313
314     @Override
315     public void resetStats() {
316         if (this.session instanceof BGPSessionStatistics) {
317             ((BGPSessionStatistics) this.session).resetSessionStats();
318         }
319     }
320
321     public synchronized void registerRootRuntimeBean(final BGPPeerRuntimeRegistrator registrator) {
322         this.registrator = registrator;
323     }
324
325     @Override
326     public BgpSessionState getBgpSessionState() {
327         if (this.session instanceof BGPSessionStatistics) {
328             return ((BGPSessionStatistics) this.session).getBgpSesionState();
329         }
330         return new BgpSessionState();
331     }
332
333     @Override
334     public synchronized BgpPeerState getBgpPeerState() {
335         final BgpPeerState peerState = new BgpPeerState();
336         final List<RouteTable> routes = Lists.newArrayList();
337         for (final TablesKey tablesKey : this.tables) {
338             final RouteTable routeTable = new RouteTable();
339             routeTable.setTableType("afi=" + tablesKey.getAfi().getSimpleName() + ",safi=" + tablesKey.getSafi().getSimpleName());
340             routeTable.setRoutesCount(this.rib.getRoutesCount(tablesKey));
341             routes.add(routeTable);
342         }
343         peerState.setRouteTable(routes);
344         peerState.setSessionEstablishedCount(this.sessionEstablishedCounter);
345         return peerState;
346     }
347
348     @Override
349     public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
350         LOG.error("Transaction chain failed.", cause);
351         releaseConnection();
352         this.chain.close();
353         this.chain = this.rib.createPeerChain(this);
354     }
355
356     @Override
357     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
358         LOG.debug("Transaction chain {} successfull.", chain);
359     }
360
361     @Override
362     public void markUptodate(final TablesKey tablesKey) {
363         this.ribWriter.markTableUptodate(tablesKey);
364     }
365 }