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