2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.protocol.bgp.rib.impl;
10 import static org.opendaylight.protocol.bgp.rib.impl.AdjRibInWriter.isAnnounceNone;
11 import static org.opendaylight.protocol.bgp.rib.impl.AdjRibInWriter.isLearnNone;
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.MoreObjects.ToStringHelper;
15 import com.google.common.base.Preconditions;
16 import com.google.common.net.InetAddresses;
17 import java.util.ArrayList;
18 import java.util.Arrays;
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.List;
23 import java.util.Optional;
25 import java.util.stream.Collectors;
26 import javax.annotation.concurrent.GuardedBy;
27 import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeMXBean;
28 import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeRegistration;
29 import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeRegistrator;
30 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpPeerState;
31 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
32 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
33 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
34 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
35 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
36 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
37 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
38 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
39 import org.opendaylight.protocol.bgp.parser.BGPError;
40 import org.opendaylight.protocol.bgp.parser.impl.message.update.LocalPreferenceAttributeParser;
41 import org.opendaylight.protocol.bgp.parser.spi.MessageUtil;
42 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
43 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContext;
44 import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPPeerStats;
45 import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPPeerStatsImpl;
46 import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPSessionStats;
47 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
48 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
49 import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason;
50 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
51 import org.opendaylight.protocol.bgp.rib.spi.Peer;
52 import org.opendaylight.protocol.bgp.rib.spi.RouterIds;
53 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.DestinationIpv4Builder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.destination.ipv4.Ipv4Prefixes;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.destination.ipv4.Ipv4PrefixesBuilder;
57 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;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.Attributes;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.AttributesBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.RouteRefresh;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.add.path.capability.AddressFamilies;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpReachNlri;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpReachNlriBuilder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpUnreachNlri;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpUnreachNlriBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.mp.reach.nlri.AdvertizedRoutesBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.mp.unreach.nlri.WithdrawnRoutesBuilder;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.peer.rpc.rev160322.BgpPeerRpcService;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.peer.rpc.rev160322.PeerContext;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.SimpleRoutingPolicy;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.PeerKey;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.AddressFamily;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.Ipv4AddressFamily;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.SubsequentAddressFamily;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.UnicastSubsequentAddressFamily;
80 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
81 import org.opendaylight.yangtools.yang.binding.Notification;
82 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
87 * Class representing a peer. We have a single instance for each peer, which provides translation from BGP events into
90 public class BGPPeer implements BGPSessionListener, Peer, AutoCloseable, BGPPeerRuntimeMXBean, TransactionChainListener {
92 private static final Logger LOG = LoggerFactory.getLogger(BGPPeer.class);
95 private final Set<TablesKey> tables = new HashSet<>();
97 private BGPSession session;
99 private byte[] rawIdentifier;
101 private DOMTransactionChain chain;
103 private AdjRibInWriter ribWriter;
105 private EffectiveRibInWriter effRibInWriter;
107 private final RIB rib;
108 private final String name;
109 private BGPPeerRuntimeRegistrator registrator;
110 private BGPPeerRuntimeRegistration runtimeReg;
111 private final Map<TablesKey, AdjRibOutListener> adjRibOutListenerSet = new HashMap();
112 private final RpcProviderRegistry rpcRegistry;
113 private RoutedRpcRegistration<BgpPeerRpcService> rpcRegistration;
114 private final PeerRole peerRole;
115 private final Optional<SimpleRoutingPolicy> simpleRoutingPolicy;
116 private final BGPPeerStats peerStats;
118 public BGPPeer(final String name, final RIB rib, final PeerRole role, final SimpleRoutingPolicy peerStatus, final RpcProviderRegistry rpcRegistry) {
119 this.peerRole = role;
120 this.simpleRoutingPolicy = Optional.ofNullable(peerStatus);
121 this.rib = Preconditions.checkNotNull(rib);
123 this.chain = rib.createPeerChain(this);
124 this.ribWriter = AdjRibInWriter.create(rib.getYangRibId(), this.peerRole, this.simpleRoutingPolicy, this.chain);
125 this.rpcRegistry = rpcRegistry;
126 this.peerStats = new BGPPeerStatsImpl(this.name, this.tables);
128 // add current peer to "configured BGP peer" stats
129 this.rib.getRenderStats().getConfiguredPeerCounter().increaseCount();
132 public BGPPeer(final String name, final RIB rib, final PeerRole role, final RpcProviderRegistry rpcRegistry) {
133 this(name, rib, role, null, rpcRegistry);
137 public synchronized void close() {
143 public void onMessage(final BGPSession session, final Notification msg) throws BGPDocumentedException {
144 if (!(msg instanceof Update) && !(msg instanceof RouteRefresh)) {
145 LOG.info("Ignoring unhandled message class {}", msg.getClass());
148 if (msg instanceof Update) {
149 onUpdateMessage((Update) msg);
151 onRouteRefreshMessage((RouteRefresh) msg, session);
155 private void onRouteRefreshMessage(final RouteRefresh message, final BGPSession session) {
156 final Class<? extends AddressFamily> rrAfi = message.getAfi();
157 final Class<? extends SubsequentAddressFamily> rrSafi = message.getSafi();
159 final TablesKey key = new TablesKey(rrAfi, rrSafi);
160 final AdjRibOutListener listener = this.adjRibOutListenerSet.get(key);
161 if (listener != null) {
163 this.adjRibOutListenerSet.remove(key);
164 createAdjRibOutListener(RouterIds.createPeerId(session.getBgpId()), key, listener.isMpSupported());
166 LOG.info("Ignoring RouteRefresh message. Afi/Safi is not supported: {}, {}.", rrAfi, rrSafi);
171 * Check for presence of well known mandatory attribute LOCAL_PREF in Update message
173 * @param message Update message
174 * @throws BGPDocumentedException
176 private void checkMandatoryAttributesPresence(final Update message) throws BGPDocumentedException {
177 if (MessageUtil.isAnyNlriPresent(message)) {
178 final Attributes attrs = message.getAttributes();
179 if (this.peerRole == PeerRole.Ibgp && (attrs == null || attrs.getLocalPref() == null)) {
180 throw new BGPDocumentedException(BGPError.MANDATORY_ATTR_MISSING_MSG + "LOCAL_PREF",
181 BGPError.WELL_KNOWN_ATTR_MISSING,
182 new byte[] { LocalPreferenceAttributeParser.TYPE });
188 * Process Update message received.
189 * Calls {@link #checkMandatoryAttributesPresence(Update)} to check for presence of mandatory attributes.
191 * @param message Update message
192 * @throws BGPDocumentedException
194 private void onUpdateMessage(final Update message) throws BGPDocumentedException {
195 checkMandatoryAttributesPresence(message);
198 final Attributes attrs = message.getAttributes();
199 MpReachNlri mpReach = null;
200 final boolean isAnyNlriAnnounced = message.getNlri() != null;
201 if (isAnyNlriAnnounced) {
202 mpReach = prefixesToMpReach(message);
204 mpReach = MessageUtil.getMpReachNlri(attrs);
206 if (mpReach != null) {
207 this.ribWriter.updateRoutes(mpReach, nextHopToAttribute(attrs, mpReach));
209 MpUnreachNlri mpUnreach = null;
210 if (message.getWithdrawnRoutes() != null) {
211 mpUnreach = prefixesToMpUnreach(message, isAnyNlriAnnounced);
213 mpUnreach = MessageUtil.getMpUnreachNlri(attrs);
215 if (mpUnreach != null) {
216 this.ribWriter.removeRoutes(mpUnreach);
220 private static Attributes nextHopToAttribute(final Attributes attrs, final MpReachNlri mpReach) {
221 if (attrs.getCNextHop() == null && mpReach.getCNextHop() != null) {
222 final AttributesBuilder attributesBuilder = new AttributesBuilder(attrs);
223 attributesBuilder.setCNextHop(mpReach.getCNextHop());
224 return attributesBuilder.build();
230 * Creates MPReach for the prefixes to be handled in the same way as linkstate routes
232 * @param message Update message containing prefixes in NLRI
233 * @return MpReachNlri with prefixes from the nlri field
235 private static MpReachNlri prefixesToMpReach(final Update message) {
236 final List<Ipv4Prefixes> prefixes = new ArrayList<>();
237 for (final Ipv4Prefix p : message.getNlri().getNlri()) {
238 prefixes.add(new Ipv4PrefixesBuilder().setPrefix(p).build());
240 final MpReachNlriBuilder b = new MpReachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi(
241 UnicastSubsequentAddressFamily.class).setAdvertizedRoutes(
242 new AdvertizedRoutesBuilder().setDestinationType(
243 new DestinationIpv4CaseBuilder().setDestinationIpv4(
244 new DestinationIpv4Builder().setIpv4Prefixes(prefixes).build()).build()).build());
245 if (message.getAttributes() != null) {
246 b.setCNextHop(message.getAttributes().getCNextHop());
252 * Create MPUnreach for the prefixes to be handled in the same way as linkstate routes
254 * @param message Update message containing withdrawn routes
255 * @param isAnyNlriAnnounced
256 * @return MpUnreachNlri with prefixes from the withdrawn routes field
258 private static MpUnreachNlri prefixesToMpUnreach(final Update message, final boolean isAnyNlriAnnounced) {
259 final List<Ipv4Prefixes> prefixes = new ArrayList<>();
260 for (final Ipv4Prefix p : message.getWithdrawnRoutes().getWithdrawnRoutes()) {
261 boolean nlriAnounced = false;
262 if(isAnyNlriAnnounced) {
263 nlriAnounced = message.getNlri().getNlri().contains(p);
267 prefixes.add(new Ipv4PrefixesBuilder().setPrefix(p).build());
270 return new MpUnreachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi(UnicastSubsequentAddressFamily.class).setWithdrawnRoutes(
271 new WithdrawnRoutesBuilder().setDestinationType(
272 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(
273 new DestinationIpv4Builder().setIpv4Prefixes(prefixes).build()).build()).build()).build();
277 public synchronized void onSessionUp(final BGPSession session) {
278 final List<AddressFamilies> addPathTablesType = session.getAdvertisedAddPathTableTypes();
279 LOG.info("Session with peer {} went up with tables {} and Add Path tables {}", this.name, addPathTablesType,
280 session.getAdvertisedAddPathTableTypes());
281 this.session = session;
283 this.rawIdentifier = InetAddresses.forString(session.getBgpId().getValue()).getAddress();
284 final PeerId peerId = RouterIds.createPeerId(session.getBgpId());
286 this.tables.addAll(this.session.getAdvertisedTableTypes().stream().map(t -> new TablesKey(t.getAfi(), t.getSafi())).collect(Collectors.toList()));
287 final boolean announceNone = isAnnounceNone(this.simpleRoutingPolicy);
289 createAdjRibOutListener(peerId);
291 addBgp4Support(peerId, announceNone);
293 if(!isLearnNone(this.simpleRoutingPolicy)) {
294 final YangInstanceIdentifier peerIId = this.rib.getYangRibId().node(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer.QNAME).node(IdentifierUtils.domPeerId(peerId));
295 this.effRibInWriter = EffectiveRibInWriter.create(this.rib.getService(), this.rib.createPeerChain(this), peerIId, this.rib.getImportPolicyPeerTracker(),
296 this.rib.getRibSupportContext(), this.peerRole, this.peerStats.getEffectiveRibInRouteCounters(), this.peerStats.getAdjRibInRouteCounters());
298 this.ribWriter = this.ribWriter.transform(peerId, this.rib.getRibSupportContext(), this.tables, addPathTablesType);
300 // register BGP Peer stats
301 this.peerStats.getSessionEstablishedCounter().increaseCount();
302 if (this.registrator != null) {
303 this.runtimeReg = this.registrator.register(this);
306 if (this.rpcRegistry != null) {
307 this.rpcRegistration = this.rpcRegistry.addRoutedRpcImplementation(BgpPeerRpcService.class, new BgpPeerRpc(session, this.tables));
308 final KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer, PeerKey> path =
309 this.rib.getInstanceIdentifier().child(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer.class, new PeerKey(peerId));
310 this.rpcRegistration.registerPath(PeerContext.class, path);
313 this.rib.getRenderStats().getConnectedPeerCounter().increaseCount();
316 private void createAdjRibOutListener(final PeerId peerId) {
317 this.tables.forEach(key->createAdjRibOutListener(peerId, key, true));
320 //try to add a support for old-school BGP-4, if peer did not advertise IPv4-Unicast MP capability
321 private void addBgp4Support(final PeerId peerId, final boolean announceNone) {
322 final TablesKey key = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
323 if (this.tables.add(key) && !announceNone) {
324 createAdjRibOutListener(peerId, key, false);
328 private void createAdjRibOutListener(final PeerId peerId, final TablesKey key, final boolean mpSupport) {
329 final RIBSupportContext context = this.rib.getRibSupportContext().getRIBSupportContext(key);
331 // not particularly nice
332 if (context != null && this.session instanceof BGPSessionImpl) {
333 this.adjRibOutListenerSet.put(key, AdjRibOutListener.create(peerId, key, this.rib.getYangRibId(), this.rib.getCodecsRegistry(),
334 context.getRibSupport(), this.rib.getService(), ((BGPSessionImpl) this.session).getLimiter(), mpSupport, this.peerStats.getAdjRibOutRouteCounters().init(key)));
338 private synchronized void cleanup() {
339 // FIXME: BUG-196: support graceful
340 for (final AdjRibOutListener adjRibOutListener : this.adjRibOutListenerSet.values()) {
341 adjRibOutListener.close();
343 this.adjRibOutListenerSet.clear();
344 if (this.effRibInWriter != null) {
345 this.effRibInWriter.close();
347 this.ribWriter.removePeer();
352 public void onSessionDown(final BGPSession session, final Exception e) {
353 if(e.getMessage().equals(BGPSessionImpl.END_OF_INPUT)) {
354 LOG.info("Session with peer {} went down", this.name);
356 LOG.info("Session with peer {} went down", this.name, e);
362 public void onSessionTerminated(final BGPSession session, final BGPTerminationReason cause) {
363 LOG.info("Session with peer {} terminated: {}", this.name, cause);
368 public String toString() {
369 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
372 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
373 toStringHelper.add("name", this.name);
374 toStringHelper.add("tables", this.tables);
375 return toStringHelper;
379 public String getName() {
384 public void releaseConnection() {
385 if (this.rpcRegistration != null) {
386 this.rpcRegistration.close();
388 addPeerToDisconnectedSharedList();
393 private void addPeerToDisconnectedSharedList() {
394 if(this.session != null) {
395 this.rib.getCacheDisconnectedPeers().insertDesconectedPeer(this.session.getBgpId());
400 private void dropConnection() {
401 if (this.runtimeReg != null) {
402 this.runtimeReg.close();
403 this.runtimeReg = null;
405 if (this.session != null) {
407 this.session.close();
408 } catch (final Exception e) {
409 LOG.warn("Error closing session with peer", e);
413 this.rib.getRenderStats().getConnectedPeerCounter().decreaseCount();
418 public boolean isSessionActive() {
419 return this.session != null;
423 public synchronized byte[] getRawIdentifier() {
424 return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
428 public void resetSession() {
433 public void resetStats() {
434 if (this.session instanceof BGPSessionStats) {
435 ((BGPSessionStats) this.session).resetBgpSessionStats();
439 public synchronized void registerRootRuntimeBean(final BGPPeerRuntimeRegistrator registrator) {
440 this.registrator = registrator;
444 public BgpSessionState getBgpSessionState() {
445 if (this.session instanceof BGPSessionStats) {
446 return ((BGPSessionStats) this.session).getBgpSessionState();
448 return new BgpSessionState();
452 public synchronized BgpPeerState getBgpPeerState() {
453 return this.peerStats.getBgpPeerState();
457 public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
458 LOG.error("Transaction chain failed.", cause);
460 this.chain = this.rib.createPeerChain(this);
461 this.ribWriter = AdjRibInWriter.create(this.rib.getYangRibId(), this.peerRole, this.simpleRoutingPolicy, this.chain);
466 public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
467 LOG.debug("Transaction chain {} successfull.", chain);
471 public void markUptodate(final TablesKey tablesKey) {
472 this.ribWriter.markTableUptodate(tablesKey);