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