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