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         this.chain = rib.createPeerChain(this);
134     }
135
136     public BGPPeer(final String name, final RIB rib, final PeerRole role, final RpcProviderRegistry rpcRegistry) {
137         this(name, rib, role, null, rpcRegistry);
138     }
139
140     public void instantiateServiceInstance() {
141         // add current peer to "configured BGP peer" stats
142         this.rib.getRenderStats().getConfiguredPeerCounter().increaseCount();
143         this.ribWriter = AdjRibInWriter.create(rib.getYangRibId(), this.peerRole, this.simpleRoutingPolicy, this.chain);
144     }
145
146     @Override
147     public synchronized void close() {
148         releaseConnection();
149         this.chain.close();
150     }
151
152     @Override
153     public void onMessage(final BGPSession session, final Notification msg) throws BGPDocumentedException {
154         if (!(msg instanceof Update) && !(msg instanceof RouteRefresh)) {
155             LOG.info("Ignoring unhandled message class {}", msg.getClass());
156             return;
157         }
158         if (msg instanceof Update) {
159             onUpdateMessage((Update) msg);
160         } else {
161             onRouteRefreshMessage((RouteRefresh) msg, session);
162         }
163     }
164
165     private void onRouteRefreshMessage(final RouteRefresh message, final BGPSession session) {
166         final Class<? extends AddressFamily> rrAfi = message.getAfi();
167         final Class<? extends SubsequentAddressFamily> rrSafi = message.getSafi();
168
169         final TablesKey key = new TablesKey(rrAfi, rrSafi);
170         final AdjRibOutListener listener = this.adjRibOutListenerSet.get(key);
171         if (listener != null) {
172             listener.close();
173             this.adjRibOutListenerSet.remove(key);
174             createAdjRibOutListener(RouterIds.createPeerId(session.getBgpId()), key, listener.isMpSupported());
175         } else {
176             LOG.info("Ignoring RouteRefresh message. Afi/Safi is not supported: {}, {}.", rrAfi, rrSafi);
177         }
178     }
179
180     /**
181      * Check for presence of well known mandatory attribute LOCAL_PREF in Update message
182      *
183      * @param message Update message
184      * @throws BGPDocumentedException
185      */
186     private void checkMandatoryAttributesPresence(final Update message) throws BGPDocumentedException {
187         if (MessageUtil.isAnyNlriPresent(message)) {
188             final Attributes attrs = message.getAttributes();
189             if (this.peerRole == PeerRole.Ibgp && (attrs == null || attrs.getLocalPref() == null)) {
190                 throw new BGPDocumentedException(BGPError.MANDATORY_ATTR_MISSING_MSG + "LOCAL_PREF",
191                         BGPError.WELL_KNOWN_ATTR_MISSING,
192                         new byte[] { LocalPreferenceAttributeParser.TYPE });
193             }
194         }
195     }
196
197     /**
198      * Process Update message received.
199      * Calls {@link #checkMandatoryAttributesPresence(Update)} to check for presence of mandatory attributes.
200      *
201      * @param message Update message
202      * @throws BGPDocumentedException
203      */
204     private void onUpdateMessage(final Update message) throws BGPDocumentedException {
205         checkMandatoryAttributesPresence(message);
206
207         // update AdjRibs
208         final Attributes attrs = message.getAttributes();
209         MpReachNlri mpReach = null;
210         final boolean isAnyNlriAnnounced = message.getNlri() != null;
211         if (isAnyNlriAnnounced) {
212             mpReach = prefixesToMpReach(message);
213         } else {
214             mpReach = MessageUtil.getMpReachNlri(attrs);
215         }
216         if (mpReach != null) {
217             this.ribWriter.updateRoutes(mpReach, nextHopToAttribute(attrs, mpReach));
218         }
219         MpUnreachNlri mpUnreach = null;
220         if (message.getWithdrawnRoutes() != null) {
221             mpUnreach = prefixesToMpUnreach(message, isAnyNlriAnnounced);
222         } else {
223             mpUnreach = MessageUtil.getMpUnreachNlri(attrs);
224         }
225         if (mpUnreach != null) {
226             this.ribWriter.removeRoutes(mpUnreach);
227         }
228     }
229
230     private static Attributes nextHopToAttribute(final Attributes attrs, final MpReachNlri mpReach) {
231         if (attrs.getCNextHop() == null && mpReach.getCNextHop() != null) {
232             final AttributesBuilder attributesBuilder = new AttributesBuilder(attrs);
233             attributesBuilder.setCNextHop(mpReach.getCNextHop());
234             return attributesBuilder.build();
235         }
236         return attrs;
237     }
238
239     /**
240      * Creates MPReach for the prefixes to be handled in the same way as linkstate routes
241      *
242      * @param message Update message containing prefixes in NLRI
243      * @return MpReachNlri with prefixes from the nlri field
244      */
245     private static MpReachNlri prefixesToMpReach(final Update message) {
246         final List<Ipv4Prefixes> prefixes = new ArrayList<>();
247         for (final Ipv4Prefix p : message.getNlri().getNlri()) {
248             prefixes.add(new Ipv4PrefixesBuilder().setPrefix(p).build());
249         }
250         final MpReachNlriBuilder b = new MpReachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi(
251                 UnicastSubsequentAddressFamily.class).setAdvertizedRoutes(
252                         new AdvertizedRoutesBuilder().setDestinationType(
253                                 new DestinationIpv4CaseBuilder().setDestinationIpv4(
254                                         new DestinationIpv4Builder().setIpv4Prefixes(prefixes).build()).build()).build());
255         if (message.getAttributes() != null) {
256             b.setCNextHop(message.getAttributes().getCNextHop());
257         }
258         return b.build();
259     }
260
261     /**
262      * Create MPUnreach for the prefixes to be handled in the same way as linkstate routes
263      *
264      * @param message Update message containing withdrawn routes
265      * @param isAnyNlriAnnounced
266      * @return MpUnreachNlri with prefixes from the withdrawn routes field
267      */
268     private static MpUnreachNlri prefixesToMpUnreach(final Update message, final boolean isAnyNlriAnnounced) {
269         final List<Ipv4Prefixes> prefixes = new ArrayList<>();
270         for (final Ipv4Prefix p : message.getWithdrawnRoutes().getWithdrawnRoutes()) {
271             boolean nlriAnounced = false;
272             if(isAnyNlriAnnounced) {
273                 nlriAnounced = message.getNlri().getNlri().contains(p);
274             }
275
276             if(!nlriAnounced) {
277                 prefixes.add(new Ipv4PrefixesBuilder().setPrefix(p).build());
278             }
279         }
280         return new MpUnreachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi(UnicastSubsequentAddressFamily.class).setWithdrawnRoutes(
281                 new WithdrawnRoutesBuilder().setDestinationType(
282                         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(
283                                 new DestinationIpv4Builder().setIpv4Prefixes(prefixes).build()).build()).build()).build();
284     }
285
286     @Override
287     public synchronized void onSessionUp(final BGPSession session) {
288         final List<AddressFamilies> addPathTablesType = session.getAdvertisedAddPathTableTypes();
289         final Set<BgpTableType> advertizedTableTypes = session.getAdvertisedTableTypes();
290         LOG.info("Session with peer {} went up with tables {} and Add Path tables {}", this.name, advertizedTableTypes, addPathTablesType);
291         this.session = session;
292
293         this.rawIdentifier = InetAddresses.forString(session.getBgpId().getValue()).getAddress();
294         final PeerId peerId = RouterIds.createPeerId(session.getBgpId());
295
296         this.tables.addAll(advertizedTableTypes.stream().map(t -> new TablesKey(t.getAfi(), t.getSafi())).collect(Collectors.toList()));
297         final boolean announceNone = isAnnounceNone(this.simpleRoutingPolicy);
298         final Map<TablesKey, SendReceive> addPathTableMaps = mapTableTypesFamilies(addPathTablesType);
299         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)
300             .node(IdentifierUtils.domPeerId(peerId));
301
302         if(!announceNone) {
303             createAdjRibOutListener(peerId);
304         }
305         this.tables.forEach(tablesKey -> {
306             final ExportPolicyPeerTracker exportTracker = this.rib.getExportPolicyPeerTracker(tablesKey);
307             if (exportTracker != null) {
308                 this.tableRegistration.add(exportTracker.registerPeer(peerId, addPathTableMaps.get(tablesKey), this.peerIId, this.peerRole,
309                     this.simpleRoutingPolicy));
310             }
311         });
312         addBgp4Support(peerId, announceNone);
313
314         if(!isLearnNone(this.simpleRoutingPolicy)) {
315             this.effRibInWriter = EffectiveRibInWriter.create(this.rib.getService(), this.rib.createPeerChain(this), this.peerIId,
316                 this.rib.getImportPolicyPeerTracker(), this.rib.getRibSupportContext(), this.peerRole,
317                 this.peerStats.getEffectiveRibInRouteCounters(), this.peerStats.getAdjRibInRouteCounters());
318         }
319         this.ribWriter = this.ribWriter.transform(peerId, this.rib.getRibSupportContext(), this.tables, addPathTableMaps);
320
321         // register BGP Peer stats
322         this.peerStats.getSessionEstablishedCounter().increaseCount();
323         if (this.registrator != null) {
324             this.runtimeReg = this.registrator.register(this);
325         }
326
327         if (this.rpcRegistry != null) {
328             this.rpcRegistration = this.rpcRegistry.addRoutedRpcImplementation(BgpPeerRpcService.class, new BgpPeerRpc(session, this.tables));
329             final KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer, PeerKey> path =
330                     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));
331             this.rpcRegistration.registerPath(PeerContext.class, path);
332         }
333
334         this.rib.getRenderStats().getConnectedPeerCounter().increaseCount();
335     }
336
337     private void createAdjRibOutListener(final PeerId peerId) {
338         this.tables.forEach(key->createAdjRibOutListener(peerId, key, true));
339     }
340
341     //try to add a support for old-school BGP-4, if peer did not advertise IPv4-Unicast MP capability
342     private void addBgp4Support(final PeerId peerId, final boolean announceNone) {
343         final TablesKey key = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
344         if (this.tables.add(key) && !announceNone) {
345             createAdjRibOutListener(peerId, key, false);
346         }
347     }
348
349     private void createAdjRibOutListener(final PeerId peerId, final TablesKey key, final boolean mpSupport) {
350         final RIBSupportContext context = this.rib.getRibSupportContext().getRIBSupportContext(key);
351
352         // not particularly nice
353         if (context != null && this.session instanceof BGPSessionImpl) {
354             this.adjRibOutListenerSet.put(key, AdjRibOutListener.create(peerId, key, this.rib.getYangRibId(), this.rib.getCodecsRegistry(),
355                 context.getRibSupport(), this.rib.getService(), ((BGPSessionImpl) this.session).getLimiter(), mpSupport,
356                 this.peerStats.getAdjRibOutRouteCounters().init(key)));
357         }
358     }
359
360     private void cleanup() {
361         // FIXME: BUG-196: support graceful
362         this.adjRibOutListenerSet.values().forEach(AdjRibOutListener::close);
363         this.adjRibOutListenerSet.clear();
364         if (this.effRibInWriter != null) {
365             this.effRibInWriter.close();
366         }
367         if(this.ribWriter != null) {
368             this.ribWriter.removePeer();
369         }
370         this.tables.clear();
371     }
372
373     @Override
374     public void onSessionDown(final BGPSession session, final Exception e) {
375         if(e.getMessage().equals(BGPSessionImpl.END_OF_INPUT)) {
376             LOG.info("Session with peer {} went down", this.name);
377         } else {
378             LOG.info("Session with peer {} went down", this.name, e);
379         }
380         releaseConnection();
381     }
382
383     @Override
384     public void onSessionTerminated(final BGPSession session, final BGPTerminationReason cause) {
385         LOG.info("Session with peer {} terminated: {}", this.name, cause);
386         releaseConnection();
387     }
388
389     @Override
390     public String toString() {
391         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
392     }
393
394     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
395         toStringHelper.add("name", this.name);
396         toStringHelper.add("tables", this.tables);
397         return toStringHelper;
398     }
399
400     @Override
401     public String getName() {
402         return this.name;
403     }
404
405     @Override
406     @GuardedBy("this")
407     public synchronized void releaseConnection() {
408         if (this.rpcRegistration != null) {
409             this.rpcRegistration.close();
410         }
411         closeRegistration();
412         cleanup();
413         dropConnection();
414     }
415
416     private void closeRegistration() {
417         for (final AbstractRegistration tableCloseable : this.tableRegistration) {
418             tableCloseable.close();
419         }
420         this.tableRegistration.clear();
421     }
422
423     private void dropConnection() {
424         if (this.runtimeReg != null) {
425             this.runtimeReg.close();
426             this.runtimeReg = null;
427         }
428         if (this.session != null) {
429             try {
430                 this.session.close();
431             } catch (final Exception e) {
432                 LOG.warn("Error closing session with peer", e);
433             }
434             this.session = null;
435
436             this.rib.getRenderStats().getConnectedPeerCounter().decreaseCount();
437         }
438     }
439
440     @Override
441     public synchronized byte[] getRawIdentifier() {
442         return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
443     }
444
445     @Override
446     public void resetSession() {
447         releaseConnection();
448     }
449
450     @Override
451     public void resetStats() {
452         if (this.session instanceof BGPSessionStats) {
453             ((BGPSessionStats) this.session).resetBgpSessionStats();
454         }
455     }
456
457     @Override
458     public BgpSessionState getBgpSessionState() {
459         if (this.session instanceof BGPSessionStats) {
460             return ((BGPSessionStats) this.session).getBgpSessionState();
461         }
462         return new BgpSessionState();
463     }
464
465     @Override
466     public synchronized BgpPeerState getBgpPeerState() {
467         return this.peerStats.getBgpPeerState();
468     }
469
470     @Override
471     public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
472         LOG.error("Transaction chain failed.", cause);
473         this.chain.close();
474         this.chain = this.rib.createPeerChain(this);
475         this.ribWriter = AdjRibInWriter.create(this.rib.getYangRibId(), this.peerRole, this.simpleRoutingPolicy, this.chain);
476         releaseConnection();
477     }
478
479     @Override
480     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
481         LOG.debug("Transaction chain {} successfull.", chain);
482     }
483
484     @Override
485     public void markUptodate(final TablesKey tablesKey) {
486         this.ribWriter.markTableUptodate(tablesKey);
487     }
488
489     private static Map<TablesKey, SendReceive> mapTableTypesFamilies(final List<AddressFamilies> addPathTablesType) {
490         return ImmutableMap.copyOf(addPathTablesType.stream().collect(Collectors.toMap(af -> new TablesKey(af.getAfi(), af.getSafi()),
491             BgpAddPathTableType::getSendReceive)));
492     }
493 }