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