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