Fix more rib-impl checkstyle
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / BGPSessionImpl.java
1 /*
2  * Copyright (c) 2013 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
12 import com.google.common.annotations.VisibleForTesting;
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.ImmutableSet;
17 import io.netty.buffer.ByteBufUtil;
18 import io.netty.channel.Channel;
19 import io.netty.channel.ChannelFuture;
20 import io.netty.channel.ChannelFutureListener;
21 import io.netty.channel.ChannelHandlerContext;
22 import io.netty.channel.SimpleChannelInboundHandler;
23 import java.io.IOException;
24 import java.nio.channels.NonWritableChannelException;
25 import java.util.ArrayList;
26 import java.util.Date;
27 import java.util.HashSet;
28 import java.util.List;
29 import java.util.Optional;
30 import java.util.Set;
31 import java.util.concurrent.TimeUnit;
32 import java.util.function.Function;
33 import javax.annotation.concurrent.GuardedBy;
34 import org.opendaylight.protocol.bgp.parser.AsNumberUtil;
35 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
36 import org.opendaylight.protocol.bgp.parser.BGPError;
37 import org.opendaylight.protocol.bgp.parser.BgpExtendedMessageUtil;
38 import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
39 import org.opendaylight.protocol.bgp.parser.GracefulRestartUtil;
40 import org.opendaylight.protocol.bgp.parser.spi.MultiPathSupport;
41 import org.opendaylight.protocol.bgp.parser.spi.PeerConstraint;
42 import org.opendaylight.protocol.bgp.parser.spi.pojo.MultiPathSupportImpl;
43 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPMessagesListener;
44 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
45 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
46 import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateImpl;
47 import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateProvider;
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.State;
52 import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState;
53 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState;
54 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState;
55 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Keepalive;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.KeepaliveBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Notify;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.NotifyBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Open;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Update;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.open.message.BgpParameters;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.open.message.bgp.parameters.OptionalCapabilities;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.open.message.bgp.parameters.optional.capabilities.CParameters;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.BgpTableType;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.CParameters1;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.MpCapabilities;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.RouteRefresh;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.AddPathCapability;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.GracefulRestartCapability;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.LlGracefulRestartCapability;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.MultiprotocolCapability;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.add.path.capability.AddressFamilies;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
76 import org.opendaylight.yangtools.yang.binding.ChildOf;
77 import org.opendaylight.yangtools.yang.binding.Notification;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
80
81 @VisibleForTesting
82 public class BGPSessionImpl extends SimpleChannelInboundHandler<Notification> implements BGPSession,
83         BGPSessionStateProvider, AutoCloseable {
84
85     private static final Logger LOG = LoggerFactory.getLogger(BGPSessionImpl.class);
86
87     private static final Notification KEEP_ALIVE = new KeepaliveBuilder().build();
88
89     private static final int KA_TO_DEADTIMER_RATIO = 3;
90
91     private static final String EXTENDED_MSG_DECODER = "EXTENDED_MSG_DECODER";
92
93     static final String END_OF_INPUT = "End of input detected. Close the session.";
94
95     /**
96      * System.nanoTime value about when was sent the last message.
97      */
98     @VisibleForTesting
99     private long lastMessageSentAt;
100
101     /**
102      * System.nanoTime value about when was received the last message.
103      */
104     private long lastMessageReceivedAt;
105
106     private final BGPSessionListener listener;
107
108     private final BGPSynchronization sync;
109
110     private int kaCounter = 0;
111
112     private final Channel channel;
113
114     @GuardedBy("this")
115     private State state = State.OPEN_CONFIRM;
116
117     private final Set<BgpTableType> tableTypes;
118     private final List<AddressFamilies> addPathTypes;
119     private final int holdTimerValue;
120     private final int keepAlive;
121     private final AsNumber asNumber;
122     private final Ipv4Address bgpId;
123     private final BGPPeerRegistry peerRegistry;
124     private final ChannelOutputLimiter limiter;
125     private final BGPSessionStateImpl sessionState;
126     private final GracefulRestartCapability gracefulCapability;
127     private final LlGracefulRestartCapability llGracefulCapability;
128     private boolean terminationReasonNotified;
129
130     public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen,
131             final BGPSessionPreferences localPreferences, final BGPPeerRegistry peerRegistry) {
132         this(listener, channel, remoteOpen, localPreferences.getHoldTime(), peerRegistry);
133     }
134
135     public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen,
136             final int localHoldTimer, final BGPPeerRegistry peerRegistry) {
137         this.listener = requireNonNull(listener);
138         this.channel = requireNonNull(channel);
139         this.limiter = new ChannelOutputLimiter(this);
140         this.channel.pipeline().addLast(this.limiter);
141         this.holdTimerValue = remoteOpen.getHoldTimer() < localHoldTimer ? remoteOpen.getHoldTimer() : localHoldTimer;
142         LOG.info("BGP HoldTimer new value: {}", this.holdTimerValue);
143         this.keepAlive = this.holdTimerValue / KA_TO_DEADTIMER_RATIO;
144         this.asNumber = AsNumberUtil.advertizedAsNumber(remoteOpen);
145         this.peerRegistry = peerRegistry;
146         this.sessionState = new BGPSessionStateImpl();
147
148         final Set<TablesKey> tts = new HashSet<>();
149         final Set<BgpTableType> tats = new HashSet<>();
150         final List<AddressFamilies> addPathCapabilitiesList = new ArrayList<>();
151         final List<BgpParameters> bgpParameters = remoteOpen.getBgpParameters();
152         if (bgpParameters != null) {
153             for (final BgpParameters param : bgpParameters) {
154                 for (final OptionalCapabilities optCapa : param.getOptionalCapabilities()) {
155                     final CParameters cParam = optCapa.getCParameters();
156                     final CParameters1 cParam1 = cParam.augmentation(CParameters1.class);
157                     if (cParam1 != null) {
158                         final MultiprotocolCapability multi = cParam1.getMultiprotocolCapability();
159                         if (multi != null) {
160                             final TablesKey tt = new TablesKey(multi.getAfi(), multi.getSafi());
161                             LOG.trace("Added table type to sync {}", tt);
162                             tts.add(tt);
163                             tats.add(new BgpTableTypeImpl(tt.getAfi(), tt.getSafi()));
164                         } else {
165                             final AddPathCapability addPathCap = cParam1.getAddPathCapability();
166                             if (addPathCap != null) {
167                                 addPathCapabilitiesList.addAll(addPathCap.getAddressFamilies());
168                             }
169                         }
170                     }
171                 }
172             }
173             this.gracefulCapability = findSingleCapability(bgpParameters, "Graceful Restart",
174                 CParameters1::getGracefulRestartCapability).orElse(GracefulRestartUtil.EMPTY_GR_CAPABILITY);
175             this.llGracefulCapability = findSingleCapability(bgpParameters, "Long-lived Graceful Restart",
176                 CParameters1::getLlGracefulRestartCapability).orElse(GracefulRestartUtil.EMPTY_LLGR_CAPABILITY);
177         } else {
178             this.gracefulCapability = GracefulRestartUtil.EMPTY_GR_CAPABILITY;
179             this.llGracefulCapability = GracefulRestartUtil.EMPTY_LLGR_CAPABILITY;
180         }
181
182         this.sync = new BGPSynchronization(this.listener, tts);
183         this.tableTypes = tats;
184         this.addPathTypes = addPathCapabilitiesList;
185
186         if (!this.addPathTypes.isEmpty()) {
187             addDecoderConstraint(MultiPathSupport.class,
188                 MultiPathSupportImpl.createParserMultiPathSupport(this.addPathTypes));
189         }
190
191         if (this.holdTimerValue != 0) {
192             channel.eventLoop().schedule(this::handleHoldTimer, this.holdTimerValue, TimeUnit.SECONDS);
193             channel.eventLoop().schedule(this::handleKeepaliveTimer, this.keepAlive, TimeUnit.SECONDS);
194         }
195         this.bgpId = remoteOpen.getBgpIdentifier();
196         this.sessionState.advertizeCapabilities(this.holdTimerValue, channel.remoteAddress(), channel.localAddress(),
197                 this.tableTypes, bgpParameters);
198     }
199
200     private static <T extends ChildOf<MpCapabilities>> Optional<T> findSingleCapability(
201             final List<BgpParameters> bgpParameters, final String name, final Function<CParameters1, T> extractor) {
202         final List<T> found = new ArrayList<>(1);
203         for (BgpParameters bgpParams : bgpParameters) {
204             for (OptionalCapabilities optCapability : bgpParams.nonnullOptionalCapabilities()) {
205                 final CParameters cparam = optCapability.getCParameters();
206                 if (cparam != null) {
207                     final CParameters1 augment = cparam.augmentation(CParameters1.class);
208                     if (augment != null) {
209                         final T capa = extractor.apply(augment);
210                         if (capa != null) {
211                             found.add(capa);
212                         }
213                     }
214                 }
215             }
216         }
217
218         final Set<T> set = ImmutableSet.copyOf(found);
219         switch (set.size()) {
220             case 0:
221                 LOG.debug("{} capability not advertised.", name);
222                 return Optional.empty();
223             case 1:
224                 return Optional.of(found.get(0));
225             default:
226                 LOG.warn("Multiple instances of {} capability advertised: {}, ignoring.", name, set);
227                 return Optional.empty();
228         }
229     }
230
231     /**
232      * Set the extend message coder for current channel.
233      * The reason for separating this part from constructor is, in #channel.pipeline().replace(..), the
234      * invokeChannelRead() will be invoked after the original message coder handler got removed. And there
235      * is chance that before the session instance is fully initiated (constructor returns), a KeepAlive
236      * message arrived already in the channel buffer. Thus #AbstractBGPSessionNegotiator.handleMessage(..)
237      * gets invoked again and a deadlock is caused.  A BGP final state machine error will happen as BGP
238      * negotiator is still in OPEN_SENT state as the session constructor hasn't returned yet.
239      */
240     public synchronized void setChannelExtMsgCoder(final Open remoteOpen) {
241         final boolean enableExMess = BgpExtendedMessageUtil.advertizedBgpExtendedMessageCapability(remoteOpen);
242         if (enableExMess) {
243             this.channel.pipeline().replace(BGPMessageHeaderDecoder.class, EXTENDED_MSG_DECODER,
244                     BGPMessageHeaderDecoder.getExtendedBGPMessageHeaderDecoder());
245         }
246     }
247
248     @Override
249     public synchronized void close() {
250         if (this.state != State.IDLE) {
251             if (!this.terminationReasonNotified) {
252                 this.writeAndFlush(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode())
253                         .setErrorSubcode(BGPError.CEASE.getSubcode()).build());
254             }
255             this.closeWithoutMessage();
256         }
257     }
258
259     /**
260      * Handles incoming message based on their type.
261      *
262      * @param msg incoming message
263      */
264     synchronized void handleMessage(final Notification msg) {
265         if (this.state == State.IDLE) {
266             return;
267         }
268         try {
269             // Update last reception time
270             this.lastMessageReceivedAt = System.nanoTime();
271
272             if (msg instanceof Open) {
273                 // Open messages should not be present here
274                 this.terminate(new BGPDocumentedException(null, BGPError.FSM_ERROR));
275             } else if (msg instanceof Notify) {
276                 final Notify notify = (Notify) msg;
277                 // Notifications are handled internally
278                 LOG.info("Session closed because Notification message received: {} / {}, data={}",
279                         notify.getErrorCode(),
280                         notify.getErrorSubcode(),
281                         notify.getData() != null ? ByteBufUtil.hexDump(notify.getData()) : null);
282                 notifyTerminationReasonAndCloseWithoutMessage(notify.getErrorCode(), notify.getErrorSubcode());
283             } else if (msg instanceof Keepalive) {
284                 // Keepalives are handled internally
285                 LOG.trace("Received KeepAlive message.");
286                 this.kaCounter++;
287                 if (this.kaCounter >= 2) {
288                     this.sync.kaReceived();
289                 }
290             } else if (msg instanceof RouteRefresh) {
291                 this.listener.onMessage(this, msg);
292             } else if (msg instanceof Update) {
293                 this.listener.onMessage(this, msg);
294                 this.sync.updReceived((Update) msg);
295             } else {
296                 LOG.warn("Ignoring unhandled message: {}.", msg.getClass());
297             }
298
299             this.sessionState.messageReceived(msg);
300         } catch (final BGPDocumentedException e) {
301             this.terminate(e);
302         }
303     }
304
305     private synchronized void notifyTerminationReasonAndCloseWithoutMessage(
306             final Short errorCode,
307             final Short errorSubcode) {
308         this.terminationReasonNotified = true;
309         this.closeWithoutMessage();
310         this.listener.onSessionTerminated(this, new BGPTerminationReason(
311                 BGPError.forValue(errorCode, errorSubcode)));
312     }
313
314     synchronized void endOfInput() {
315         if (this.state == State.UP) {
316             LOG.info(END_OF_INPUT);
317             this.listener.onSessionDown(this, new IOException(END_OF_INPUT));
318         }
319     }
320
321     @GuardedBy("this")
322     private ChannelFuture writeEpilogue(final ChannelFuture future, final Notification msg) {
323         future.addListener((ChannelFutureListener) f -> {
324             if (!f.isSuccess()) {
325                 LOG.warn("Failed to send message {} to socket {}", msg, BGPSessionImpl.this.channel, f.cause());
326             } else {
327                 LOG.trace("Message {} sent to socket {}", msg, BGPSessionImpl.this.channel);
328             }
329         });
330         this.lastMessageSentAt = System.nanoTime();
331         this.sessionState.messageSent(msg);
332         return future;
333     }
334
335     void flush() {
336         this.channel.flush();
337     }
338
339     synchronized void write(final Notification msg) {
340         try {
341             writeEpilogue(this.channel.write(msg), msg);
342         } catch (final Exception e) {
343             LOG.warn("Message {} was not sent.", msg, e);
344         }
345     }
346
347     synchronized ChannelFuture writeAndFlush(final Notification msg) {
348         if (isWritable()) {
349             return writeEpilogue(this.channel.writeAndFlush(msg), msg);
350         }
351         return this.channel.newFailedFuture(new NonWritableChannelException());
352     }
353
354     @Override
355     public synchronized void closeWithoutMessage() {
356         if (this.state == State.IDLE) {
357             return;
358         }
359         LOG.info("Closing session: {}", this);
360         this.channel.close().addListener((ChannelFutureListener) future
361             -> Preconditions.checkArgument(future.isSuccess(), "Channel failed to close: %s", future.cause()));
362         this.state = State.IDLE;
363         removePeerSession();
364         this.sessionState.setSessionState(this.state);
365     }
366
367     /**
368      * Closes BGP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
369      * modified, because he initiated the closing. (To prevent concurrent modification exception).
370      *
371      * @param e BGPDocumentedException
372      */
373     @VisibleForTesting
374     synchronized void terminate(final BGPDocumentedException e) {
375         final BGPError error = e.getError();
376         final byte[] data = e.getData();
377         final NotifyBuilder builder = new NotifyBuilder().setErrorCode(error.getCode())
378                 .setErrorSubcode(error.getSubcode());
379         if (data != null && data.length != 0) {
380             builder.setData(data);
381         }
382         this.writeAndFlush(builder.build());
383         notifyTerminationReasonAndCloseWithoutMessage(error.getCode(), error.getSubcode());
384     }
385
386     private void removePeerSession() {
387         if (this.peerRegistry != null) {
388             this.peerRegistry.removePeerSession(StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress()));
389         }
390     }
391
392     /**
393      * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
394      * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
395      * which the message was received. If the session was closed by the time this method starts to execute (the session
396      * state will become IDLE), then rescheduling won't occur.
397      */
398     private synchronized void handleHoldTimer() {
399         if (this.state == State.IDLE) {
400             return;
401         }
402
403         final long ct = System.nanoTime();
404         final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(this.holdTimerValue);
405
406         if (ct >= nextHold) {
407             LOG.debug("HoldTimer expired. {}", new Date());
408             this.terminate(new BGPDocumentedException(BGPError.HOLD_TIMER_EXPIRED));
409         } else {
410             this.channel.eventLoop().schedule(this::handleHoldTimer, nextHold - ct, TimeUnit.NANOSECONDS);
411         }
412     }
413
414     /**
415      * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
416      * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
417      * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
418      * starts to execute (the session state will become IDLE), that rescheduling won't occur.
419      */
420     private synchronized void handleKeepaliveTimer() {
421         if (this.state == State.IDLE) {
422             return;
423         }
424
425         final long ct = System.nanoTime();
426         long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
427
428         if (ct >= nextKeepalive) {
429             this.writeAndFlush(KEEP_ALIVE);
430             nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
431         }
432         this.channel.eventLoop().schedule(this::handleKeepaliveTimer, nextKeepalive - ct, TimeUnit.NANOSECONDS);
433     }
434
435     @Override
436     public final String toString() {
437         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
438     }
439
440     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
441         toStringHelper.add("channel", this.channel);
442         toStringHelper.add("state", this.getState());
443         return toStringHelper;
444     }
445
446     @Override
447     public Set<BgpTableType> getAdvertisedTableTypes() {
448         return this.tableTypes;
449     }
450
451     @Override
452     public List<AddressFamilies> getAdvertisedAddPathTableTypes() {
453         return this.addPathTypes;
454     }
455
456     @Override
457     public GracefulRestartCapability getAdvertisedGracefulRestartCapability() {
458         return this.gracefulCapability;
459     }
460
461     @Override
462     public LlGracefulRestartCapability getAdvertisedLlGracefulRestartCapability() {
463         return this.llGracefulCapability;
464     }
465
466     @VisibleForTesting
467     synchronized void sessionUp() {
468         this.state = State.UP;
469         try {
470             this.sessionState.setSessionState(this.state);
471             this.listener.onSessionUp(this);
472         } catch (final Exception e) {
473             handleException(e);
474             throw e;
475         }
476     }
477
478     public synchronized State getState() {
479         return this.state;
480     }
481
482     @Override
483     public final Ipv4Address getBgpId() {
484         return this.bgpId;
485     }
486
487     @Override
488     public final AsNumber getAsNumber() {
489         return this.asNumber;
490     }
491
492     private synchronized boolean isWritable() {
493         return this.channel != null && this.channel.isWritable();
494     }
495
496     public ChannelOutputLimiter getLimiter() {
497         return this.limiter;
498     }
499
500     @Override
501     public final void channelInactive(final ChannelHandlerContext ctx) {
502         LOG.debug("Channel {} inactive.", ctx.channel());
503         this.endOfInput();
504
505         try {
506             super.channelInactive(ctx);
507         } catch (final Exception e) {
508             throw new IllegalStateException("Failed to delegate channel inactive event on channel " + ctx.channel(), e);
509         }
510     }
511
512     @Override
513     protected final void channelRead0(final ChannelHandlerContext ctx, final Notification msg) {
514         LOG.debug("Message was received: {}", msg);
515         this.handleMessage(msg);
516     }
517
518     @Override
519     public final void handlerAdded(final ChannelHandlerContext ctx) {
520         this.sessionUp();
521     }
522
523     @Override
524     public synchronized void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
525         handleException(cause);
526     }
527
528     /**
529      * Handle exception occurred in the BGP session. The session in error state should be closed
530      * properly so that it can be restored later.
531      */
532     @VisibleForTesting
533     void handleException(final Throwable cause) {
534         LOG.warn("BGP session encountered error", cause);
535         final Throwable docCause = cause.getCause();
536         if (docCause instanceof BGPDocumentedException) {
537             this.terminate((BGPDocumentedException) docCause);
538         } else {
539             this.terminate(new BGPDocumentedException(BGPError.CEASE));
540         }
541     }
542
543     @Override
544     public BGPSessionState getBGPSessionState() {
545         return this.sessionState;
546     }
547
548     @Override
549     public BGPTimersState getBGPTimersState() {
550         return this.sessionState;
551     }
552
553     @Override
554     public BGPTransportState getBGPTransportState() {
555         return this.sessionState;
556     }
557
558     @Override
559     public void registerMessagesCounter(final BGPMessagesListener bgpMessagesListener) {
560         this.sessionState.registerMessagesCounter(bgpMessagesListener);
561     }
562
563     @Override
564     public <T extends PeerConstraint> void addDecoderConstraint(final Class<T> constraintClass, final T constraint) {
565         this.channel.pipeline().get(BGPByteToMessageDecoder.class).addDecoderConstraint(constraintClass, constraint);
566     }
567 }