BUG-54 : switched channel pipeline to be protocol specific.
[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 io.netty.channel.Channel;
11 import io.netty.util.Timeout;
12 import io.netty.util.Timer;
13 import io.netty.util.TimerTask;
14
15 import java.io.IOException;
16 import java.util.Date;
17 import java.util.Set;
18 import java.util.concurrent.TimeUnit;
19
20 import javax.annotation.concurrent.GuardedBy;
21
22 import org.opendaylight.protocol.bgp.concepts.BGPTableType;
23 import org.opendaylight.protocol.bgp.parser.BGPError;
24 import org.opendaylight.protocol.bgp.parser.BGPMessage;
25 import org.opendaylight.protocol.bgp.parser.BGPParameter;
26 import org.opendaylight.protocol.bgp.parser.BGPSession;
27 import org.opendaylight.protocol.bgp.parser.BGPSessionListener;
28 import org.opendaylight.protocol.bgp.parser.BGPTerminationReason;
29 import org.opendaylight.protocol.bgp.parser.message.BGPKeepAliveMessage;
30 import org.opendaylight.protocol.bgp.parser.message.BGPNotificationMessage;
31 import org.opendaylight.protocol.bgp.parser.message.BGPOpenMessage;
32 import org.opendaylight.protocol.bgp.parser.parameter.MultiprotocolCapability;
33 import org.opendaylight.protocol.framework.AbstractProtocolSession;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 import com.google.common.annotations.VisibleForTesting;
38 import com.google.common.base.Objects;
39 import com.google.common.base.Objects.ToStringHelper;
40 import com.google.common.base.Preconditions;
41 import com.google.common.collect.Sets;
42
43 @VisibleForTesting
44 public class BGPSessionImpl extends AbstractProtocolSession<BGPMessage> implements BGPSession {
45
46         private static final Logger logger = LoggerFactory.getLogger(BGPSessionImpl.class);
47
48         private static final int DEFAULT_HOLD_TIMER_VALUE = 15;
49
50         public static int HOLD_TIMER_VALUE = DEFAULT_HOLD_TIMER_VALUE; // 240
51
52         /**
53          * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
54          */
55         protected long lastMessageSentAt;
56
57         /**
58          * System.nanoTime value about when was received the last message
59          */
60         private long lastMessageReceivedAt;
61
62         private final BGPSessionListener listener;
63
64         /**
65          * Timer object grouping FSM Timers
66          */
67         private final Timer stateTimer;
68
69         private final BGPSynchronization sync;
70
71         private int kaCounter = 0;
72
73         private final Channel channel;
74
75         @GuardedBy("this")
76         private boolean closed = false;
77
78         private final short keepAlive;
79
80         private final Set<BGPTableType> tableTypes;
81
82         BGPSessionImpl(final Timer timer, final BGPSessionListener listener, final Channel channel, final short keepAlive,
83                         final BGPOpenMessage remoteOpen) {
84                 this.listener = Preconditions.checkNotNull(listener);
85                 this.stateTimer = Preconditions.checkNotNull(timer);
86                 this.channel = Preconditions.checkNotNull(channel);
87                 this.keepAlive = keepAlive;
88
89                 final Set<BGPTableType> tts = Sets.newHashSet();
90                 if (remoteOpen.getOptParams() != null) {
91                         for (final BGPParameter param : remoteOpen.getOptParams()) {
92                                 if (param instanceof MultiprotocolCapability) {
93                                         tts.add(((MultiprotocolCapability) param).getTableType());
94                                 }
95                         }
96                 }
97
98                 this.sync = new BGPSynchronization(this, this.listener, tts);
99                 this.tableTypes = tts;
100
101                 if (remoteOpen.getHoldTime() != 0) {
102                         this.stateTimer.newTimeout(new TimerTask() {
103
104                                 @Override
105                                 public void run(final Timeout timeout) throws Exception {
106                                         handleHoldTimer();
107                                 }
108                         }, remoteOpen.getHoldTime(), TimeUnit.SECONDS);
109
110                         this.stateTimer.newTimeout(new TimerTask() {
111                                 @Override
112                                 public void run(final Timeout timeout) throws Exception {
113                                         handleKeepaliveTimer();
114                                 }
115                         }, keepAlive, TimeUnit.SECONDS);
116                 }
117         }
118
119         @Override
120         public synchronized void close() {
121                 logger.debug("Closing session: {}", this);
122                 if (!this.closed) {
123                         this.sendMessage(new BGPNotificationMessage(BGPError.CEASE));
124                         this.channel.close();
125                         this.closed = true;
126                 }
127         }
128
129         /**
130          * Handles incoming message based on their type.
131          * 
132          * @param msg incoming message
133          */
134         @Override
135         public void handleMessage(final BGPMessage msg) {
136                 // Update last reception time
137                 this.lastMessageReceivedAt = System.nanoTime();
138
139                 if (msg instanceof BGPOpenMessage) {
140                         // Open messages should not be present here
141                         this.terminate(BGPError.FSM_ERROR);
142                 } else if (msg instanceof BGPNotificationMessage) {
143                         // Notifications are handled internally
144                         logger.info("Session closed because Notification message received: {}", ((BGPNotificationMessage) msg).getError());
145                         this.closeWithoutMessage();
146                         this.listener.onSessionTerminated(this, new BGPTerminationReason(((BGPNotificationMessage) msg).getError()));
147                 } else if (msg instanceof BGPKeepAliveMessage) {
148                         // Keepalives are handled internally
149                         logger.debug("Received KeepAlive messsage.");
150                         this.kaCounter++;
151                         if (this.kaCounter >= 2) {
152                                 this.sync.kaReceived();
153                         }
154                 } else {
155                         // All others are passed up
156                         this.listener.onMessage(this, msg);
157                 }
158         }
159
160         @Override
161         public synchronized void endOfInput() {
162                 if (!this.closed) {
163                         this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
164                 }
165         }
166
167         void sendMessage(final BGPMessage msg) {
168                 try {
169                         this.channel.writeAndFlush(msg);
170                         this.lastMessageSentAt = System.nanoTime();
171                         logger.debug("Sent message: {}", msg);
172                 } catch (final Exception e) {
173                         logger.warn("Message {} was not sent.", msg, e);
174                 }
175         }
176
177         private synchronized void closeWithoutMessage() {
178                 logger.debug("Closing session: {}", this);
179                 this.channel.close();
180                 this.closed = true;
181         }
182
183         /**
184          * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
185          * modified, because he initiated the closing. (To prevent concurrent modification exception).
186          * 
187          * @param closeObject
188          */
189         private void terminate(final BGPError error) {
190                 this.sendMessage(new BGPNotificationMessage(error));
191                 this.closeWithoutMessage();
192                 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
193         }
194
195         /**
196          * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
197          * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
198          * which the message was received. If the session was closed by the time this method starts to execute (the session
199          * state will become IDLE), then rescheduling won't occur.
200          */
201         private synchronized void handleHoldTimer() {
202                 final long ct = System.nanoTime();
203
204                 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(HOLD_TIMER_VALUE);
205
206                 if (!this.closed) {
207                         if (ct >= nextHold) {
208                                 logger.debug("HoldTimer expired. " + new Date());
209                                 this.terminate(BGPError.HOLD_TIMER_EXPIRED);
210                         } else {
211                                 this.stateTimer.newTimeout(new TimerTask() {
212                                         @Override
213                                         public void run(final Timeout timeout) throws Exception {
214                                                 handleHoldTimer();
215                                         }
216                                 }, nextHold - ct, TimeUnit.NANOSECONDS);
217                         }
218                 }
219         }
220
221         /**
222          * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
223          * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
224          * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
225          * starts to execute (the session state will become IDLE), that rescheduling won't occur.
226          */
227         private synchronized void handleKeepaliveTimer() {
228                 final long ct = System.nanoTime();
229
230                 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
231
232                 if (!this.closed) {
233                         if (ct >= nextKeepalive) {
234                                 this.sendMessage(new BGPKeepAliveMessage());
235                                 nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
236                         }
237                         this.stateTimer.newTimeout(new TimerTask() {
238                                 @Override
239                                 public void run(final Timeout timeout) throws Exception {
240                                         handleKeepaliveTimer();
241                                 }
242                         }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
243                 }
244         }
245
246         @Override
247         final public String toString() {
248                 return addToStringAttributes(Objects.toStringHelper(this)).toString();
249         }
250
251         protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
252                 toStringHelper.add("channel", this.channel);
253                 toStringHelper.add("closed", this.closed);
254                 return toStringHelper;
255         }
256
257         @Override
258         public Set<BGPTableType> getAdvertisedTableTypes() {
259                 return this.tableTypes;
260         }
261
262         @Override
263         protected void sessionUp() {
264                 this.listener.onSessionUp(this);
265         }
266 }