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