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 java.util.Objects.requireNonNull;
12 import com.google.common.base.MoreObjects;
13 import com.google.common.base.Objects;
14 import com.google.common.base.Stopwatch;
15 import com.google.common.cache.CacheBuilder;
16 import com.google.common.cache.CacheLoader;
17 import com.google.common.cache.LoadingCache;
18 import com.google.common.collect.ImmutableMap;
19 import com.google.common.collect.ImmutableSet;
20 import com.google.common.collect.Sets;
21 import com.google.common.net.InetAddresses;
22 import com.google.common.util.concurrent.FluentFuture;
23 import com.google.common.util.concurrent.Futures;
24 import com.google.common.util.concurrent.ListenableFuture;
25 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
26 import java.util.ArrayList;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.List;
32 import java.util.Optional;
34 import java.util.concurrent.TimeUnit;
35 import java.util.stream.Collectors;
36 import javax.annotation.concurrent.GuardedBy;
37 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
38 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
39 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
40 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
41 import org.opendaylight.mdsal.common.api.CommitInfo;
42 import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
43 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
44 import org.opendaylight.protocol.bgp.parser.BGPError;
45 import org.opendaylight.protocol.bgp.parser.impl.message.update.LocalPreferenceAttributeParser;
46 import org.opendaylight.protocol.bgp.parser.spi.MessageUtil;
47 import org.opendaylight.protocol.bgp.parser.spi.RevisedErrorHandlingSupport;
48 import org.opendaylight.protocol.bgp.rib.impl.config.BgpPeer;
49 import org.opendaylight.protocol.bgp.rib.impl.config.GracefulRestartUtil;
50 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
51 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
52 import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateProvider;
53 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
54 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
55 import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason;
56 import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
57 import org.opendaylight.protocol.bgp.rib.spi.RouterIds;
58 import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState;
59 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState;
60 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState;
61 import org.opendaylight.protocol.util.Ipv4Util;
62 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
63 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev180329.ipv4.prefixes.DestinationIpv4Builder;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev180329.ipv4.prefixes.destination.ipv4.Ipv4Prefixes;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev180329.ipv4.prefixes.destination.ipv4.Ipv4PrefixesBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev180329.update.attributes.mp.reach.nlri.advertized.routes.destination.type.DestinationIpv4CaseBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Update;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.open.message.BgpParameters;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.path.attributes.Attributes;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.path.attributes.AttributesBuilder;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.update.message.Nlri;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.BgpAddPathTableType;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.BgpTableType;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.RouteRefresh;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.SendReceive;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.GracefulRestartCapability;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.add.path.capability.AddressFamilies;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpReachNlri;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpReachNlriBuilder;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpUnreachNlri;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpUnreachNlriBuilder;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.mp.reach.nlri.AdvertizedRoutesBuilder;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.mp.unreach.nlri.WithdrawnRoutesBuilder;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.peer.rpc.rev180329.BgpPeerRpcService;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.peer.rpc.rev180329.PeerContext;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.PeerRole;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.PeerKey;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.peer.AdjRibOut;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.Tables;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.AddressFamily;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.ClusterIdentifier;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.Ipv4AddressFamily;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.RouteTarget;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.SubsequentAddressFamily;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.UnicastSubsequentAddressFamily;
98 import org.opendaylight.yangtools.concepts.Registration;
99 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
100 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
101 import org.opendaylight.yangtools.yang.binding.Notification;
102 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
103 import org.slf4j.Logger;
104 import org.slf4j.LoggerFactory;
107 * Class representing a peer. We have a single instance for each peer, which provides translation from BGP events into
110 public class BGPPeer extends AbstractPeer implements BGPSessionListener {
111 private static final Logger LOG = LoggerFactory.getLogger(BGPPeer.class);
112 private static final TablesKey IPV4_UCAST_TABLE_KEY = new TablesKey(Ipv4AddressFamily.class,
113 UnicastSubsequentAddressFamily.class);
115 private ImmutableSet<TablesKey> tables = ImmutableSet.of();
116 private ImmutableSet<TablesKey> advertizedTables = ImmutableSet.of();
117 private final RIB rib;
118 private final Map<TablesKey, AdjRibOutListener> adjRibOutListenerSet = new HashMap<>();
119 private final List<RouteTarget> rtMemberships = new ArrayList<>();
120 private final RpcProviderRegistry rpcRegistry;
121 private final BGPTableTypeRegistryConsumer tableTypeRegistry;
122 private final BgpPeer bgpPeer;
123 private InstanceIdentifier<AdjRibOut> peerRibOutIId;
124 private KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib
125 .rev180329.bgp.rib.rib.Peer, PeerKey> peerIId;
127 private Registration trackerRegistration;
128 private final LoadingCache<TablesKey, KeyedInstanceIdentifier<Tables, TablesKey>> tablesIId
129 = CacheBuilder.newBuilder()
130 .build(new CacheLoader<TablesKey, KeyedInstanceIdentifier<Tables, TablesKey>>() {
132 public KeyedInstanceIdentifier<Tables, TablesKey> load(final TablesKey tablesKey) {
133 return BGPPeer.this.peerRibOutIId.child(Tables.class, tablesKey);
138 private BGPSession currentSession;
140 private AdjRibInWriter ribWriter;
142 private EffectiveRibInWriter effRibInWriter;
143 private RoutedRpcRegistration<BgpPeerRpcService> rpcRegistration;
144 private Map<TablesKey, SendReceive> addPathTableMaps = Collections.emptyMap();
145 private YangInstanceIdentifier peerPath;
146 private boolean sessionUp;
147 private boolean llgrSupport;
148 private Stopwatch peerRestartStopwatch;
149 private long currentSelectionDeferralTimerSeconds;
150 private final List<TablesKey> missingEOT = new ArrayList<>();
153 final BGPTableTypeRegistryConsumer tableTypeRegistry,
154 final IpAddress neighborAddress,
155 final String peerGroupName,
158 final ClusterIdentifier clusterId,
159 final AsNumber localAs,
160 final RpcProviderRegistry rpcRegistry,
161 final Set<TablesKey> afiSafisAdvertized,
162 final Set<TablesKey> afiSafisGracefulAdvertized,
163 final Map<TablesKey, Integer> llGracefulTablesAdvertised,
164 final BgpPeer bgpPeer) {
165 super(rib, Ipv4Util.toStringIP(neighborAddress), peerGroupName, role, clusterId,
166 localAs, neighborAddress, afiSafisAdvertized, afiSafisGracefulAdvertized, llGracefulTablesAdvertised);
167 this.tableTypeRegistry = requireNonNull(tableTypeRegistry);
168 this.rib = requireNonNull(rib);
169 this.rpcRegistry = rpcRegistry;
170 this.bgpPeer = bgpPeer;
173 private static Attributes nextHopToAttribute(final Attributes attrs, final MpReachNlri mpReach) {
174 if (attrs.getCNextHop() == null && mpReach.getCNextHop() != null) {
175 final AttributesBuilder attributesBuilder = new AttributesBuilder(attrs);
176 attributesBuilder.setCNextHop(mpReach.getCNextHop());
177 return attributesBuilder.build();
183 * Creates MPReach for the prefixes to be handled in the same way as linkstate routes.
185 * @param message Update message containing prefixes in NLRI
186 * @return MpReachNlri with prefixes from the nlri field
188 private static MpReachNlri prefixesToMpReach(final Update message) {
189 final List<Ipv4Prefixes> prefixes = message.getNlri().stream()
190 .map(n -> new Ipv4PrefixesBuilder().setPrefix(n.getPrefix()).setPathId(n.getPathId()).build())
191 .collect(Collectors.toList());
192 final MpReachNlriBuilder b = new MpReachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi(
193 UnicastSubsequentAddressFamily.class).setAdvertizedRoutes(
194 new AdvertizedRoutesBuilder().setDestinationType(
195 new DestinationIpv4CaseBuilder().setDestinationIpv4(
196 new DestinationIpv4Builder().setIpv4Prefixes(prefixes).build()).build()).build());
197 if (message.getAttributes() != null) {
198 b.setCNextHop(message.getAttributes().getCNextHop());
204 * Create MPUnreach for the prefixes to be handled in the same way as linkstate routes.
206 * @param message Update message containing withdrawn routes
207 * @param isAnyNlriAnnounced isAnyNlriAnnounced
208 * @return MpUnreachNlri with prefixes from the withdrawn routes field
210 private static MpUnreachNlri prefixesToMpUnreach(final Update message, final boolean isAnyNlriAnnounced) {
211 final List<Ipv4Prefixes> prefixes = new ArrayList<>();
212 message.getWithdrawnRoutes().forEach(w -> {
214 Optional<Nlri> nlriAnounced = Optional.empty();
215 if (isAnyNlriAnnounced) {
216 nlriAnounced = message.getNlri().stream().filter(n -> Objects.equal(n.getPrefix(), w.getPrefix())
217 && Objects.equal(n.getPathId(), w.getPathId()))
220 if (!nlriAnounced.isPresent()) {
221 prefixes.add(new Ipv4PrefixesBuilder().setPrefix(w.getPrefix()).setPathId(w.getPathId()).build());
224 return new MpUnreachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi(UnicastSubsequentAddressFamily.class)
225 .setWithdrawnRoutes(new WithdrawnRoutesBuilder().setDestinationType(new org.opendaylight.yang.gen.v1
226 .urn.opendaylight.params.xml.ns.yang.bgp.inet.rev180329.update.attributes.mp.unreach.nlri
227 .withdrawn.routes.destination.type.DestinationIpv4CaseBuilder().setDestinationIpv4(
228 new DestinationIpv4Builder().setIpv4Prefixes(prefixes).build()).build()).build()).build();
231 private static Map<TablesKey, SendReceive> mapTableTypesFamilies(final List<AddressFamilies> addPathTablesType) {
232 return ImmutableMap.copyOf(addPathTablesType.stream().collect(Collectors.toMap(af -> new TablesKey(af.getAfi(),
233 af.getSafi()), BgpAddPathTableType::getSendReceive)));
236 public synchronized void instantiateServiceInstance() {
237 this.ribWriter = AdjRibInWriter.create(this.rib.getYangRibId(), this.peerRole, this);
242 public synchronized FluentFuture<? extends CommitInfo> close() {
243 final FluentFuture<? extends CommitInfo> future = releaseConnection();
250 public void onMessage(final BGPSession session, final Notification msg) throws BGPDocumentedException {
251 if (msg instanceof Update) {
252 onUpdateMessage((Update) msg);
253 } else if (msg instanceof RouteRefresh) {
254 onRouteRefreshMessage((RouteRefresh) msg);
256 LOG.info("Ignoring unhandled message class {}", msg.getClass());
260 private void onRouteRefreshMessage(final RouteRefresh message) {
261 final Class<? extends AddressFamily> rrAfi = message.getAfi();
262 final Class<? extends SubsequentAddressFamily> rrSafi = message.getSafi();
264 final TablesKey key = new TablesKey(rrAfi, rrSafi);
265 synchronized (this) {
266 final AdjRibOutListener listener = this.adjRibOutListenerSet.remove(key);
267 if (listener != null) {
269 createAdjRibOutListener(key, listener.isMpSupported());
271 LOG.info("Ignoring RouteRefresh message. Afi/Safi is not supported: {}, {}.", rrAfi, rrSafi);
277 * Check for presence of well known mandatory attribute LOCAL_PREF in Update message.
279 * @param message Update message
281 private void checkMandatoryAttributesPresence(final Update message) throws BGPDocumentedException {
282 if (MessageUtil.isAnyNlriPresent(message)) {
283 final Attributes attrs = message.getAttributes();
284 if (this.peerRole == PeerRole.Ibgp && (attrs == null || attrs.getLocalPref() == null)) {
285 throw new BGPDocumentedException(BGPError.MANDATORY_ATTR_MISSING_MSG + "LOCAL_PREF",
286 BGPError.WELL_KNOWN_ATTR_MISSING,
287 new byte[]{LocalPreferenceAttributeParser.TYPE});
293 * Process Update message received.
294 * Calls {@link #checkMandatoryAttributesPresence(Update)} to check for presence of mandatory attributes.
296 * @param message Update message
298 private synchronized void onUpdateMessage(final Update message) throws BGPDocumentedException {
299 checkMandatoryAttributesPresence(message);
302 final Attributes attrs = message.getAttributes();
304 final boolean isAnyNlriAnnounced = message.getNlri() != null;
305 if (isAnyNlriAnnounced) {
306 mpReach = prefixesToMpReach(message);
308 mpReach = MessageUtil.getMpReachNlri(attrs);
310 if (mpReach != null) {
311 this.ribWriter.updateRoutes(mpReach, nextHopToAttribute(attrs, mpReach));
313 final MpUnreachNlri mpUnreach;
314 if (message.getWithdrawnRoutes() != null) {
315 mpUnreach = prefixesToMpUnreach(message, isAnyNlriAnnounced);
317 mpUnreach = MessageUtil.getMpUnreachNlri(attrs);
319 final boolean endOfRib = BgpPeerUtil.isEndOfRib(message);
320 if (mpUnreach != null) {
322 final TablesKey tablesKey = new TablesKey(mpUnreach.getAfi(), mpUnreach.getSafi());
323 this.ribWriter.removeStaleRoutes(tablesKey);
324 this.missingEOT.remove(tablesKey);
325 handleGracefulEndOfRib();
327 this.ribWriter.removeRoutes(mpUnreach);
329 } else if (endOfRib) {
330 this.ribWriter.removeStaleRoutes(IPV4_UCAST_TABLE_KEY);
331 this.missingEOT.remove(IPV4_UCAST_TABLE_KEY);
332 handleGracefulEndOfRib();
337 private void handleGracefulEndOfRib() {
338 if (isLocalRestarting()) {
339 if (this.missingEOT.isEmpty()) {
340 createEffRibInWriter();
341 this.effRibInWriter.init();
342 registerPrefixesCounters(this.effRibInWriter, this.effRibInWriter);
343 for (final TablesKey key : this.advertizedTables) {
344 createAdjRibOutListener(key, true);
346 setLocalRestartingState(false);
347 setGracefulPreferences(false, Collections.emptySet());
353 public synchronized void onSessionUp(final BGPSession session) {
354 this.currentSession = session;
355 this.sessionUp = true;
356 this.bindingChain = this.rib.createPeerChain(this);
357 if (this.currentSession instanceof BGPSessionStateProvider) {
358 ((BGPSessionStateProvider) this.currentSession).registerMessagesCounter(this);
360 final GracefulRestartCapability advertisedGracefulRestartCapability =
361 session.getAdvertisedGracefulRestartCapability();
362 final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp
363 .capabilities.graceful.restart.capability.Tables> advertisedTables =
364 advertisedGracefulRestartCapability.getTables();
365 final List<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp
366 .capabilities.ll.graceful.restart.capability.Tables> advertisedLLTables =
367 session.getAdvertisedLlGracefulRestartCapability().getTables();
369 final List<AddressFamilies> addPathTablesType = session.getAdvertisedAddPathTableTypes();
370 final Set<BgpTableType> advertizedTableTypes = session.getAdvertisedTableTypes();
371 LOG.info("Session with peer {} went up with tables {} and Add Path tables {}", this.name,
372 advertizedTableTypes, addPathTablesType);
373 final Set<TablesKey> setTables = advertizedTableTypes.stream().map(t -> new TablesKey(t.getAfi(), t.getSafi()))
374 .collect(Collectors.toSet());
375 this.tables = ImmutableSet.copyOf(setTables);
376 this.advertizedTables = ImmutableSet.copyOf(Sets.intersection(tables, getAfiSafisAdvertized()));
378 this.addPathTableMaps = mapTableTypesFamilies(addPathTablesType);
379 final boolean restartingLocally = isLocalRestarting();
381 if (!isRestartingGracefully()) {
382 this.rawIdentifier = InetAddresses.forString(session.getBgpId().getValue()).getAddress();
383 this.peerId = RouterIds.createPeerId(session.getBgpId());
384 this.peerIId = getInstanceIdentifier().child(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns
385 .yang.bgp.rib.rev180329.bgp.rib.rib.Peer.class, new PeerKey(this.peerId));
386 this.peerPath = createPeerPath();
387 this.peerRibOutIId = peerIId.child(AdjRibOut.class);
388 this.trackerRegistration = this.rib.getPeerTracker().registerPeer(this);
389 createEffRibInWriter();
390 registerPrefixesCounters(this.effRibInWriter, this.effRibInWriter);
392 this.effRibInWriter.init();
393 this.ribWriter = this.ribWriter.transform(this.peerId, this.peerPath, this.rib.getRibSupportContext(),
394 this.tables, this.addPathTableMaps);
396 if (this.rpcRegistry != null) {
397 this.rpcRegistration = this.rpcRegistry.addRoutedRpcImplementation(BgpPeerRpcService.class,
398 new BgpPeerRpc(this, session, this.tables));
399 final KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib
400 .rev180329.bgp.rib.rib.Peer, PeerKey> path = this.rib.getInstanceIdentifier()
401 .child(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp
402 .rib.rib.Peer.class, new PeerKey(this.peerId));
403 this.rpcRegistration.registerPath(PeerContext.class, path);
406 final Set<TablesKey> forwardingTables;
407 if (advertisedTables == null) {
408 forwardingTables = Collections.emptySet();
410 forwardingTables = advertisedTables.stream()
411 .filter(table -> table.getAfiFlags() != null)
412 .filter(table -> table.getAfiFlags().isForwardingState())
413 .map(table -> new TablesKey(table.getAfi(), table.getSafi()))
414 .collect(Collectors.toSet());
416 this.ribWriter.clearTables(Sets.difference(this.tables, forwardingTables));
417 if (restartingLocally) {
418 this.effRibInWriter.close();
419 this.peerRestartStopwatch = Stopwatch.createStarted();
420 handleSelectionReferralTimer();
421 this.missingEOT.addAll(this.tables);
424 if (advertisedTables == null || advertisedTables.isEmpty()) {
425 setAdvertizedGracefulRestartTableTypes(Collections.emptyList());
427 setAdvertizedGracefulRestartTableTypes(advertisedTables.stream()
428 .map(t -> new TablesKey(t.getAfi(), t.getSafi())).collect(Collectors.toList()));
430 setAfiSafiGracefulRestartState(advertisedGracefulRestartCapability.getRestartTime(), false, restartingLocally);
432 final Map<TablesKey, Integer> llTablesReceived;
433 if (advertisedLLTables != null) {
434 llTablesReceived = new HashMap<>();
435 for (org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp
436 .capabilities.ll.graceful.restart.capability.Tables table : advertisedLLTables) {
437 llTablesReceived.put(new TablesKey(table.getAfi(), table.getSafi()),
438 table.getLongLivedStaleTime().intValue());
441 llTablesReceived = Collections.emptyMap();
443 setAdvertizedLlGracefulRestartTableTypes(llTablesReceived);
445 if (!llTablesReceived.isEmpty()) {
447 // FIXME: propagate preserved tables
449 // FIXME: clear preserved tables
453 if (!restartingLocally) {
455 for (final TablesKey key : this.advertizedTables) {
456 createAdjRibOutListener(key, true);
460 // SpotBugs does not grok Optional.ifPresent() and thinks we are using unsynchronized access
461 final Optional<RevisedErrorHandlingSupport> errorHandling = this.bgpPeer.getErrorHandling();
462 if (errorHandling.isPresent()) {
463 this.currentSession.addDecoderConstraint(RevisedErrorHandlingSupport.class, errorHandling.get());
467 private boolean isRestartingGracefully() {
468 return isLocalRestarting() || isPeerRestarting();
471 private synchronized void createEffRibInWriter() {
472 this.effRibInWriter = new EffectiveRibInWriter(this, this.rib,
473 this.rib.createPeerDOMChain(this),
474 this.peerPath, this.tables, this.tableTypeRegistry,
479 //try to add a support for old-school BGP-4, if peer did not advertise IPv4-Unicast MP capability
481 private void addBgp4Support() {
482 if (!this.tables.contains(IPV4_UCAST_TABLE_KEY)) {
483 final HashSet<TablesKey> newSet = new HashSet<>(this.tables);
484 newSet.add(IPV4_UCAST_TABLE_KEY);
485 this.tables = ImmutableSet.copyOf(newSet);
486 createAdjRibOutListener(IPV4_UCAST_TABLE_KEY, false);
491 private void createAdjRibOutListener(final TablesKey key, final boolean mpSupport) {
492 final RIBSupport<?, ?, ?, ?> ribSupport = this.rib.getRibSupportContext().getRIBSupport(key);
494 // not particularly nice
495 if (ribSupport != null && this.currentSession instanceof BGPSessionImpl) {
496 final ChannelOutputLimiter limiter = ((BGPSessionImpl) this.currentSession).getLimiter();
497 final AdjRibOutListener adjRibOut = AdjRibOutListener.create(this.peerId, key,
498 this.rib.getYangRibId(), this.rib.getCodecsRegistry(), ribSupport,
499 this.rib.getService(), limiter, mpSupport);
500 this.adjRibOutListenerSet.put(key, adjRibOut);
501 registerPrefixesSentCounter(key, adjRibOut);
506 public synchronized void onSessionDown(final BGPSession session, final Exception exc) {
507 if (exc.getMessage().equals(BGPSessionImpl.END_OF_INPUT)) {
508 LOG.info("Session with peer {} went down", this.name);
510 LOG.info("Session with peer {} went down", this.name, exc);
512 releaseConnectionGracefully();
516 public synchronized void onSessionTerminated(final BGPSession session, final BGPTerminationReason cause) {
517 LOG.info("Session with peer {} terminated: {}", this.name, cause);
518 releaseConnectionGracefully();
522 public String toString() {
523 return MoreObjects.toStringHelper(this).add("name", this.name).add("tables", this.tables).toString();
527 public synchronized FluentFuture<? extends CommitInfo> releaseConnection() {
528 LOG.info("Closing session with peer");
529 this.sessionUp = false;
530 this.adjRibOutListenerSet.values().forEach(AdjRibOutListener::close);
531 this.adjRibOutListenerSet.clear();
532 final FluentFuture<? extends CommitInfo> future;
533 if (!isRestartingGracefully()) {
534 future = terminateConnection();
536 final Set<TablesKey> gracefulTables = getGracefulTables();
537 this.ribWriter.storeStaleRoutes(gracefulTables);
538 future = this.ribWriter.clearTables(Sets.difference(this.tables, gracefulTables));
539 if (isPeerRestarting()) {
540 this.peerRestartStopwatch = Stopwatch.createStarted();
541 handleRestartTimer();
544 releaseBindingChain();
551 @SuppressWarnings("checkstyle:illegalCatch")
552 private void closeSession() {
553 if (this.currentSession != null) {
555 if (isRestartingGracefully()) {
556 this.currentSession.closeWithoutMessage();
558 this.currentSession.close();
560 } catch (final Exception e) {
561 LOG.warn("Error closing session with peer", e);
563 this.currentSession = null;
567 private Set<TablesKey> getGracefulTables() {
568 return this.tables.stream()
569 .filter(this::isGracefulRestartReceived)
570 .filter(this::isGracefulRestartAdvertized)
571 .collect(Collectors.toSet());
574 private synchronized FluentFuture<? extends CommitInfo> terminateConnection() {
575 final FluentFuture<? extends CommitInfo> future;
576 if (this.trackerRegistration != null) {
577 this.trackerRegistration.close();
578 this.trackerRegistration = null;
580 if (this.rpcRegistration != null) {
581 this.rpcRegistration.close();
583 this.ribWriter.releaseChain();
585 if (this.effRibInWriter != null) {
586 this.effRibInWriter.close();
588 this.tables = ImmutableSet.of();
589 this.addPathTableMaps = Collections.emptyMap();
590 future = removePeer(this.peerPath);
597 * If Graceful Restart Timer expires, remove all routes advertised by peer.
599 private synchronized void handleRestartTimer() {
600 if (!isPeerRestarting()) {
604 final long peerRestartTimeNanos = TimeUnit.SECONDS.toNanos(getPeerRestartTime());
605 final long elapsedNanos = this.peerRestartStopwatch.elapsed(TimeUnit.NANOSECONDS);
606 if (elapsedNanos >= peerRestartTimeNanos) {
607 setAfiSafiGracefulRestartState(0, false, false);
608 onSessionTerminated(this.currentSession, new BGPTerminationReason(BGPError.HOLD_TIMER_EXPIRED));
611 currentSession.schedule(this::handleRestartTimer, peerRestartTimeNanos - elapsedNanos, TimeUnit.NANOSECONDS);
614 private synchronized void handleSelectionReferralTimer() {
615 if (!isLocalRestarting()) {
619 final long referalTimerNanos = TimeUnit.SECONDS.toNanos(this.currentSelectionDeferralTimerSeconds);
620 final long elapsedNanos = this.peerRestartStopwatch.elapsed(TimeUnit.NANOSECONDS);
621 if (elapsedNanos >= referalTimerNanos) {
622 this.missingEOT.clear();
623 handleGracefulEndOfRib();
625 currentSession.schedule(this::handleSelectionReferralTimer, referalTimerNanos - elapsedNanos,
626 TimeUnit.NANOSECONDS);
629 private void releaseConnectionGracefully() {
630 if (getPeerRestartTime() > 0) {
631 setRestartingState();
636 @SuppressFBWarnings("IS2_INCONSISTENT_SYNC")
638 public SendReceive getSupportedAddPathTables(final TablesKey tableKey) {
639 return this.addPathTableMaps.get(tableKey);
643 public boolean supportsTable(final TablesKey tableKey) {
644 return this.advertizedTables.contains(tableKey) && this.sessionUp;
648 public KeyedInstanceIdentifier<Tables, TablesKey> getRibOutIId(final TablesKey tablesKey) {
649 return this.tablesIId.getUnchecked(tablesKey);
653 public synchronized void onTransactionChainFailed(final TransactionChain<?, ?> chain,
654 final AsyncTransaction<?, ?> transaction, final Throwable cause) {
655 LOG.error("Transaction domChain failed.", cause);
660 public synchronized void markUptodate(final TablesKey tablesKey) {
661 this.ribWriter.markTableUptodate(tablesKey);
665 public synchronized BGPSessionState getBGPSessionState() {
666 if (this.currentSession instanceof BGPSessionStateProvider) {
667 return ((BGPSessionStateProvider) this.currentSession).getBGPSessionState();
673 public synchronized BGPTimersState getBGPTimersState() {
674 if (this.currentSession instanceof BGPSessionStateProvider) {
675 return ((BGPSessionStateProvider) this.currentSession).getBGPTimersState();
681 public synchronized BGPTransportState getBGPTransportState() {
682 if (this.currentSession instanceof BGPSessionStateProvider) {
683 return ((BGPSessionStateProvider) this.currentSession).getBGPTransportState();
689 public List<RouteTarget> getMemberships() {
690 return this.rtMemberships;
694 public synchronized ListenableFuture<?> restartGracefully(final long selectionDeferralTimerSeconds) {
695 final Set<TablesKey> tablesToPreserve = getGracefulTables();
696 if (tablesToPreserve == null || tablesToPreserve.isEmpty()) {
697 LOG.info("Peer {} is not capable of graceful restart or have no matching graceful tables.", this.peerId);
698 return Futures.immediateFailedFuture(new UnsupportedOperationException(
699 "Peer is not capable of graceful restart"));
701 setGracefulPreferences(true, tablesToPreserve);
702 this.currentSelectionDeferralTimerSeconds = selectionDeferralTimerSeconds;
703 setLocalRestartingState(true);
704 return releaseConnection();
708 boolean supportsLLGR() {
709 return this.llgrSupport;
712 private synchronized void setGracefulPreferences(final boolean localRestarting,
713 final Set<TablesKey> preservedTables) {
714 final Set<TablesKey> gracefulTables = this.tables.stream()
715 .filter(this::isGracefulRestartAdvertized)
716 .collect(Collectors.toSet());
717 final BgpParameters bgpParameters = GracefulRestartUtil.getGracefulBgpParameters(
718 this.bgpPeer.getBgpFixedCapabilities(), gracefulTables, preservedTables,
719 this.bgpPeer.getGracefulRestartTimer(), localRestarting, Collections.emptySet());
720 final BGPSessionPreferences oldPrefs = this.rib.getDispatcher().getBGPPeerRegistry()
721 .getPeerPreferences(getNeighborAddress());
722 final BGPSessionPreferences newPrefs = new BGPSessionPreferences(
724 oldPrefs.getHoldTime(),
726 oldPrefs.getExpectedRemoteAs(),
727 Collections.singletonList(bgpParameters),
728 oldPrefs.getMd5Password());
729 this.rib.getDispatcher().getBGPPeerRegistry()
730 .updatePeerPreferences(getNeighborAddress(), newPrefs);