Remove a potential NPE
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / device / DeviceContextImpl.java
index c128a06ea1594c9e9786ca151b8d3c9af95bd7df..e09a5c6e048e99c4daee9eee1262cacdfdd3acbd 100644 (file)
@@ -9,21 +9,25 @@ package org.opendaylight.openflowplugin.impl.device;
 
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
-import com.google.common.util.concurrent.SettableFuture;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
 import io.netty.util.HashedWheelTimer;
 import io.netty.util.Timeout;
 import java.math.BigInteger;
+import java.util.Collection;
 import java.util.HashMap;
-import java.util.Iterator;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
-import java.util.TreeMap;
-import java.util.concurrent.atomic.AtomicLong;
 import javax.annotation.Nonnull;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
+import org.opendaylight.controller.md.sal.binding.api.NotificationService;
 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
+import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
+import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
@@ -34,7 +38,7 @@ import org.opendaylight.openflowplugin.api.openflow.device.Xid;
 import org.opendaylight.openflowplugin.api.openflow.device.exception.DeviceDataException;
 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceContextClosedHandler;
 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceDisconnectedHandler;
-import org.opendaylight.openflowplugin.api.openflow.device.listener.OpenflowMessageListenerFacade;
+import org.opendaylight.openflowplugin.api.openflow.device.handlers.MultiMsgCollector;
 import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
 import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
@@ -42,6 +46,7 @@ import org.opendaylight.openflowplugin.api.openflow.registry.group.DeviceGroupRe
 import org.opendaylight.openflowplugin.api.openflow.registry.meter.DeviceMeterRegistry;
 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
 import org.opendaylight.openflowplugin.impl.common.NodeStaticReplyTranslatorUtil;
+import org.opendaylight.openflowplugin.impl.device.listener.MultiMsgCollectorImpl;
 import org.opendaylight.openflowplugin.impl.registry.flow.DeviceFlowRegistryImpl;
 import org.opendaylight.openflowplugin.impl.registry.group.DeviceGroupRegistryImpl;
 import org.opendaylight.openflowplugin.impl.registry.meter.DeviceMeterRegistryImpl;
@@ -64,14 +69,10 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731
 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.FlowCapableNodeConnectorStatisticsData;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.FlowCapableNodeConnectorStatisticsDataBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableFeatures;
 import org.opendaylight.yangtools.yang.binding.ChildOf;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -81,27 +82,41 @@ import org.slf4j.LoggerFactory;
 public class DeviceContextImpl implements DeviceContext {
 
     private static final Logger LOG = LoggerFactory.getLogger(DeviceContextImpl.class);
+    public static final String DEVICE_DISCONNECTED = "Device disconnected.";
 
     private final ConnectionContext primaryConnectionContext;
     private final DeviceState deviceState;
     private final DataBroker dataBroker;
-    private final XidGenerator xidGenerator;
     private final HashedWheelTimer hashedWheelTimer;
-    private Map<Long, RequestContext> requests = new TreeMap<>();
-
     private final Map<SwitchConnectionDistinguisher, ConnectionContext> auxiliaryConnectionContexts;
     private final TransactionChainManager txChainManager;
     private TranslatorLibrary translatorLibrary;
-    private OpenflowMessageListenerFacade openflowMessageListenerFacade;
     private final DeviceFlowRegistry deviceFlowRegistry;
     private final DeviceGroupRegistry deviceGroupRegistry;
     private final DeviceMeterRegistry deviceMeterRegistry;
     private Timeout barrierTaskTimeout;
-    private NotificationProviderService notificationService;
-    private final MessageSpy<Class> messageSpy;
+    private NotificationService notificationService;
+    private final MessageSpy messageSpy;
     private DeviceDisconnectedHandler deviceDisconnectedHandler;
-    private DeviceContextClosedHandler deviceContextClosedHandler;
+    private final Collection<DeviceContextClosedHandler> closeHandlers = new HashSet<>();
+    private NotificationPublishService notificationPublishService;
+    private final OutboundQueue outboundQueueProvider;
+    private final MultiMsgCollector multiMsgCollector = new MultiMsgCollectorImpl();
+
+    private volatile int outstandingNotificationsAmount = 0;
+    private volatile boolean filteringPacketIn = false;
+    private final Object throttlingLock = new Object();
+    private int filteringHighWaterMark = 0;
+
+    @Override
+    public MultiMsgCollector getMultiMsgCollector() {
+        return multiMsgCollector;
+    }
 
+    @Override
+    public Long getReservedXid() {
+        return outboundQueueProvider.reserveEntry();
+    }
 
     @VisibleForTesting
     DeviceContextImpl(@Nonnull final ConnectionContext primaryConnectionContext,
@@ -113,14 +128,14 @@ public class DeviceContextImpl implements DeviceContext {
         this.deviceState = Preconditions.checkNotNull(deviceState);
         this.dataBroker = Preconditions.checkNotNull(dataBroker);
         this.hashedWheelTimer = Preconditions.checkNotNull(hashedWheelTimer);
-        xidGenerator = new XidGenerator();
-        txChainManager = new TransactionChainManager(dataBroker, hashedWheelTimer, 500L);
+        txChainManager = new TransactionChainManager(dataBroker, hashedWheelTimer, 500L, 500L);
         auxiliaryConnectionContexts = new HashMap<>();
-        requests = new HashMap<>();
         deviceFlowRegistry = new DeviceFlowRegistryImpl();
         deviceGroupRegistry = new DeviceGroupRegistryImpl();
         deviceMeterRegistry = new DeviceMeterRegistryImpl();
         messageSpy = _messageSpy;
+        multiMsgCollector.setDeviceReplyProcessor(this);
+        outboundQueueProvider = Preconditions.checkNotNull(primaryConnectionContext.getOutboundQueueProvider());
     }
 
     /**
@@ -128,22 +143,25 @@ public class DeviceContextImpl implements DeviceContext {
      * and we are able to set a scheduler for an automatic transaction submitting by time (0,5sec).
      */
     void submitTransaction() {
+        txChainManager.enableSubmit();
         txChainManager.submitTransaction();
-        txChainManager.enableCounter();
     }
 
     @Override
-    public <M extends ChildOf<DataObject>> void onMessage(final M message, final RequestContext requestContext) {
+    public <M extends ChildOf<DataObject>> void onMessage(final M message, final RequestContext<?> requestContext) {
         // TODO Auto-generated method stub
-
     }
 
     @Override
     public void addAuxiliaryConenctionContext(final ConnectionContext connectionContext) {
-        final SwitchConnectionDistinguisher connectionDistinguisher = new SwitchConnectionCookieOFImpl(connectionContext.getFeatures().getAuxiliaryId());
+        final SwitchConnectionDistinguisher connectionDistinguisher = createConnectionDistinguisher(connectionContext);
         auxiliaryConnectionContexts.put(connectionDistinguisher, connectionContext);
     }
 
+    private static SwitchConnectionDistinguisher createConnectionDistinguisher(final ConnectionContext connectionContext) {
+        return new SwitchConnectionCookieOFImpl(connectionContext.getFeatures().getAuxiliaryId());
+    }
+
     @Override
     public void removeAuxiliaryConenctionContext(final ConnectionContext connectionContext) {
         // TODO Auto-generated method stub
@@ -170,12 +188,6 @@ public class DeviceContextImpl implements DeviceContext {
         txChainManager.addDeleteOperationTotTxChain(store, path);
     }
 
-    @Override
-    public TableFeatures getCapabilities() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
     @Override
     public ConnectionContext getPrimaryConnectionContext() {
         return primaryConnectionContext;
@@ -186,42 +198,6 @@ public class DeviceContextImpl implements DeviceContext {
         return auxiliaryConnectionContexts.get(new SwitchConnectionCookieOFImpl(cookie.longValue()));
     }
 
-    @Override
-    public Xid getNextXid() {
-        return xidGenerator.generate();
-    }
-
-    @Override
-    public RequestContext lookupRequest(Xid xid) {
-        return requests.get(xid.getValue());
-    }
-
-    @Override
-    public int getNumberOfOutstandingRequests() {
-        return requests.size();
-    }
-
-    @Override
-    public void hookRequestCtx(final Xid xid, final RequestContext requestFutureContext) {
-        requests.put(xid.getValue(), requestFutureContext);
-    }
-
-    @Override
-    public RequestContext unhookRequestCtx(Xid xid) {
-        return requests.remove(xid.getValue());
-    }
-
-    @Override
-    public void attachOpenflowMessageListener(final OpenflowMessageListenerFacade openflowMessageListenerFacade) {
-        this.openflowMessageListenerFacade = openflowMessageListenerFacade;
-        primaryConnectionContext.getConnectionAdapter().setMessageListener(openflowMessageListenerFacade);
-    }
-
-    @Override
-    public OpenflowMessageListenerFacade getOpenflowMessageListenerFacade() {
-        return openflowMessageListenerFacade;
-    }
-
     @Override
     public DeviceFlowRegistry getDeviceFlowRegistry() {
         return deviceFlowRegistry;
@@ -239,89 +215,23 @@ public class DeviceContextImpl implements DeviceContext {
 
     @Override
     public void processReply(final OfHeader ofHeader) {
-        final RequestContext requestContext = requests.get(ofHeader.getXid());
-        if (null != requestContext) {
-            final SettableFuture replyFuture = requestContext.getFuture();
-            requests.remove(ofHeader.getXid());
-            RpcResult<OfHeader> rpcResult;
-            if (ofHeader instanceof Error) {
-                final Error error = (Error) ofHeader;
-                final String message = "Operation on device failed";
-                rpcResult = RpcResultBuilder
-                        .<OfHeader>failed()
-                        .withError(RpcError.ErrorType.APPLICATION, message, new DeviceDataException(message, error))
-                        .build();
-                messageSpy.spyMessage(ofHeader.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE);
-            } else {
-                rpcResult = RpcResultBuilder
-                        .<OfHeader>success()
-                        .withResult(ofHeader)
-                        .build();
-                messageSpy.spyMessage(ofHeader.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS);
-            }
-
-            replyFuture.set(rpcResult);
-            try {
-                requestContext.close();
-            } catch (final Exception e) {
-                LOG.error("Closing RequestContext failed: ", e);
-            }
+        if (ofHeader instanceof Error) {
+            messageSpy.spyMessage(ofHeader.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE);
         } else {
-            LOG.error("Can't find request context registered for xid : {}. Type of reply: {}. From address: {}", ofHeader.getXid(), ofHeader.getClass().getName(),
-                    getPrimaryConnectionContext().getConnectionAdapter().getRemoteAddress());
+            messageSpy.spyMessage(ofHeader.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS);
         }
     }
 
     @Override
     public void processReply(final Xid xid, final List<MultipartReply> ofHeaderList) {
-        final RequestContext requestContext = requests.get(xid.getValue());
-        if (null != requestContext) {
-            final SettableFuture replyFuture = requestContext.getFuture();
-            requests.remove(xid.getValue());
-            final RpcResult<List<MultipartReply>> rpcResult = RpcResultBuilder
-                    .<List<MultipartReply>>success()
-                    .withResult(ofHeaderList)
-                    .build();
-            replyFuture.set(rpcResult);
-            for (MultipartReply multipartReply : ofHeaderList) {
-                messageSpy.spyMessage(multipartReply.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE);
-            }
-
-            try {
-                requestContext.close();
-            } catch (final Exception e) {
-                LOG.error("Closing RequestContext failed: ", e);
-            }
-        } else {
-            LOG.error("Can't find request context registered for xid : {}. Type of reply: MULTIPART. From address: {}", xid.getValue(),
-                    getPrimaryConnectionContext().getConnectionAdapter().getRemoteAddress());
+        for (final MultipartReply multipartReply : ofHeaderList) {
+            messageSpy.spyMessage(multipartReply.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE);
         }
     }
 
     @Override
     public void processException(final Xid xid, final DeviceDataException deviceDataException) {
-
-        LOG.trace("Processing exception for xid : {}", xid.getValue());
-
-        final RequestContext requestContext = requests.get(xid.getValue());
-
-        if (null != requestContext) {
-            final SettableFuture replyFuture = requestContext.getFuture();
-            requests.remove(xid.getValue());
-            final RpcResult<List<OfHeader>> rpcResult = RpcResultBuilder
-                    .<List<OfHeader>>failed()
-                    .withError(RpcError.ErrorType.APPLICATION, String.format("Message processing failed : %s", deviceDataException.getError()), deviceDataException)
-                    .build();
-            replyFuture.set(rpcResult);
-            messageSpy.spyMessage(deviceDataException.getClass(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE);
-            try {
-                requestContext.close();
-            } catch (final Exception e) {
-                LOG.error("Closing RequestContext failed: ", e);
-            }
-        } else {
-            LOG.error("Can't find request context registered for xid : {}", xid.getValue());
-        }
+        messageSpy.spyMessage(deviceDataException.getClass(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE);
     }
 
     @Override
@@ -357,11 +267,66 @@ public class DeviceContextImpl implements DeviceContext {
 
     @Override
     public void processPacketInMessage(final PacketInMessage packetInMessage) {
-        messageSpy.spyMessage(packetInMessage.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS);
+        messageSpy.spyMessage(packetInMessage.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH);
+        final ConnectionAdapter connectionAdapter = getPrimaryConnectionContext().getConnectionAdapter();
+
         final TranslatorKey translatorKey = new TranslatorKey(packetInMessage.getVersion(), PacketIn.class.getName());
         final MessageTranslator<PacketInMessage, PacketReceived> messageTranslator = translatorLibrary.lookupTranslator(translatorKey);
         final PacketReceived packetReceived = messageTranslator.translate(packetInMessage, this, null);
-        notificationService.publish(packetReceived);
+
+        if (packetReceived == null) {
+            LOG.debug("Received a null packet from switch");
+            return;
+        }
+        messageSpy.spyMessage(packetReceived.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_TRANSLATE_SRC_FAILURE);
+
+        ListenableFuture<? extends Object> offerNotification = notificationPublishService.offerNotification(packetReceived);
+        synchronized (throttlingLock) {
+            outstandingNotificationsAmount += 1;
+        }
+        if (NotificationPublishService.REJECTED.equals(offerNotification)) {
+            LOG.debug("notification offer rejected");
+            synchronized (throttlingLock) {
+                if (outstandingNotificationsAmount > 1 && !filteringPacketIn) {
+                    connectionAdapter.setPacketInFiltering(true);
+                    messageSpy.spyMessage(DeviceContext.class, MessageSpy.STATISTIC_GROUP.OFJ_BACKPRESSURE_ON);
+                    filteringPacketIn = true;
+                    filteringHighWaterMark = outstandingNotificationsAmount;
+                    LOG.debug("PacketIn filtering on: {}, watermark: {}", connectionAdapter.getRemoteAddress(), outstandingNotificationsAmount);
+                }
+            }
+        }
+
+        Futures.addCallback(offerNotification,
+                new FutureCallback<Object>() {
+                    @Override
+                    public void onSuccess(final Object result) {
+                        countdownFiltering();
+                        messageSpy.spyMessage(packetReceived.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS);
+                    }
+
+                    @Override
+                    public void onFailure(final Throwable t) {
+                        countdownFiltering();
+                        messageSpy.spyMessage(packetReceived.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_NOTIFICATION_REJECTED);
+                        LOG.debug("notification offer failed: {}, outstanding: {}", t.getMessage(), outstandingNotificationsAmount);
+                        LOG.trace("notification offer failed..", t);
+                    }
+
+                    private void countdownFiltering() {
+                        synchronized (throttlingLock) {
+                            outstandingNotificationsAmount -= 1;
+                            if (outstandingNotificationsAmount == 0 && filteringPacketIn) {
+                                connectionAdapter.setPacketInFiltering(false);
+                                messageSpy.spyMessage(DeviceContext.class, MessageSpy.STATISTIC_GROUP.OFJ_BACKPRESSURE_OFF);
+
+                                filteringPacketIn = false;
+                                LOG.debug("PacketIn filtering off: {}, outstanding: {}", connectionAdapter.getRemoteAddress(), outstandingNotificationsAmount);
+                            }
+                        }
+                    }
+                }
+        );
     }
 
     @Override
@@ -380,19 +345,28 @@ public class DeviceContextImpl implements DeviceContext {
     }
 
     @Override
-    public void close() throws Exception {
-        for (Map.Entry<Long, RequestContext> entry : requests.entrySet()) {
-            entry.getValue().close();
-        }
+    public void close() {
+        deviceState.setValid(false);
+
+        LOG.trace("Removing node {} from operational DS.", getDeviceState().getNodeId());
+        addDeleteToTxChain(LogicalDatastoreType.OPERATIONAL, getDeviceState().getNodeInstanceIdentifier());
+
+        deviceGroupRegistry.close();
+        deviceFlowRegistry.close();
+        deviceMeterRegistry.close();
+
         if (primaryConnectionContext.getConnectionAdapter().isAlive()) {
+            primaryConnectionContext.setConnectionState(ConnectionContext.CONNECTION_STATE.RIP);
             primaryConnectionContext.getConnectionAdapter().disconnect();
         }
-        for (ConnectionContext connectionContext : auxiliaryConnectionContexts.values()) {
+        for (final ConnectionContext connectionContext : auxiliaryConnectionContexts.values()) {
             if (connectionContext.getConnectionAdapter().isAlive()) {
-                primaryConnectionContext.getConnectionAdapter().disconnect();
+                connectionContext.getConnectionAdapter().disconnect();
             }
         }
-        deviceContextClosedHandler.onDeviceContextClosed(this);
+        for (final DeviceContextClosedHandler deviceContextClosedHandler : closeHandlers) {
+            deviceContextClosedHandler.onDeviceContextClosed(this);
+        }
     }
 
     @Override
@@ -400,38 +374,16 @@ public class DeviceContextImpl implements DeviceContext {
         if (this.getPrimaryConnectionContext().equals(connectionContext)) {
             try {
                 close();
-            } catch (Exception e) {
+            } catch (final Exception e) {
                 LOG.trace("Error closing device context.");
             }
             if (null != deviceDisconnectedHandler) {
                 deviceDisconnectedHandler.onDeviceDisconnected(connectionContext);
             }
         } else {
-            auxiliaryConnectionContexts.remove(connectionContext);
-        }
-    }
-
-
-    private class XidGenerator {
-
-        private final AtomicLong xid = new AtomicLong(0);
-
-        public Xid generate() {
-            return new Xid(xid.incrementAndGet());
-        }
-    }
-
-    @Override
-    public RequestContext extractNextOutstandingMessage(final long barrierXid) {
-        RequestContext nextMessage = null;
-        final Iterator<Long> keyIterator = requests.keySet().iterator();
-        if (keyIterator.hasNext()) {
-            final Long oldestXid = keyIterator.next();
-            if (oldestXid < barrierXid) {
-                nextMessage = requests.remove(oldestXid);
-            }
+            final SwitchConnectionDistinguisher connectionDistinguisher = createConnectionDistinguisher(connectionContext);
+            auxiliaryConnectionContexts.remove(connectionDistinguisher);
         }
-        return nextMessage;
     }
 
     @Override
@@ -445,10 +397,15 @@ public class DeviceContextImpl implements DeviceContext {
     }
 
     @Override
-    public void setNotificationService(final NotificationProviderService notificationServiceParam) {
+    public void setNotificationService(final NotificationService notificationServiceParam) {
         notificationService = notificationServiceParam;
     }
 
+    @Override
+    public void setNotificationPublishService(final NotificationPublishService notificationPublishService) {
+        this.notificationPublishService = notificationPublishService;
+    }
+
     @Override
     public MessageSpy getMessageSpy() {
         return messageSpy;
@@ -460,7 +417,25 @@ public class DeviceContextImpl implements DeviceContext {
     }
 
     @Override
-    public void setDeviceContextClosedHandler(final DeviceContextClosedHandler deviceContextClosedHandler) {
-        this.deviceContextClosedHandler = deviceContextClosedHandler;
+    public void addDeviceContextClosedHandler(final DeviceContextClosedHandler deviceContextClosedHandler) {
+        this.closeHandlers.add(deviceContextClosedHandler);
+    }
+
+    @Override
+    public void startGatheringOperationsToOneTransaction() {
+        txChainManager.startGatheringOperationsToOneTransaction();
+    }
+
+    @Override
+    public void commitOperationsGatheredInOneTransaction() {
+        txChainManager.commitOperationsGatheredInOneTransaction();
+    }
+
+    @Override
+    public void onPublished() {
+        primaryConnectionContext.getConnectionAdapter().setPacketInFiltering(false);
+        for (ConnectionContext switchAuxConnectionContext : auxiliaryConnectionContexts.values()) {
+            switchAuxConnectionContext.getConnectionAdapter().setPacketInFiltering(false);
+        }
     }
 }