65bb948121bb48332b68a3c77b2c3e475b50d235
[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          * Internal session state.
54          */
55         public enum State {
56                 /**
57                  * The session object is created by the negotiator in OpenConfirm state.
58                  * While in this state, the session object is half-alive, e.g. the timers
59                  * are running, but the session is not completely up, e.g. it has not been
60                  * announced to the listener. If the session is torn down in this state,
61                  * we do not inform the listener.
62                  */
63                 OpenConfirm,
64                 /**
65                  * The session has been completely established.
66                  */
67                 Up,
68                 /**
69                  * The session has been closed. It will not be resurrected.
70                  */
71                 Idle,
72         }
73
74         /**
75          * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
76          */
77         protected long lastMessageSentAt;
78
79         /**
80          * System.nanoTime value about when was received the last message
81          */
82         private long lastMessageReceivedAt;
83
84         private final BGPSessionListener listener;
85
86         /**
87          * Timer object grouping FSM Timers
88          */
89         private final Timer stateTimer;
90
91         private final BGPSynchronization sync;
92
93         private int kaCounter = 0;
94
95         private final Channel channel;
96
97         @GuardedBy("this")
98         private State state = State.OpenConfirm;
99
100         private final int keepAlive;
101
102         private final Set<BGPTableType> tableTypes;
103
104         BGPSessionImpl(final Timer timer, final BGPSessionListener listener, final Channel channel, final BGPOpenMessage remoteOpen) {
105                 this.listener = Preconditions.checkNotNull(listener);
106                 this.stateTimer = Preconditions.checkNotNull(timer);
107                 this.channel = Preconditions.checkNotNull(channel);
108                 this.keepAlive = remoteOpen.getHoldTime() / 3;
109
110                 final Set<BGPTableType> tts = Sets.newHashSet();
111                 if (remoteOpen.getOptParams() != null) {
112                         for (final BGPParameter param : remoteOpen.getOptParams()) {
113                                 if (param instanceof MultiprotocolCapability) {
114                                         tts.add(((MultiprotocolCapability) param).getTableType());
115                                 }
116                         }
117                 }
118
119                 this.sync = new BGPSynchronization(this, this.listener, tts);
120                 this.tableTypes = tts;
121
122                 if (remoteOpen.getHoldTime() != 0) {
123                         this.stateTimer.newTimeout(new TimerTask() {
124
125                                 @Override
126                                 public void run(final Timeout timeout) throws Exception {
127                                         handleHoldTimer();
128                                 }
129                         }, remoteOpen.getHoldTime(), TimeUnit.SECONDS);
130
131                         this.stateTimer.newTimeout(new TimerTask() {
132                                 @Override
133                                 public void run(final Timeout timeout) throws Exception {
134                                         handleKeepaliveTimer();
135                                 }
136                         }, this.keepAlive, TimeUnit.SECONDS);
137                 }
138         }
139
140         @Override
141         public synchronized void close() {
142                 logger.debug("Closing session: {}", this);
143                 if (this.state != State.Idle) {
144                         this.sendMessage(new BGPNotificationMessage(BGPError.CEASE));
145                         this.channel.close();
146                         this.state = State.Idle;
147                 }
148         }
149
150         /**
151          * Handles incoming message based on their type.
152          * 
153          * @param msg incoming message
154          */
155         @Override
156         public void handleMessage(final BGPMessage msg) {
157                 // Update last reception time
158                 this.lastMessageReceivedAt = System.nanoTime();
159
160                 if (msg instanceof BGPOpenMessage) {
161                         // Open messages should not be present here
162                         this.terminate(BGPError.FSM_ERROR);
163                 } else if (msg instanceof BGPNotificationMessage) {
164                         // Notifications are handled internally
165                         logger.info("Session closed because Notification message received: {}", ((BGPNotificationMessage) msg).getError());
166                         this.closeWithoutMessage();
167                         this.listener.onSessionTerminated(this, new BGPTerminationReason(((BGPNotificationMessage) msg).getError()));
168                 } else if (msg instanceof BGPKeepAliveMessage) {
169                         // Keepalives are handled internally
170                         logger.debug("Received KeepAlive messsage.");
171                         this.kaCounter++;
172                         if (this.kaCounter >= 2) {
173                                 this.sync.kaReceived();
174                         }
175                 } else {
176                         // All others are passed up
177                         this.listener.onMessage(this, msg);
178                 }
179         }
180
181         @Override
182         public synchronized void endOfInput() {
183                 if (this.state == State.Up) {
184                         this.listener.onSessionDown(this, new IOException("End of input detected. Close the session."));
185                 }
186         }
187
188         void sendMessage(final BGPMessage msg) {
189                 try {
190                         this.channel.writeAndFlush(msg);
191                         this.lastMessageSentAt = System.nanoTime();
192                         logger.debug("Sent message: {}", msg);
193                 } catch (final Exception e) {
194                         logger.warn("Message {} was not sent.", msg, e);
195                 }
196         }
197
198         private synchronized void closeWithoutMessage() {
199                 logger.debug("Closing session: {}", this);
200                 this.channel.close();
201                 this.state = State.Idle;
202         }
203
204         /**
205          * Closes PCEP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
206          * modified, because he initiated the closing. (To prevent concurrent modification exception).
207          * 
208          * @param closeObject
209          */
210         private void terminate(final BGPError error) {
211                 this.sendMessage(new BGPNotificationMessage(error));
212                 this.closeWithoutMessage();
213
214                 this.listener.onSessionTerminated(this, new BGPTerminationReason(error));
215         }
216
217         /**
218          * If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
219          * will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
220          * which the message was received. If the session was closed by the time this method starts to execute (the session
221          * state will become IDLE), then rescheduling won't occur.
222          */
223         private synchronized void handleHoldTimer() {
224                 if (this.state == State.Idle) {
225                         return;
226                 }
227
228                 final long ct = System.nanoTime();
229                 final long nextHold = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(HOLD_TIMER_VALUE);
230
231                 if (ct >= nextHold) {
232                         logger.debug("HoldTimer expired. " + new Date());
233                         this.terminate(BGPError.HOLD_TIMER_EXPIRED);
234                 } else {
235                         this.stateTimer.newTimeout(new TimerTask() {
236                                 @Override
237                                 public void run(final Timeout timeout) throws Exception {
238                                         handleHoldTimer();
239                                 }
240                         }, nextHold - ct, TimeUnit.NANOSECONDS);
241                 }
242         }
243
244         /**
245          * If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
246          * KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
247          * KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
248          * starts to execute (the session state will become IDLE), that rescheduling won't occur.
249          */
250         private synchronized void handleKeepaliveTimer() {
251                 if (this.state == State.Idle) {
252                         return;
253                 }
254
255                 final long ct = System.nanoTime();
256                 long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
257
258                 if (ct >= nextKeepalive) {
259                         this.sendMessage(new BGPKeepAliveMessage());
260                         nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
261                 }
262                 this.stateTimer.newTimeout(new TimerTask() {
263                         @Override
264                         public void run(final Timeout timeout) throws Exception {
265                                 handleKeepaliveTimer();
266                         }
267                 }, nextKeepalive - ct, TimeUnit.NANOSECONDS);
268         }
269
270         @Override
271         final public String toString() {
272                 return addToStringAttributes(Objects.toStringHelper(this)).toString();
273         }
274
275         protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
276                 toStringHelper.add("channel", this.channel);
277                 toStringHelper.add("state", this.state);
278                 return toStringHelper;
279         }
280
281         @Override
282         public Set<BGPTableType> getAdvertisedTableTypes() {
283                 return this.tableTypes;
284         }
285
286         @Override
287         protected synchronized void sessionUp() {
288                 this.state = State.Up;
289                 this.listener.onSessionUp(this);
290         }
291
292         public synchronized State getState() {
293                 return this.state;
294         }
295 }