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