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;
12 import com.google.common.base.MoreObjects;
13 import com.google.common.base.MoreObjects.ToStringHelper;
14 import com.google.common.base.Preconditions;
15 import com.google.common.net.InetAddresses;
16 import java.util.ArrayList;
17 import java.util.Arrays;
18 import java.util.HashMap;
19 import java.util.HashSet;
20 import java.util.List;
22 import java.util.Optional;
24 import java.util.stream.Collectors;
25 import javax.annotation.concurrent.GuardedBy;
26 import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeMXBean;
27 import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeRegistration;
28 import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeRegistrator;
29 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpPeerState;
30 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
31 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
32 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
33 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
34 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
35 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
36 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
37 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
38 import org.opendaylight.protocol.bgp.parser.BGPError;
39 import org.opendaylight.protocol.bgp.parser.impl.message.update.LocalPreferenceAttributeParser;
40 import org.opendaylight.protocol.bgp.parser.spi.MessageUtil;
41 import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPPeerStats;
42 import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPSessionStats;
43 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
44 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContext;
45 import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPPeerStatsImpl;
46 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
47 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
48 import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason;
49 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
50 import org.opendaylight.protocol.bgp.rib.spi.Peer;
51 import org.opendaylight.protocol.bgp.rib.spi.RouterIds;
52 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.DestinationIpv4Builder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.destination.ipv4.Ipv4Prefixes;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.destination.ipv4.Ipv4PrefixesBuilder;
56 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;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.Attributes;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.AttributesBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.RouteRefresh;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.add.path.capability.AddressFamilies;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpReachNlri;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpReachNlriBuilder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpUnreachNlri;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpUnreachNlriBuilder;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.mp.reach.nlri.AdvertizedRoutesBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.mp.unreach.nlri.WithdrawnRoutesBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.peer.rpc.rev160322.BgpPeerRpcService;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.peer.rpc.rev160322.PeerContext;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.SimpleRoutingPolicy;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.PeerKey;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.AddressFamily;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.Ipv4AddressFamily;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.SubsequentAddressFamily;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.UnicastSubsequentAddressFamily;
79 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
80 import org.opendaylight.yangtools.yang.binding.Notification;
81 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
86 * Class representing a peer. We have a single instance for each peer, which provides translation from BGP events into
89 public class BGPPeer implements BGPSessionListener, Peer, AutoCloseable, BGPPeerRuntimeMXBean, TransactionChainListener {
91 private static final Logger LOG = LoggerFactory.getLogger(BGPPeer.class);
94 private final Set<TablesKey> tables = new HashSet<>();
96 private BGPSession session;
98 private byte[] rawIdentifier;
100 private DOMTransactionChain chain;
102 private AdjRibInWriter ribWriter;
104 private EffectiveRibInWriter effRibInWriter;
106 private final RIB rib;
107 private final String name;
108 private BGPPeerRuntimeRegistrator registrator;
109 private BGPPeerRuntimeRegistration runtimeReg;
110 private final Map<TablesKey, AdjRibOutListener> adjRibOutListenerSet = new HashMap();
111 private final RpcProviderRegistry rpcRegistry;
112 private RoutedRpcRegistration<BgpPeerRpcService> rpcRegistration;
113 private final PeerRole peerRole;
114 private final Optional<SimpleRoutingPolicy> simpleRoutingPolicy;
115 private final BGPPeerStats peerStats;
117 public BGPPeer(final String name, final RIB rib, final PeerRole role, final SimpleRoutingPolicy peerStatus, final RpcProviderRegistry rpcRegistry) {
118 this.peerRole = role;
119 this.simpleRoutingPolicy = Optional.ofNullable(peerStatus);
120 this.rib = Preconditions.checkNotNull(rib);
122 this.chain = rib.createPeerChain(this);
123 this.ribWriter = AdjRibInWriter.create(rib.getYangRibId(), this.peerRole, this.simpleRoutingPolicy, this.chain);
124 this.rpcRegistry = rpcRegistry;
125 this.peerStats = new BGPPeerStatsImpl(this.name, this.tables);
127 // add current peer to "configured BGP peer" stats
128 this.rib.getRenderStats().getConfiguredPeerCounter().increaseCount();
131 public BGPPeer(final String name, final RIB rib, final PeerRole role, final RpcProviderRegistry rpcRegistry) {
132 this(name, rib, role, null, rpcRegistry);
136 public synchronized void close() {
142 public void onMessage(final BGPSession session, final Notification msg) throws BGPDocumentedException {
143 if (!(msg instanceof Update) && !(msg instanceof RouteRefresh)) {
144 LOG.info("Ignoring unhandled message class {}", msg.getClass());
147 if (msg instanceof Update) {
148 onUpdateMessage((Update) msg);
150 onRouteRefreshMessage((RouteRefresh) msg, session);
154 private void onRouteRefreshMessage(final RouteRefresh message, final BGPSession session) {
155 final Class<? extends AddressFamily> rrAfi = message.getAfi();
156 final Class<? extends SubsequentAddressFamily> rrSafi = message.getSafi();
158 final TablesKey key = new TablesKey(rrAfi, rrSafi);
159 final AdjRibOutListener listener = this.adjRibOutListenerSet.get(key);
160 if (listener != null) {
162 this.adjRibOutListenerSet.remove(listener);
163 createAdjRibOutListener(RouterIds.createPeerId(session.getBgpId()), key, listener.isMpSupported());
165 LOG.info("Ignoring RouteRefresh message. Afi/Safi is not supported: {}, {}.", rrAfi, rrSafi);
170 * Check for presence of well known mandatory attribute LOCAL_PREF in Update message
172 * @param message Update message
173 * @throws BGPDocumentedException
175 private void checkMandatoryAttributesPresence(final Update message) throws BGPDocumentedException {
176 if (MessageUtil.isAnyNlriPresent(message)) {
177 final Attributes attrs = message.getAttributes();
178 if (this.peerRole == PeerRole.Ibgp && (attrs == null || attrs.getLocalPref() == null)) {
179 throw new BGPDocumentedException(BGPError.MANDATORY_ATTR_MISSING_MSG + "LOCAL_PREF",
180 BGPError.WELL_KNOWN_ATTR_MISSING,
181 new byte[] { LocalPreferenceAttributeParser.TYPE });
187 * Process Update message received.
188 * Calls {@link #checkMandatoryAttributesPresence(Update)} to check for presence of mandatory attributes.
190 * @param message Update message
191 * @throws BGPDocumentedException
193 private void onUpdateMessage(final Update message) throws BGPDocumentedException {
194 checkMandatoryAttributesPresence(message);
197 final Attributes attrs = message.getAttributes();
198 MpReachNlri mpReach = null;
199 final boolean isAnyNlriAnnounced = message.getNlri() != null;
200 if (isAnyNlriAnnounced) {
201 mpReach = prefixesToMpReach(message);
203 mpReach = MessageUtil.getMpReachNlri(attrs);
205 if (mpReach != null) {
206 this.ribWriter.updateRoutes(mpReach, nextHopToAttribute(attrs, mpReach));
208 MpUnreachNlri mpUnreach = null;
209 if (message.getWithdrawnRoutes() != null) {
210 mpUnreach = prefixesToMpUnreach(message, isAnyNlriAnnounced);
212 mpUnreach = MessageUtil.getMpUnreachNlri(attrs);
214 if (mpUnreach != null) {
215 this.ribWriter.removeRoutes(mpUnreach);
219 private static Attributes nextHopToAttribute(final Attributes attrs, final MpReachNlri mpReach) {
220 if (attrs.getCNextHop() == null && mpReach.getCNextHop() != null) {
221 final AttributesBuilder attributesBuilder = new AttributesBuilder(attrs);
222 attributesBuilder.setCNextHop(mpReach.getCNextHop());
223 return attributesBuilder.build();
229 * Creates MPReach for the prefixes to be handled in the same way as linkstate routes
231 * @param message Update message containing prefixes in NLRI
232 * @return MpReachNlri with prefixes from the nlri field
234 private static MpReachNlri prefixesToMpReach(final Update message) {
235 final List<Ipv4Prefixes> prefixes = new ArrayList<>();
236 for (final Ipv4Prefix p : message.getNlri().getNlri()) {
237 prefixes.add(new Ipv4PrefixesBuilder().setPrefix(p).build());
239 final MpReachNlriBuilder b = new MpReachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi(
240 UnicastSubsequentAddressFamily.class).setAdvertizedRoutes(
241 new AdvertizedRoutesBuilder().setDestinationType(
242 new DestinationIpv4CaseBuilder().setDestinationIpv4(
243 new DestinationIpv4Builder().setIpv4Prefixes(prefixes).build()).build()).build());
244 if (message.getAttributes() != null) {
245 b.setCNextHop(message.getAttributes().getCNextHop());
251 * Create MPUnreach for the prefixes to be handled in the same way as linkstate routes
253 * @param message Update message containing withdrawn routes
254 * @param isAnyNlriAnnounced
255 * @return MpUnreachNlri with prefixes from the withdrawn routes field
257 private static MpUnreachNlri prefixesToMpUnreach(final Update message, final boolean isAnyNlriAnnounced) {
258 final List<Ipv4Prefixes> prefixes = new ArrayList<>();
259 for (final Ipv4Prefix p : message.getWithdrawnRoutes().getWithdrawnRoutes()) {
260 boolean nlriAnounced = false;
261 if(isAnyNlriAnnounced) {
262 nlriAnounced = message.getNlri().getNlri().contains(p);
266 prefixes.add(new Ipv4PrefixesBuilder().setPrefix(p).build());
269 return new MpUnreachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi(UnicastSubsequentAddressFamily.class).setWithdrawnRoutes(
270 new WithdrawnRoutesBuilder().setDestinationType(
271 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(
272 new DestinationIpv4Builder().setIpv4Prefixes(prefixes).build()).build()).build()).build();
276 public synchronized void onSessionUp(final BGPSession session) {
277 final List<AddressFamilies> addPathTablesType = session.getAdvertisedAddPathTableTypes();
278 LOG.info("Session with peer {} went up with tables {} and Add Path tables {}", this.name, addPathTablesType,
279 session.getAdvertisedAddPathTableTypes());
280 this.session = session;
282 this.rawIdentifier = InetAddresses.forString(session.getBgpId().getValue()).getAddress();
283 final PeerId peerId = RouterIds.createPeerId(session.getBgpId());
285 this.tables.addAll(this.session.getAdvertisedTableTypes().stream().map(t -> new TablesKey(t.getAfi(), t.getSafi())).collect(Collectors.toList()));
286 final boolean announceNone = isAnnounceNone(this.simpleRoutingPolicy);
288 createAdjRibOutListener(peerId);
290 addBgp4Support(peerId, announceNone);
292 if(!isLearnNone(this.simpleRoutingPolicy)) {
293 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));
294 this.effRibInWriter = EffectiveRibInWriter.create(this.rib.getService(), this.rib.createPeerChain(this), peerIId, ((RIBImpl) this.rib).getImportPolicyPeerTracker(),
295 this.rib.getRibSupportContext(), this.peerRole, this.peerStats.getEffectiveRibInRouteCounters(), this.peerStats.getAdjRibInRouteCounters());
297 this.ribWriter = this.ribWriter.transform(peerId, this.rib.getRibSupportContext(), this.tables, addPathTablesType);
299 // register BGP Peer stats
300 this.peerStats.getSessionEstablishedCounter().increaseCount();
301 if (this.registrator != null) {
302 this.runtimeReg = this.registrator.register(this);
305 if (this.rpcRegistry != null) {
306 this.rpcRegistration = this.rpcRegistry.addRoutedRpcImplementation(BgpPeerRpcService.class, new BgpPeerRpc(session, this.tables));
307 final KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer, PeerKey> path =
308 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));
309 this.rpcRegistration.registerPath(PeerContext.class, path);
312 this.rib.getRenderStats().getConnectedPeerCounter().increaseCount();
315 private void createAdjRibOutListener(final PeerId peerId) {
316 this.tables.forEach(key->createAdjRibOutListener(peerId, key, true));
319 //try to add a support for old-school BGP-4, if peer did not advertise IPv4-Unicast MP capability
320 private void addBgp4Support(final PeerId peerId, final boolean announceNone) {
321 final TablesKey key = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
322 if (this.tables.add(key) && !announceNone) {
323 createAdjRibOutListener(peerId, key, false);
327 private void createAdjRibOutListener(final PeerId peerId, final TablesKey key, final boolean mpSupport) {
328 final RIBSupportContext context = this.rib.getRibSupportContext().getRIBSupportContext(key);
330 // not particularly nice
331 if (context != null && this.session instanceof BGPSessionImpl) {
332 this.adjRibOutListenerSet.put(key, AdjRibOutListener.create(peerId, key, this.rib.getYangRibId(), this.rib.getCodecsRegistry(),
333 context.getRibSupport(), ((RIBImpl) this.rib).getService(), ((BGPSessionImpl) this.session).getLimiter(), mpSupport, peerStats.getAdjRibOutRouteCounters().init(key)));
337 private synchronized void cleanup() {
338 // FIXME: BUG-196: support graceful
339 for (final AdjRibOutListener adjRibOutListener : this.adjRibOutListenerSet.values()) {
340 adjRibOutListener.close();
342 this.adjRibOutListenerSet.clear();
343 if (this.effRibInWriter != null) {
344 this.effRibInWriter.close();
346 this.ribWriter.removePeer();
351 public void onSessionDown(final BGPSession session, final Exception e) {
352 if(e.getMessage().equals(BGPSessionImpl.END_OF_INPUT)) {
353 LOG.info("Session with peer {} went down", this.name);
355 LOG.info("Session with peer {} went down", this.name, e);
361 public void onSessionTerminated(final BGPSession session, final BGPTerminationReason cause) {
362 LOG.info("Session with peer {} terminated: {}", this.name, cause);
367 public String toString() {
368 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
371 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
372 toStringHelper.add("name", this.name);
373 toStringHelper.add("tables", this.tables);
374 return toStringHelper;
378 public String getName() {
383 public void releaseConnection() {
384 if (this.rpcRegistration != null) {
385 this.rpcRegistration.close();
387 addPeerToDisconnectedSharedList();
392 private void addPeerToDisconnectedSharedList() {
393 if(this.session != null) {
394 this.rib.getCacheDisconnectedPeers().insertDesconectedPeer(this.session.getBgpId());
399 private void dropConnection() {
400 if (this.runtimeReg != null) {
401 this.runtimeReg.close();
402 this.runtimeReg = null;
404 if (this.session != null) {
406 this.session.close();
407 } catch (final Exception e) {
408 LOG.warn("Error closing session with peer", e);
412 this.rib.getRenderStats().getConnectedPeerCounter().decreaseCount();
417 public boolean isSessionActive() {
418 return this.session != null;
422 public synchronized byte[] getRawIdentifier() {
423 return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
427 public void resetSession() {
432 public void resetStats() {
433 if (this.session instanceof BGPSessionStats) {
434 ((BGPSessionStats) this.session).resetBgpSessionStats();
438 public synchronized void registerRootRuntimeBean(final BGPPeerRuntimeRegistrator registrator) {
439 this.registrator = registrator;
443 public BgpSessionState getBgpSessionState() {
444 if (this.session instanceof BGPSessionStats) {
445 return ((BGPSessionStats) this.session).getBgpSessionState();
447 return new BgpSessionState();
451 public synchronized BgpPeerState getBgpPeerState() {
452 return peerStats.getBgpPeerState();
456 public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
457 LOG.error("Transaction chain failed.", cause);
459 this.chain = this.rib.createPeerChain(this);
460 this.ribWriter = AdjRibInWriter.create(this.rib.getYangRibId(), this.peerRole, this.simpleRoutingPolicy, this.chain);
465 public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
466 LOG.debug("Transaction chain {} successfull.", chain);
470 public void markUptodate(final TablesKey tablesKey) {
471 this.ribWriter.markTableUptodate(tablesKey);