Bug 5061: Introduce BGP Application Peer deployer
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / AbstractBGPSessionNegotiator.java
index ed91c55ae466d2f3c603ff19d005438d1f3af663..121ddedb3f38e191131207a3f03a7d816d409484 100644 (file)
@@ -22,13 +22,11 @@ import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
 import org.opendaylight.protocol.bgp.parser.BGPError;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
-import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionValidator;
 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
 import org.opendaylight.protocol.bgp.rib.spi.SessionNegotiator;
 import org.opendaylight.protocol.util.Values;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
@@ -43,7 +41,7 @@ import org.slf4j.LoggerFactory;
  * Bgp Session negotiator. Common for local-to-remote and remote-to-local connections.
  * One difference is session validation performed by injected BGPSessionValidator when OPEN message is received.
  */
-public abstract class AbstractBGPSessionNegotiator extends ChannelInboundHandlerAdapter implements SessionNegotiator {
+abstract class AbstractBGPSessionNegotiator extends ChannelInboundHandlerAdapter implements SessionNegotiator {
     // 4 minutes recommended in http://tools.ietf.org/html/rfc4271#section-8.2.2
     private static final int INITIAL_HOLDTIMER = 4;
 
@@ -75,7 +73,6 @@ public abstract class AbstractBGPSessionNegotiator extends ChannelInboundHandler
 
     private static final Logger LOG = LoggerFactory.getLogger(AbstractBGPSessionNegotiator.class);
     private final BGPPeerRegistry registry;
-    private final BGPSessionValidator sessionValidator;
     private final Promise<BGPSessionImpl> promise;
     private final Channel channel;
     @GuardedBy("this")
@@ -84,57 +81,56 @@ public abstract class AbstractBGPSessionNegotiator extends ChannelInboundHandler
     @GuardedBy("this")
     private BGPSessionImpl session;
 
-    public AbstractBGPSessionNegotiator(final Promise<BGPSessionImpl> promise, final Channel channel,
-            final BGPPeerRegistry registry, final BGPSessionValidator sessionValidator) {
+    AbstractBGPSessionNegotiator(final Promise<BGPSessionImpl> promise, final Channel channel,
+            final BGPPeerRegistry registry) {
         this.promise = Preconditions.checkNotNull(promise);
         this.channel = Preconditions.checkNotNull(channel);
         this.registry = registry;
-        this.sessionValidator = sessionValidator;
     }
 
     private synchronized void startNegotiation() {
-        // Open can be sent first either from ODL (IDLE) or from peer (OPEN_CONFIRM)
-        Preconditions.checkState(this.state == State.IDLE || this.state == State.OPEN_CONFIRM);
-
-        // Check if peer is configured in registry before retrieving preferences
-        if (!this.registry.isPeerConfigured(getRemoteIp())) {
-            final BGPDocumentedException cause = new BGPDocumentedException(
-                    "BGP peer with ip: " + getRemoteIp()
-                    + " not configured, check configured peers in : "
-                    + this.registry, BGPError.CONNECTION_REJECTED);
-            negotiationFailed(cause);
+        if (!(this.state == State.IDLE || this.state == State.OPEN_CONFIRM)) {
             return;
         }
+        // Open can be sent first either from ODL (IDLE) or from peer (OPEN_CONFIRM)
+        final IpAddress remoteIp = getRemoteIp();
+        try {
+            // Check if peer is configured in registry before retrieving preferences
+            if (!this.registry.isPeerConfigured(remoteIp)) {
+                final BGPDocumentedException cause = new BGPDocumentedException(
+                    String.format("BGP peer with ip: %s not configured, check configured peers in : %s", remoteIp, this.registry), BGPError.CONNECTION_REJECTED);
+                negotiationFailed(cause);
+                return;
+            }
 
-        final BGPSessionPreferences preferences = getPreferences();
+            final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
 
-        int as = preferences.getMyAs().getValue().intValue();
-        // Set as AS_TRANS if the value is bigger than 2B
-        if (as > Values.UNSIGNED_SHORT_MAX_VALUE) {
-            as = AS_TRANS;
-        }
-        sendMessage(new OpenBuilder().setMyAsNumber(as).setHoldTimer(preferences.getHoldTime()).setBgpIdentifier(
+            int as = preferences.getMyAs().getValue().intValue();
+            // Set as AS_TRANS if the value is bigger than 2B
+            if (as > Values.UNSIGNED_SHORT_MAX_VALUE) {
+                as = AS_TRANS;
+            }
+            sendMessage(new OpenBuilder().setMyAsNumber(as).setHoldTimer(preferences.getHoldTime()).setBgpIdentifier(
                 preferences.getBgpId()).setBgpParameters(preferences.getParams()).build());
-        if (this.state != State.FINISHED) {
-            this.state = State.OPEN_SENT;
-
-            this.channel.eventLoop().schedule(new Runnable() {
-                @Override
-                public void run() {
-                    if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
-                        AbstractBGPSessionNegotiator.this.sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
-                        negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
-                        AbstractBGPSessionNegotiator.this.state = State.FINISHED;
+            if (this.state != State.FINISHED) {
+                this.state = State.OPEN_SENT;
+                this.channel.eventLoop().schedule(new Runnable() {
+                    @Override
+                    public void run() {
+                        if (AbstractBGPSessionNegotiator.this.state != State.FINISHED) {
+                            AbstractBGPSessionNegotiator.this.sendMessage(buildErrorNotify(BGPError.HOLD_TIMER_EXPIRED));
+                            negotiationFailed(new BGPDocumentedException("HoldTimer expired", BGPError.FSM_ERROR));
+                            AbstractBGPSessionNegotiator.this.state = State.FINISHED;
+                        }
                     }
-                }
-            }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
+                }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
+            }
+        } catch (final Exception e) {
+            LOG.warn("Unexpected negotiation failure", e);
+            negotiationFailedCloseChannel(e);
         }
     }
 
-    private BGPSessionPreferences getPreferences() {
-        return this.registry.getPeerPreferences(getRemoteIp());
-    }
-
     private IpAddress getRemoteIp() {
         return StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress());
     }
@@ -148,10 +144,11 @@ public abstract class AbstractBGPSessionNegotiator extends ChannelInboundHandler
             return;
         case IDLE:
             // to avoid race condition when Open message was sent by the peer before startNegotiation could be executed
-            if (msg instanceof Open) {
-                handleOpen((Open) msg);
-                return;
-            }
+           if (msg instanceof Open) {
+               startNegotiation();
+               handleOpen((Open) msg);
+               return;
+           }
             sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
             return;
         case OPEN_CONFIRM:
@@ -177,7 +174,7 @@ public abstract class AbstractBGPSessionNegotiator extends ChannelInboundHandler
         // Catch-all for unexpected message
         LOG.warn("Channel {} state {} unexpected message {}", this.channel, this.state, msg);
         sendMessage(buildErrorNotify(BGPError.FSM_ERROR));
-        negotiationFailed(new BGPDocumentedException("Unexpected message", BGPError.FSM_ERROR));
+        negotiationFailed(new BGPDocumentedException("Unexpected message channel: " + this.channel + ", state: " + this.state + ", message: " + msg, BGPError.FSM_ERROR));
         this.state = State.FINISHED;
     }
 
@@ -194,17 +191,12 @@ public abstract class AbstractBGPSessionNegotiator extends ChannelInboundHandler
     }
 
     private void handleOpen(final Open openObj) {
+        final IpAddress remoteIp = getRemoteIp();
+        final BGPSessionPreferences preferences = this.registry.getPeerPreferences(remoteIp);
         try {
-            this.sessionValidator.validate(openObj, getPreferences());
-        } catch (final BGPDocumentedException e) {
-            negotiationFailed(e);
-            return;
-        }
-
-        try {
-            final BGPSessionListener peer = this.registry.getPeer(getRemoteIp(), getSourceId(openObj, getPreferences()), getDestinationId(openObj, getPreferences()), getAsNumber(openObj, getPreferences()), openObj);
+            final BGPSessionListener peer = this.registry.getPeer(remoteIp, getSourceId(openObj, preferences), getDestinationId(openObj, preferences), openObj);
             sendMessage(new KeepaliveBuilder().build());
-            this.session = new BGPSessionImpl(peer, this.channel, openObj, getPreferences(), this.registry);
+            this.session = new BGPSessionImpl(peer, this.channel, openObj, preferences, this.registry);
             this.state = State.OPEN_CONFIRM;
             LOG.debug("Channel {} moved to OpenConfirm state with remote proposal {}", this.channel, openObj);
         } catch (final BGPDocumentedException e) {
@@ -220,7 +212,9 @@ public abstract class AbstractBGPSessionNegotiator extends ChannelInboundHandler
             // deliver the message, this method gets called with different exception (definitely not with BGPDocumentedException).
             sendMessage(buildErrorNotify(((BGPDocumentedException)e).getError(), ((BGPDocumentedException) e).getData()));
         }
-        this.registry.removePeerSession(getRemoteIp());
+        if (this.state == State.OPEN_CONFIRM) {
+            this.registry.removePeerSession(getRemoteIp());
+        }
         negotiationFailedCloseChannel(e);
         this.state = State.FINISHED;
     }
@@ -239,13 +233,6 @@ public abstract class AbstractBGPSessionNegotiator extends ChannelInboundHandler
      */
     protected abstract Ipv4Address getSourceId(final Open openMsg, final BGPSessionPreferences preferences);
 
-    /**
-     * @param openMsg Open message received from remote BGP speaker
-     * @param preferences Local BGP speaker preferences
-     * @return AS Number of device that initiate connection
-     */
-    protected abstract AsNumber getAsNumber(final Open openMsg, final BGPSessionPreferences preferences);
-
     public synchronized State getState() {
         return this.state;
     }
@@ -267,12 +254,11 @@ public abstract class AbstractBGPSessionNegotiator extends ChannelInboundHandler
             @Override
             public void operationComplete(final ChannelFuture f) {
                 if (!f.isSuccess()) {
-                    LOG.info("Failed to send message {}", msg, f.cause());
+                    LOG.warn("Failed to send message {}", msg, f.cause());
                     negotiationFailedCloseChannel(f.cause());
                 } else {
                     LOG.trace("Message {} sent to socket", msg);
                 }
-
             }
         });
     }
@@ -280,20 +266,12 @@ public abstract class AbstractBGPSessionNegotiator extends ChannelInboundHandler
     @Override
     public final void channelActive(final ChannelHandlerContext ctx) {
         LOG.debug("Starting session negotiation on channel {}", this.channel);
-
-        try {
-            startNegotiation();
-        } catch (final Exception e) {
-            LOG.warn("Unexpected negotiation failure", e);
-            negotiationFailedCloseChannel(e);
-        }
-
+        startNegotiation();
     }
 
     @Override
     public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
         LOG.debug("Negotiation read invoked on channel {}", this.channel);
-
         try {
             handleMessage((Notification) msg);
         } catch (final Exception e) {