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