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