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