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