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