76e70e0bc063f96ed27f452745235b61e9566b69
[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
9 package org.opendaylight.protocol.bgp.rib.impl;
10
11 import com.google.common.base.MoreObjects;
12 import com.google.common.base.MoreObjects.ToStringHelper;
13 import com.google.common.base.Preconditions;
14 import com.google.common.collect.Lists;
15 import com.google.common.net.InetAddresses;
16 import java.util.ArrayList;
17 import java.util.Arrays;
18 import java.util.HashSet;
19 import java.util.List;
20 import java.util.Set;
21 import javax.annotation.concurrent.GuardedBy;
22 import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeMXBean;
23 import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeRegistration;
24 import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeRegistrator;
25 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpPeerState;
26 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
27 import org.opendaylight.controller.config.yang.bgp.rib.impl.RouteTable;
28 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
29 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
30 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
31 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
32 import org.opendaylight.protocol.bgp.rib.RibReference;
33 import org.opendaylight.protocol.bgp.rib.impl.spi.AdjRIBsOutRegistration;
34 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionStatistics;
35 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
36 import org.opendaylight.protocol.bgp.rib.impl.spi.ReusableBGPPeer;
37 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
38 import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason;
39 import org.opendaylight.protocol.bgp.rib.spi.Peer;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.DestinationIpv4Builder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.destination.ipv4.Ipv4Prefixes;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.destination.ipv4.Ipv4PrefixesBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.update.path.attributes.mp.reach.nlri.advertized.routes.destination.type.DestinationIpv4CaseBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.update.PathAttributes;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.PathAttributes1;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.PathAttributes2;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.MpReachNlri;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.MpReachNlriBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.MpUnreachNlri;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.MpUnreachNlriBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.mp.reach.nlri.AdvertizedRoutesBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.mp.unreach.nlri.WithdrawnRoutesBuilder;
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 /**
66  * Class representing a peer. We have a single instance for each peer, which provides translation from BGP events into
67  * RIB actions.
68  */
69 public class BGPPeer implements ReusableBGPPeer, Peer, AutoCloseable, BGPPeerRuntimeMXBean, TransactionChainListener {
70
71     private static final Logger LOG = LoggerFactory.getLogger(BGPPeer.class);
72
73     @GuardedBy("this")
74     private final Set<TablesKey> tables = new HashSet<>();
75     private final RIB rib;
76     private final String name;
77
78     @GuardedBy("this")
79     private BGPSession session;
80     @GuardedBy("this")
81     private byte[] rawIdentifier;
82     @GuardedBy("this")
83     private AdjRIBsOutRegistration reg;
84
85     private BGPPeerRuntimeRegistrator registrator;
86     private BGPPeerRuntimeRegistration runtimeReg;
87     private long sessionEstablishedCounter = 0L;
88
89     @GuardedBy("this")
90     private AdjRibInWriter ribWriter;
91
92     public BGPPeer(final String name, final RIB rib) {
93         this.rib = Preconditions.checkNotNull(rib);
94         this.name = name;
95
96         final DOMTransactionChain chain = rib.createPeerChain(this);
97         // FIXME: make this configurable
98         final PeerRole role = PeerRole.Ibgp;
99
100         this.ribWriter = AdjRibInWriter.create(((RibReference)rib).getInstanceIdentifier().getKey(), role, chain);
101     }
102
103     @Override
104     public synchronized void close() {
105         dropConnection();
106         // TODO should this perform cleanup ?
107     }
108
109     @Override
110     public void onMessage(final BGPSession session, final Notification msg) {
111         if (!(msg instanceof Update)) {
112             LOG.info("Ignoring unhandled message class {}", msg.getClass());
113             return;
114         }
115         final Update message = (Update) msg;
116         this.rib.updateTables(this, message);
117         // update AdjRibs
118         final PathAttributes attrs = message.getPathAttributes();
119         MpReachNlri mpReach = null;
120         if (message.getNlri() != null) {
121             mpReach = prefixesToMpReach(message);
122         } else if (attrs.getAugmentation(PathAttributes1.class) != null) {
123             mpReach = attrs.getAugmentation(PathAttributes1.class).getMpReachNlri();
124         }
125         if (mpReach != null) {
126             this.ribWriter.updateRoutes(mpReach, attrs);
127             return;
128         }
129         MpUnreachNlri mpUnreach = null;
130         if (message.getWithdrawnRoutes() != null) {
131             mpUnreach = prefixesToMpUnreach(message);
132         } else if (attrs.getAugmentation(PathAttributes2.class) != null) {
133             mpUnreach = attrs.getAugmentation(PathAttributes2.class).getMpUnreachNlri();
134         }
135         if (mpUnreach != null) {
136             this.ribWriter.removeRoutes(mpUnreach);
137         }
138     }
139
140     /**
141      * Creates MPReach for the prefixes to be handled in the same way as linkstate routes
142      *
143      * @param message Update message containing prefixes in NLRI
144      * @return MpReachNlri with prefixes from the nlri field
145      */
146     private MpReachNlri prefixesToMpReach(final Update message) {
147         final List<Ipv4Prefixes> prefixes = new ArrayList<>();
148         for (final Ipv4Prefix p : message.getNlri().getNlri()) {
149             prefixes.add(new Ipv4PrefixesBuilder().setPrefix(p).build());
150         }
151         final MpReachNlriBuilder b = new MpReachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi(
152             UnicastSubsequentAddressFamily.class).setAdvertizedRoutes(
153                 new AdvertizedRoutesBuilder().setDestinationType(
154                     new DestinationIpv4CaseBuilder().setDestinationIpv4(
155                         new DestinationIpv4Builder().setIpv4Prefixes(prefixes).build()).build()).build());
156         if (message.getPathAttributes() != null) {
157             b.setCNextHop(message.getPathAttributes().getCNextHop());
158         }
159         return b.build();
160     }
161
162     /**
163      * Create MPUnreach for the prefixes to be handled in the same way as linkstate routes
164      *
165      * @param message Update message containing withdrawn routes
166      * @return MpUnreachNlri with prefixes from the withdrawn routes field
167      */
168     private MpUnreachNlri prefixesToMpUnreach(final Update message) {
169         final List<Ipv4Prefixes> prefixes = new ArrayList<>();
170         for (final Ipv4Prefix p : message.getWithdrawnRoutes().getWithdrawnRoutes()) {
171             prefixes.add(new Ipv4PrefixesBuilder().setPrefix(p).build());
172         }
173         return new MpUnreachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi(UnicastSubsequentAddressFamily.class).setWithdrawnRoutes(
174                 new WithdrawnRoutesBuilder().setDestinationType(
175                     new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.update.path.attributes.mp.unreach.nlri.withdrawn.routes.destination.type.DestinationIpv4CaseBuilder().setDestinationIpv4(
176                         new DestinationIpv4Builder().setIpv4Prefixes(prefixes).build()).build()).build()).build();
177     }
178
179     @Override
180     public synchronized void onSessionUp(final BGPSession session) {
181         LOG.info("Session with peer {} went up with tables: {}", this.name, session.getAdvertisedTableTypes());
182
183         this.session = session;
184         this.rawIdentifier = InetAddresses.forString(session.getBgpId().getValue()).getAddress();
185
186         for (final BgpTableType t : session.getAdvertisedTableTypes()) {
187             final TablesKey key = new TablesKey(t.getAfi(), t.getSafi());
188
189             this.tables.add(key);
190             this.rib.initTable(this, key);
191         }
192
193         this.ribWriter = this.ribWriter.transform(session.getBgpId(), this.rib.getRibExtensions(), this.tables);
194
195         // Not particularly nice, but what can
196         if (session instanceof BGPSessionImpl) {
197             this.reg = this.rib.registerRIBsOut(this, new SessionRIBsOut((BGPSessionImpl) session));
198         }
199         this.sessionEstablishedCounter++;
200         if (this.registrator != null) {
201             this.runtimeReg = this.registrator.register(this);
202         }
203     }
204
205     private synchronized void cleanup() {
206         // FIXME: BUG-196: support graceful restart
207         this.ribWriter.cleanTables(this.tables);
208         for (final TablesKey key : this.tables) {
209             this.rib.clearTable(this, key);
210         }
211
212         if (this.reg != null) {
213             this.reg.close();
214             this.reg = null;
215         }
216
217         this.tables.clear();
218     }
219
220     @Override
221     public void onSessionDown(final BGPSession session, final Exception e) {
222         LOG.info("Session with peer {} went down", this.name, e);
223         releaseConnection();
224     }
225
226     @Override
227     public void onSessionTerminated(final BGPSession session, final BGPTerminationReason cause) {
228         LOG.info("Session with peer {} terminated: {}", this.name, cause);
229         releaseConnection();
230     }
231
232     @Override
233     public String toString() {
234         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
235     }
236
237     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
238         toStringHelper.add("name", this.name);
239         toStringHelper.add("tables", this.tables);
240         return toStringHelper;
241     }
242
243     @Override
244     public String getName() {
245         return this.name;
246     }
247
248     protected RIB getRib() {
249         return this.rib;
250     }
251
252     @Override
253     public void releaseConnection() {
254         dropConnection();
255         cleanup();
256     }
257
258     @GuardedBy("this")
259     private void dropConnection() {
260         if (this.runtimeReg != null) {
261             this.runtimeReg.close();
262             this.runtimeReg = null;
263         }
264         if (this.session != null) {
265             this.session.close();
266             this.session = null;
267         }
268     }
269
270     @Override
271     public boolean isSessionActive() {
272         return this.session != null;
273     }
274
275     @Override
276     public synchronized byte[] getRawIdentifier() {
277         return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
278     }
279
280     @Override
281     public void resetSession() {
282         releaseConnection();
283     }
284
285     @Override
286     public void resetStats() {
287         if (this.session instanceof BGPSessionStatistics) {
288             ((BGPSessionStatistics) this.session).resetSessionStats();
289         }
290     }
291
292     public synchronized void registerRootRuntimeBean(final BGPPeerRuntimeRegistrator registrator) {
293         this.registrator = registrator;
294     }
295
296     @Override
297     public BgpSessionState getBgpSessionState() {
298         if (this.session instanceof BGPSessionStatistics) {
299             return ((BGPSessionStatistics) this.session).getBgpSesionState();
300         }
301         return new BgpSessionState();
302     }
303
304     @Override
305     public synchronized BgpPeerState getBgpPeerState() {
306         final BgpPeerState peerState = new BgpPeerState();
307         final List<RouteTable> routes = Lists.newArrayList();
308         for (final TablesKey tablesKey : this.tables) {
309             final RouteTable routeTable = new RouteTable();
310             routeTable.setTableType("afi=" + tablesKey.getAfi().getSimpleName() + ",safi=" + tablesKey.getSafi().getSimpleName());
311             routeTable.setRoutesCount(this.rib.getRoutesCount(tablesKey));
312             routes.add(routeTable);
313         }
314         peerState.setRouteTable(routes);
315         peerState.setSessionEstablishedCount(this.sessionEstablishedCounter);
316         return peerState;
317     }
318
319     @Override
320     public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
321         // TODO Auto-generated method stub
322
323     }
324
325     @Override
326     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
327         // TODO Auto-generated method stub
328     }
329 }