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