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