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