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