Replace Preconditions.CheckNotNull per RequireNonNull
[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.rev160322.BgpPeerRpcService;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.peer.rpc.rev160322.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, new BgpPeerRpc(session, this.tables));
359             final KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer, PeerKey> path =
360                     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));
361             this.rpcRegistration.registerPath(PeerContext.class, path);
362         }
363
364         this.rib.getRenderStats().getConnectedPeerCounter().increment();
365     }
366
367     private void createAdjRibOutListener(final PeerId peerId) {
368         this.tables.forEach(key->createAdjRibOutListener(peerId, key, true));
369     }
370
371     //try to add a support for old-school BGP-4, if peer did not advertise IPv4-Unicast MP capability
372     private void addBgp4Support(final PeerId peerId, final boolean announceNone) {
373         final TablesKey key = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
374         if (this.tables.add(key) && !announceNone) {
375             createAdjRibOutListener(peerId, key, false);
376         }
377     }
378
379     private void createAdjRibOutListener(final PeerId peerId, final TablesKey key, final boolean mpSupport) {
380         final RIBSupportContext context = this.rib.getRibSupportContext().getRIBSupportContext(key);
381
382         // not particularly nice
383         if (context != null && this.session instanceof BGPSessionImpl) {
384             final ChannelOutputLimiter limiter = ((BGPSessionImpl) this.session).getLimiter();
385             final AdjRibOutListener adjRibOut = AdjRibOutListener.create(peerId, key,
386                 this.rib.getYangRibId(), this.rib.getCodecsRegistry(), context.getRibSupport(),
387                 this.rib.getService(), limiter, mpSupport, this.peerStats.getAdjRibOutRouteCounters().init(key));
388             this.adjRibOutListenerSet.put(key, adjRibOut);
389             registerPrefixesSentCounter(key, adjRibOut);
390         }
391     }
392
393     private ListenableFuture<Void> cleanup() {
394         // FIXME: BUG-196: support graceful
395         this.adjRibOutListenerSet.values().forEach(AdjRibOutListener::close);
396         this.adjRibOutListenerSet.clear();
397         if (this.effRibInWriter != null) {
398             this.effRibInWriter.close();
399         }
400         this.tables.clear();
401         if (this.ribWriter != null) {
402             return this.ribWriter.removePeer();
403         }
404         return Futures.immediateFuture(null);
405     }
406
407     @Override
408     public void onSessionDown(final BGPSession session, final Exception e) {
409         if(e.getMessage().equals(BGPSessionImpl.END_OF_INPUT)) {
410             LOG.info("Session with peer {} went down", this.name);
411         } else {
412             LOG.info("Session with peer {} went down", this.name, e);
413         }
414         releaseConnection();
415     }
416
417     @Override
418     public void onSessionTerminated(final BGPSession session, final BGPTerminationReason cause) {
419         LOG.info("Session with peer {} terminated: {}", this.name, cause);
420         releaseConnection();
421     }
422
423     @Override
424     public String toString() {
425         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
426     }
427
428     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
429         toStringHelper.add("name", this.name);
430         toStringHelper.add("tables", this.tables);
431         return toStringHelper;
432     }
433
434     @Override
435     public String getName() {
436         return this.name;
437     }
438
439     @Override
440     public synchronized ListenableFuture<Void> releaseConnection() {
441         if (this.rpcRegistration != null) {
442             this.rpcRegistration.close();
443         }
444         closeRegistration();
445         final ListenableFuture<Void> future = cleanup();
446         dropConnection();
447         resetState();
448         return future;
449     }
450
451     private void closeRegistration() {
452         for (final AbstractRegistration tableCloseable : this.tableRegistration) {
453             tableCloseable.close();
454         }
455         this.tableRegistration.clear();
456     }
457
458     private void dropConnection() {
459         if (this.runtimeReg != null) {
460             this.runtimeReg.close();
461             this.runtimeReg = null;
462         }
463         if (this.session != null) {
464             try {
465                 this.session.close();
466             } catch (final Exception e) {
467                 LOG.warn("Error closing session with peer", e);
468             }
469             this.session = null;
470
471             this.rib.getRenderStats().getConnectedPeerCounter().decrement();
472         }
473     }
474
475     @Override
476     public synchronized byte[] getRawIdentifier() {
477         return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
478     }
479
480     @Override
481     public void resetSession() {
482         releaseConnection();
483     }
484
485     @Override
486     public void resetStats() {
487         if (this.session instanceof BGPSessionStats) {
488             ((BGPSessionStats) this.session).resetBgpSessionStats();
489         }
490     }
491
492     @Override
493     public BgpSessionState getBgpSessionState() {
494         if (this.session instanceof BGPSessionStats) {
495             return ((BGPSessionStats) this.session).getBgpSessionState();
496         }
497         return new BgpSessionState();
498     }
499
500     @Override
501     public synchronized BgpPeerState getBgpPeerState() {
502         return this.peerStats.getBgpPeerState();
503     }
504
505     @Override
506     public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
507         LOG.error("Transaction chain failed.", cause);
508         this.chain.close();
509         this.chain = this.rib.createPeerChain(this);
510         this.ribWriter = AdjRibInWriter.create(this.rib.getYangRibId(), this.peerRole, this.simpleRoutingPolicy, this.chain);
511         releaseConnection();
512     }
513
514     @Override
515     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
516         LOG.debug("Transaction chain {} successfull.", chain);
517     }
518
519     @Override
520     public void markUptodate(final TablesKey tablesKey) {
521         this.ribWriter.markTableUptodate(tablesKey);
522     }
523
524     private static Map<TablesKey, SendReceive> mapTableTypesFamilies(final List<AddressFamilies> addPathTablesType) {
525         return ImmutableMap.copyOf(addPathTablesType.stream().collect(Collectors.toMap(af -> new TablesKey(af.getAfi(), af.getSafi()),
526             BgpAddPathTableType::getSendReceive)));
527     }
528
529     @Override
530     public BGPErrorHandlingState getBGPErrorHandlingState() {
531         return this;
532     }
533
534     @Override
535     public BGPAfiSafiState getBGPAfiSafiState() {
536         return this;
537     }
538
539     @Override
540     public BGPSessionState getBGPSessionState() {
541         if (this.session instanceof BGPSessionStateProvider) {
542             return ((BGPSessionStateProvider) this.session).getBGPSessionState();
543         }
544         return null;
545     }
546
547     @Override
548     public BGPTimersState getBGPTimersState() {
549         if (this.session instanceof BGPSessionStateProvider) {
550             return ((BGPSessionStateProvider) this.session).getBGPTimersState();
551         }
552         return null;
553     }
554
555     @Override
556     public BGPTransportState getBGPTransportState() {
557         if (this.session instanceof BGPSessionStateProvider) {
558             return ((BGPSessionStateProvider) this.session).getBGPTransportState();
559         }
560         return null;
561     }
562 }