BGPCEP-685: Add Peer Release session rpc
[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 static java.util.Objects.requireNonNull;
11 import static org.opendaylight.protocol.bgp.rib.impl.AdjRibInWriter.isAnnounceNone;
12 import static org.opendaylight.protocol.bgp.rib.impl.AdjRibInWriter.isLearnNone;
13
14 import com.google.common.base.MoreObjects;
15 import com.google.common.base.MoreObjects.ToStringHelper;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.net.InetAddresses;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Optional;
27 import java.util.Set;
28 import java.util.stream.Collectors;
29 import javax.annotation.Nonnull;
30 import javax.annotation.concurrent.GuardedBy;
31 import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeMXBean;
32 import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeRegistration;
33 import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeRegistrator;
34 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpPeerState;
35 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
36 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
37 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
38 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
39 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
40 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
41 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
42 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
43 import org.opendaylight.protocol.bgp.parser.BGPError;
44 import org.opendaylight.protocol.bgp.parser.impl.message.update.LocalPreferenceAttributeParser;
45 import org.opendaylight.protocol.bgp.parser.spi.MessageUtil;
46 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
47 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContext;
48 import org.opendaylight.protocol.bgp.rib.impl.state.BGPPeerStateImpl;
49 import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateProvider;
50 import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPPeerStats;
51 import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPPeerStatsImpl;
52 import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPSessionStats;
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.ExportPolicyPeerTracker;
57 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
58 import org.opendaylight.protocol.bgp.rib.spi.Peer;
59 import org.opendaylight.protocol.bgp.rib.spi.RouterIds;
60 import org.opendaylight.protocol.bgp.rib.spi.state.BGPAfiSafiState;
61 import org.opendaylight.protocol.bgp.rib.spi.state.BGPErrorHandlingState;
62 import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState;
63 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState;
64 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState;
65 import org.opendaylight.protocol.concepts.AbstractRegistration;
66 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
67 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
68 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.DestinationIpv4Builder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.destination.ipv4.Ipv4Prefixes;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.destination.ipv4.Ipv4PrefixesBuilder;
72 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;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.Attributes;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.AttributesBuilder;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpAddPathTableType;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.RouteRefresh;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.SendReceive;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.add.path.capability.AddressFamilies;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpReachNlri;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpReachNlriBuilder;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpUnreachNlri;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpUnreachNlriBuilder;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.mp.reach.nlri.AdvertizedRoutesBuilder;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.mp.unreach.nlri.WithdrawnRoutesBuilder;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.peer.rpc.rev171027.BgpPeerRpcService;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.peer.rpc.rev171027.PeerContext;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.SimpleRoutingPolicy;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.PeerKey;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.AddressFamily;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.Ipv4AddressFamily;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.SubsequentAddressFamily;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.UnicastSubsequentAddressFamily;
98 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
99 import org.opendaylight.yangtools.yang.binding.Notification;
100 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
101 import org.slf4j.Logger;
102 import org.slf4j.LoggerFactory;
103
104 /**
105  * Class representing a peer. We have a single instance for each peer, which provides translation from BGP events into
106  * RIB actions.
107  */
108 public class BGPPeer extends BGPPeerStateImpl implements BGPSessionListener, Peer, BGPPeerRuntimeMXBean,
109     TransactionChainListener {
110     private static final Logger LOG = LoggerFactory.getLogger(BGPPeer.class);
111
112     @GuardedBy("this")
113     private final Set<TablesKey> tables = new HashSet<>();
114     @GuardedBy("this")
115     private BGPSession session;
116     @GuardedBy("this")
117     private byte[] rawIdentifier;
118     @GuardedBy("this")
119     private DOMTransactionChain chain;
120     @GuardedBy("this")
121     private AdjRibInWriter ribWriter;
122     @GuardedBy("this")
123     private EffectiveRibInWriter effRibInWriter;
124
125     private final RIB rib;
126     private final String name;
127     private BGPPeerRuntimeRegistrator registrator;
128     private BGPPeerRuntimeRegistration runtimeReg;
129     private final Map<TablesKey, AdjRibOutListener> adjRibOutListenerSet = new HashMap<>();
130     private final RpcProviderRegistry rpcRegistry;
131     private RoutedRpcRegistration<BgpPeerRpcService> rpcRegistration;
132     private final PeerRole peerRole;
133     private final Optional<SimpleRoutingPolicy> simpleRoutingPolicy;
134     private final BGPPeerStats peerStats;
135     private YangInstanceIdentifier peerIId;
136     private final Set<AbstractRegistration> tableRegistration = new HashSet<>();
137
138     public BGPPeer(final String name, final RIB rib, final PeerRole role, final SimpleRoutingPolicy peerStatus,
139         final RpcProviderRegistry rpcRegistry,
140         @Nonnull final Set<TablesKey> afiSafisAdvertized,
141         @Nonnull final Set<TablesKey> afiSafisGracefulAdvertized) {
142         //FIXME BUG-6971 Once Peer Group is implemented, pass it
143         super(rib.getInstanceIdentifier(), null, new IpAddress(new Ipv4Address(name)), afiSafisAdvertized,
144             afiSafisGracefulAdvertized);
145         this.peerRole = role;
146         this.simpleRoutingPolicy = Optional.ofNullable(peerStatus);
147         this.rib = requireNonNull(rib);
148         this.name = name;
149         this.rpcRegistry = rpcRegistry;
150         this.peerStats = new BGPPeerStatsImpl(this.name, this.tables, this);
151         this.chain = rib.createPeerChain(this);
152     }
153
154     public BGPPeer(final String name, final RIB rib, final PeerRole role,
155         final RpcProviderRegistry rpcRegistry, @Nonnull final Set<TablesKey> afiSafisAdvertized,
156         @Nonnull final Set<TablesKey> afiSafisGracefulAdvertized) {
157         this(name, rib, role, null, rpcRegistry, afiSafisAdvertized, afiSafisGracefulAdvertized);
158     }
159
160     public void instantiateServiceInstance() {
161         // add current peer to "configured BGP peer" stats
162         this.rib.getRenderStats().getConfiguredPeerCounter().increment();
163         this.ribWriter = AdjRibInWriter.create(this.rib.getYangRibId(), this.peerRole, this.simpleRoutingPolicy, this.chain);
164     }
165
166     // FIXME ListenableFuture<?> should be used once closeServiceInstance uses wildcard too
167     @Override
168     public synchronized ListenableFuture<Void> close() {
169         final ListenableFuture<Void> future = releaseConnection();
170         this.chain.close();
171         return future;
172     }
173
174     @Override
175     public void onMessage(final BGPSession session, final Notification msg) throws BGPDocumentedException {
176         if (!(msg instanceof Update) && !(msg instanceof RouteRefresh)) {
177             LOG.info("Ignoring unhandled message class {}", msg.getClass());
178             return;
179         }
180         if (msg instanceof Update) {
181             onUpdateMessage((Update) msg);
182         } else {
183             onRouteRefreshMessage((RouteRefresh) msg, session);
184         }
185     }
186
187     private void onRouteRefreshMessage(final RouteRefresh message, final BGPSession session) {
188         final Class<? extends AddressFamily> rrAfi = message.getAfi();
189         final Class<? extends SubsequentAddressFamily> rrSafi = message.getSafi();
190
191         final TablesKey key = new TablesKey(rrAfi, rrSafi);
192         final AdjRibOutListener listener = this.adjRibOutListenerSet.get(key);
193         if (listener != null) {
194             listener.close();
195             this.adjRibOutListenerSet.remove(key);
196             createAdjRibOutListener(RouterIds.createPeerId(session.getBgpId()), key, listener.isMpSupported());
197         } else {
198             LOG.info("Ignoring RouteRefresh message. Afi/Safi is not supported: {}, {}.", rrAfi, rrSafi);
199         }
200     }
201
202     /**
203      * Check for presence of well known mandatory attribute LOCAL_PREF in Update message
204      *
205      * @param message Update message
206      * @throws BGPDocumentedException
207      */
208     private void checkMandatoryAttributesPresence(final Update message) throws BGPDocumentedException {
209         if (MessageUtil.isAnyNlriPresent(message)) {
210             final Attributes attrs = message.getAttributes();
211             if (this.peerRole == PeerRole.Ibgp && (attrs == null || attrs.getLocalPref() == null)) {
212                 throw new BGPDocumentedException(BGPError.MANDATORY_ATTR_MISSING_MSG + "LOCAL_PREF",
213                         BGPError.WELL_KNOWN_ATTR_MISSING,
214                         new byte[] { LocalPreferenceAttributeParser.TYPE });
215             }
216         }
217     }
218
219     /**
220      * Process Update message received.
221      * Calls {@link #checkMandatoryAttributesPresence(Update)} to check for presence of mandatory attributes.
222      *
223      * @param message Update message
224      * @throws BGPDocumentedException
225      */
226     private void onUpdateMessage(final Update message) throws BGPDocumentedException {
227         checkMandatoryAttributesPresence(message);
228
229         // update AdjRibs
230         final Attributes attrs = message.getAttributes();
231         MpReachNlri mpReach = null;
232         final boolean isAnyNlriAnnounced = message.getNlri() != null;
233         if (isAnyNlriAnnounced) {
234             mpReach = prefixesToMpReach(message);
235         } else {
236             mpReach = MessageUtil.getMpReachNlri(attrs);
237         }
238         if (mpReach != null) {
239             this.ribWriter.updateRoutes(mpReach, nextHopToAttribute(attrs, mpReach));
240         }
241         MpUnreachNlri mpUnreach = null;
242         if (message.getWithdrawnRoutes() != null) {
243             mpUnreach = prefixesToMpUnreach(message, isAnyNlriAnnounced);
244         } else {
245             mpUnreach = MessageUtil.getMpUnreachNlri(attrs);
246         }
247         if (mpUnreach != null) {
248             this.ribWriter.removeRoutes(mpUnreach);
249         }
250     }
251
252     private static Attributes nextHopToAttribute(final Attributes attrs, final MpReachNlri mpReach) {
253         if (attrs.getCNextHop() == null && mpReach.getCNextHop() != null) {
254             final AttributesBuilder attributesBuilder = new AttributesBuilder(attrs);
255             attributesBuilder.setCNextHop(mpReach.getCNextHop());
256             return attributesBuilder.build();
257         }
258         return attrs;
259     }
260
261     /**
262      * Creates MPReach for the prefixes to be handled in the same way as linkstate routes
263      *
264      * @param message Update message containing prefixes in NLRI
265      * @return MpReachNlri with prefixes from the nlri field
266      */
267     private static MpReachNlri prefixesToMpReach(final Update message) {
268         final List<Ipv4Prefixes> prefixes = new ArrayList<>();
269         for (final Ipv4Prefix p : message.getNlri().getNlri()) {
270             prefixes.add(new Ipv4PrefixesBuilder().setPrefix(p).build());
271         }
272         final MpReachNlriBuilder b = new MpReachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi(
273                 UnicastSubsequentAddressFamily.class).setAdvertizedRoutes(
274                         new AdvertizedRoutesBuilder().setDestinationType(
275                                 new DestinationIpv4CaseBuilder().setDestinationIpv4(
276                                         new DestinationIpv4Builder().setIpv4Prefixes(prefixes).build()).build()).build());
277         if (message.getAttributes() != null) {
278             b.setCNextHop(message.getAttributes().getCNextHop());
279         }
280         return b.build();
281     }
282
283     /**
284      * Create MPUnreach for the prefixes to be handled in the same way as linkstate routes
285      *
286      * @param message Update message containing withdrawn routes
287      * @param isAnyNlriAnnounced
288      * @return MpUnreachNlri with prefixes from the withdrawn routes field
289      */
290     private static MpUnreachNlri prefixesToMpUnreach(final Update message, final boolean isAnyNlriAnnounced) {
291         final List<Ipv4Prefixes> prefixes = new ArrayList<>();
292         for (final Ipv4Prefix p : message.getWithdrawnRoutes().getWithdrawnRoutes()) {
293             boolean nlriAnounced = false;
294             if(isAnyNlriAnnounced) {
295                 nlriAnounced = message.getNlri().getNlri().contains(p);
296             }
297
298             if(!nlriAnounced) {
299                 prefixes.add(new Ipv4PrefixesBuilder().setPrefix(p).build());
300             }
301         }
302         return new MpUnreachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi(UnicastSubsequentAddressFamily.class).setWithdrawnRoutes(
303                 new WithdrawnRoutesBuilder().setDestinationType(
304                         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(
305                                 new DestinationIpv4Builder().setIpv4Prefixes(prefixes).build()).build()).build()).build();
306     }
307
308     @Override
309     public synchronized void onSessionUp(final BGPSession session) {
310         this.session = session;
311         if (this.session instanceof BGPSessionStateProvider) {
312             ((BGPSessionStateProvider) this.session).registerMessagesCounter(this);
313         }
314
315         final List<AddressFamilies> addPathTablesType = session.getAdvertisedAddPathTableTypes();
316         final Set<BgpTableType> advertizedTableTypes = session.getAdvertisedTableTypes();
317         final List<BgpTableType> advertizedGracefulRestartTableTypes = session.getAdvertisedGracefulRestartTableTypes();
318         LOG.info("Session with peer {} went up with tables {} and Add Path tables {}", this.name, advertizedTableTypes, addPathTablesType);
319         this.rawIdentifier = InetAddresses.forString(session.getBgpId().getValue()).getAddress();
320         final PeerId peerId = RouterIds.createPeerId(session.getBgpId());
321
322         this.tables.addAll(advertizedTableTypes.stream().map(t -> new TablesKey(t.getAfi(), t.getSafi())).collect(Collectors.toList()));
323
324         setAdvertizedGracefulRestartTableTypes(advertizedGracefulRestartTableTypes.stream()
325             .map(t -> new TablesKey(t.getAfi(), t.getSafi())).collect(Collectors.toList()));
326         final boolean announceNone = isAnnounceNone(this.simpleRoutingPolicy);
327         final Map<TablesKey, SendReceive> addPathTableMaps = mapTableTypesFamilies(addPathTablesType);
328         this.peerIId = this.rib.getYangRibId().node(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer.QNAME)
329             .node(IdentifierUtils.domPeerId(peerId));
330
331         if(!announceNone) {
332             createAdjRibOutListener(peerId);
333         }
334         this.tables.forEach(tablesKey -> {
335             final ExportPolicyPeerTracker exportTracker = this.rib.getExportPolicyPeerTracker(tablesKey);
336             if (exportTracker != null) {
337                 this.tableRegistration.add(exportTracker.registerPeer(peerId, addPathTableMaps.get(tablesKey), this.peerIId, this.peerRole,
338                     this.simpleRoutingPolicy));
339             }
340         });
341         addBgp4Support(peerId, announceNone);
342
343         if(!isLearnNone(this.simpleRoutingPolicy)) {
344             this.effRibInWriter = EffectiveRibInWriter.create(this.rib.getService(), this.rib.createPeerChain(this),
345                 this.peerIId, this.rib.getImportPolicyPeerTracker(), this.rib.getRibSupportContext(), this.peerRole,
346                 this.peerStats.getAdjRibInRouteCounters(), this.tables);
347             registerPrefixesCounters(this.effRibInWriter, this.effRibInWriter);
348         }
349         this.ribWriter = this.ribWriter.transform(peerId, this.rib.getRibSupportContext(), this.tables, addPathTableMaps);
350
351         // register BGP Peer stats
352         this.peerStats.getSessionEstablishedCounter().increment();
353         if (this.registrator != null) {
354             this.runtimeReg = this.registrator.register(this);
355         }
356
357         if (this.rpcRegistry != null) {
358             this.rpcRegistration = this.rpcRegistry.addRoutedRpcImplementation(BgpPeerRpcService.class,
359                     new BgpPeerRpc(this, session, this.tables));
360             final KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer, PeerKey> path =
361                     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));
362             this.rpcRegistration.registerPath(PeerContext.class, path);
363         }
364
365         this.rib.getRenderStats().getConnectedPeerCounter().increment();
366     }
367
368     private void createAdjRibOutListener(final PeerId peerId) {
369         this.tables.forEach(key->createAdjRibOutListener(peerId, key, true));
370     }
371
372     //try to add a support for old-school BGP-4, if peer did not advertise IPv4-Unicast MP capability
373     private void addBgp4Support(final PeerId peerId, final boolean announceNone) {
374         final TablesKey key = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
375         if (this.tables.add(key) && !announceNone) {
376             createAdjRibOutListener(peerId, key, false);
377         }
378     }
379
380     private void createAdjRibOutListener(final PeerId peerId, final TablesKey key, final boolean mpSupport) {
381         final RIBSupportContext context = this.rib.getRibSupportContext().getRIBSupportContext(key);
382
383         // not particularly nice
384         if (context != null && this.session instanceof BGPSessionImpl) {
385             final ChannelOutputLimiter limiter = ((BGPSessionImpl) this.session).getLimiter();
386             final AdjRibOutListener adjRibOut = AdjRibOutListener.create(peerId, key,
387                 this.rib.getYangRibId(), this.rib.getCodecsRegistry(), context.getRibSupport(),
388                 this.rib.getService(), limiter, mpSupport, this.peerStats.getAdjRibOutRouteCounters().init(key));
389             this.adjRibOutListenerSet.put(key, adjRibOut);
390             registerPrefixesSentCounter(key, adjRibOut);
391         }
392     }
393
394     private ListenableFuture<Void> cleanup() {
395         // FIXME: BUG-196: support graceful
396         this.adjRibOutListenerSet.values().forEach(AdjRibOutListener::close);
397         this.adjRibOutListenerSet.clear();
398         if (this.effRibInWriter != null) {
399             this.effRibInWriter.close();
400         }
401         this.tables.clear();
402         if (this.ribWriter != null) {
403             return this.ribWriter.removePeer();
404         }
405         return Futures.immediateFuture(null);
406     }
407
408     @Override
409     public void onSessionDown(final BGPSession session, final Exception e) {
410         if(e.getMessage().equals(BGPSessionImpl.END_OF_INPUT)) {
411             LOG.info("Session with peer {} went down", this.name);
412         } else {
413             LOG.info("Session with peer {} went down", this.name, e);
414         }
415         releaseConnection();
416     }
417
418     @Override
419     public void onSessionTerminated(final BGPSession session, final BGPTerminationReason cause) {
420         LOG.info("Session with peer {} terminated: {}", this.name, cause);
421         releaseConnection();
422     }
423
424     @Override
425     public String toString() {
426         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
427     }
428
429     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
430         toStringHelper.add("name", this.name);
431         toStringHelper.add("tables", this.tables);
432         return toStringHelper;
433     }
434
435     @Override
436     public String getName() {
437         return this.name;
438     }
439
440     @Override
441     public synchronized ListenableFuture<Void> releaseConnection() {
442         if (this.rpcRegistration != null) {
443             this.rpcRegistration.close();
444         }
445         closeRegistration();
446         final ListenableFuture<Void> future = cleanup();
447         dropConnection();
448         resetState();
449         return future;
450     }
451
452     private void closeRegistration() {
453         for (final AbstractRegistration tableCloseable : this.tableRegistration) {
454             tableCloseable.close();
455         }
456         this.tableRegistration.clear();
457     }
458
459     private void dropConnection() {
460         if (this.runtimeReg != null) {
461             this.runtimeReg.close();
462             this.runtimeReg = null;
463         }
464         if (this.session != null) {
465             try {
466                 this.session.close();
467             } catch (final Exception e) {
468                 LOG.warn("Error closing session with peer", e);
469             }
470             this.session = null;
471
472             this.rib.getRenderStats().getConnectedPeerCounter().decrement();
473         }
474     }
475
476     @Override
477     public synchronized byte[] getRawIdentifier() {
478         return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
479     }
480
481     @Override
482     public void resetSession() {
483         releaseConnection();
484     }
485
486     @Override
487     public void resetStats() {
488         if (this.session instanceof BGPSessionStats) {
489             ((BGPSessionStats) this.session).resetBgpSessionStats();
490         }
491     }
492
493     @Override
494     public BgpSessionState getBgpSessionState() {
495         if (this.session instanceof BGPSessionStats) {
496             return ((BGPSessionStats) this.session).getBgpSessionState();
497         }
498         return new BgpSessionState();
499     }
500
501     @Override
502     public synchronized BgpPeerState getBgpPeerState() {
503         return this.peerStats.getBgpPeerState();
504     }
505
506     @Override
507     public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
508         LOG.error("Transaction chain failed.", cause);
509         this.chain.close();
510         this.chain = this.rib.createPeerChain(this);
511         this.ribWriter = AdjRibInWriter.create(this.rib.getYangRibId(), this.peerRole, this.simpleRoutingPolicy, this.chain);
512         releaseConnection();
513     }
514
515     @Override
516     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
517         LOG.debug("Transaction chain {} successfull.", chain);
518     }
519
520     @Override
521     public void markUptodate(final TablesKey tablesKey) {
522         this.ribWriter.markTableUptodate(tablesKey);
523     }
524
525     private static Map<TablesKey, SendReceive> mapTableTypesFamilies(final List<AddressFamilies> addPathTablesType) {
526         return ImmutableMap.copyOf(addPathTablesType.stream().collect(Collectors.toMap(af -> new TablesKey(af.getAfi(), af.getSafi()),
527             BgpAddPathTableType::getSendReceive)));
528     }
529
530     @Override
531     public BGPErrorHandlingState getBGPErrorHandlingState() {
532         return this;
533     }
534
535     @Override
536     public BGPAfiSafiState getBGPAfiSafiState() {
537         return this;
538     }
539
540     @Override
541     public BGPSessionState getBGPSessionState() {
542         if (this.session instanceof BGPSessionStateProvider) {
543             return ((BGPSessionStateProvider) this.session).getBGPSessionState();
544         }
545         return null;
546     }
547
548     @Override
549     public BGPTimersState getBGPTimersState() {
550         if (this.session instanceof BGPSessionStateProvider) {
551             return ((BGPSessionStateProvider) this.session).getBGPTimersState();
552         }
553         return null;
554     }
555
556     @Override
557     public BGPTransportState getBGPTransportState() {
558         if (this.session instanceof BGPSessionStateProvider) {
559             return ((BGPSessionStateProvider) this.session).getBGPTransportState();
560         }
561         return null;
562     }
563 }