Merge "Move a Timer (scheduler) Submit Transaction from TxChain"
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / device / DeviceManagerImpl.java
index 45bf8d7f3d67b955c686b97c94a07cde9cadfd91..40020aee7cc0601a4950e9cacae6da52a6e08f1d 100644 (file)
@@ -7,6 +7,8 @@
  */
 package org.opendaylight.openflowplugin.impl.device;
 
+import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
+
 import com.google.common.base.Preconditions;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
@@ -14,7 +16,17 @@ import com.google.common.util.concurrent.JdkFutureAdapters;
 import com.google.common.util.concurrent.ListenableFuture;
 import com.google.common.util.concurrent.SettableFuture;
 import io.netty.util.HashedWheelTimer;
+import java.math.BigInteger;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.CheckForNull;
+import javax.annotation.Nonnull;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
@@ -24,19 +36,28 @@ import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
 import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
 import org.opendaylight.openflowplugin.api.openflow.device.Xid;
-import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceContextReadyHandler;
+import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
 import org.opendaylight.openflowplugin.api.openflow.device.handlers.MultiMsgCollector;
-import org.opendaylight.openflowplugin.api.openflow.rpc.RpcManager;
 import org.opendaylight.openflowplugin.impl.common.MultipartRequestInputFactory;
 import org.opendaylight.openflowplugin.impl.common.NodeStaticReplyTranslatorUtil;
 import org.opendaylight.openflowplugin.impl.device.listener.OpenflowProtocolListenerFullImpl;
 import org.opendaylight.openflowplugin.impl.rpc.RequestContextImpl;
+import org.opendaylight.openflowplugin.impl.services.OFJResult2RequestCtxFuture;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsData;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsDataBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.NodeGroupFeatures;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorUpdated;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodesBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterFeatures;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
@@ -44,26 +65,22 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyDescCase;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyGroupFeaturesCase;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyMeterFeaturesCase;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyPortDescCase;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyTableFeaturesCase;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.desc._case.MultipartReplyDesc;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group.features._case.MultipartReplyGroupFeatures;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.features._case.MultipartReplyMeterFeatures;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.desc._case.MultipartReplyPortDesc;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.desc._case.multipart.reply.port.desc.Ports;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table.features._case.MultipartReplyTableFeatures;
+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.table.features.TableFeatures;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.common.RpcError;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import javax.annotation.CheckForNull;
-import javax.annotation.Nonnull;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
 
 /**
  *
@@ -74,26 +91,30 @@ public class DeviceManagerImpl implements DeviceManager {
 
     private static final long TICK_DURATION = 500; // 0.5 sec.
 
-    private final RpcManager rpcManager;
     private final DataBroker dataBroker;
     private final HashedWheelTimer hashedWheelTimer;
     private RequestContextStack dummyRequestContextStack;
     private TranslatorLibrary translatorLibrary;
+    private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
+    private NotificationProviderService notificationService;
 
 
-    public DeviceManagerImpl(@Nonnull final RpcManager rpcManager, @Nonnull final DataBroker dataBroker) {
-        this.rpcManager = Preconditions.checkNotNull(rpcManager);
+    public DeviceManagerImpl(@Nonnull final DataBroker dataBroker) {
         this.dataBroker = Preconditions.checkNotNull(dataBroker);
         hashedWheelTimer = new HashedWheelTimer(TICK_DURATION, TimeUnit.MILLISECONDS, 10);
+        /* merge empty nodes to oper DS to predict any problems with missing parent for Node */
+        final WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
+        tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class), new NodesBuilder().build());
+        tx.submit();
 
         dummyRequestContextStack = new RequestContextStack() {
             @Override
-            public <T> void forgetRequestContext(RequestContext<T> requestContext) {
+            public <T> void forgetRequestContext(final RequestContext<T> requestContext) {
                 //NOOP
             }
 
             @Override
-            public <T> SettableFuture<RpcResult<T>> storeOrFail(RequestContext<T> data) {
+            public <T> SettableFuture<RpcResult<T>> storeOrFail(final RequestContext<T> data) {
                 return data.getFuture();
             }
 
@@ -104,40 +125,60 @@ public class DeviceManagerImpl implements DeviceManager {
         };
     }
 
+    @Override
+    public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
+        deviceInitPhaseHandler = handler;
+    }
+
+    @Override
+    public void onDeviceContextLevelUp(final DeviceContext deviceContext) {
+        // final phase - we have to add new Device to MD-SAL DataStore
+        Preconditions.checkNotNull(deviceContext != null);
+        ((DeviceContextImpl) deviceContext).submitTransaction();
+        new BarrierTaskBuilder(deviceContext).buildAndFireBarrierTask();
+    }
+
     @Override
     public void deviceConnected(@CheckForNull final ConnectionContext connectionContext) {
         Preconditions.checkArgument(connectionContext != null);
+
         final DeviceState deviceState = new DeviceStateImpl(connectionContext.getFeatures(), connectionContext.getNodeId());
+
         final DeviceContextImpl deviceContext = new DeviceContextImpl(connectionContext, deviceState, dataBroker, hashedWheelTimer);
+
+        deviceContext.setNotificationService(notificationService);
+        deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, deviceState.getNodeInstanceIdentifier(), new NodeBuilder().setId(deviceState.getNodeId()).build());
+
         deviceContext.setTranslatorLibrary(translatorLibrary);
+
         final OpenflowProtocolListenerFullImpl messageListener = new OpenflowProtocolListenerFullImpl(
                 connectionContext.getConnectionAdapter(), deviceContext);
-        connectionContext.getConnectionAdapter().setMessageListener(messageListener);
 
-        final Xid nodeDescXid = deviceContext.getNextXid();
-        final ListenableFuture<Collection<MultipartReply>> replyDesc = getNodeStaticInfo(nodeDescXid, messageListener,
+        deviceContext.attachOpenflowMessageListener(messageListener);
+
+        final ListenableFuture<RpcResult<List<MultipartReply>>> replyDesc = getNodeStaticInfo(messageListener,
                 MultipartType.OFPMPDESC, deviceContext, deviceState.getNodeInstanceIdentifier(), deviceState.getVersion());
 
-        final Xid nodeMeterXid = deviceContext.getNextXid();
-        final ListenableFuture<Collection<MultipartReply>> replyMeterFeature = getNodeStaticInfo(nodeMeterXid, messageListener,
+        final ListenableFuture<RpcResult<List<MultipartReply>>> replyMeterFeature = getNodeStaticInfo(messageListener,
                 MultipartType.OFPMPMETERFEATURES, deviceContext, deviceState.getNodeInstanceIdentifier(), deviceState.getVersion());
 
-        final Xid nodeGroupXid = deviceContext.getNextXid();
-        final ListenableFuture<Collection<MultipartReply>> replyGroupFeatures = getNodeStaticInfo(nodeGroupXid, messageListener,
+        final ListenableFuture<RpcResult<List<MultipartReply>>> replyGroupFeatures = getNodeStaticInfo(messageListener,
                 MultipartType.OFPMPGROUPFEATURES, deviceContext, deviceState.getNodeInstanceIdentifier(), deviceState.getVersion());
 
-        final Xid nodeTableXid = deviceContext.getNextXid();
-        final ListenableFuture<Collection<MultipartReply>> replyTableFeatures = getNodeStaticInfo(nodeTableXid, messageListener,
+        final ListenableFuture<RpcResult<List<MultipartReply>>> replyTableFeatures = getNodeStaticInfo(messageListener,
                 MultipartType.OFPMPTABLEFEATURES, deviceContext, deviceState.getNodeInstanceIdentifier(), deviceState.getVersion());
 
-        final ListenableFuture<List<Collection<MultipartReply>>> deviceFeaturesFuture =
-                Futures.allAsList(Arrays.asList(replyDesc, replyMeterFeature, replyGroupFeatures, replyTableFeatures));
-        Futures.addCallback(deviceFeaturesFuture, new FutureCallback<List<Collection<MultipartReply>>>() {
+        final ListenableFuture<RpcResult<List<MultipartReply>>> replyPortDescription = getNodeStaticInfo(messageListener,
+                MultipartType.OFPMPPORTDESC, deviceContext, deviceState.getNodeInstanceIdentifier(), deviceState.getVersion());
+
+        final ListenableFuture<List<RpcResult<List<MultipartReply>>>> deviceFeaturesFuture =
+                Futures.allAsList(Arrays.asList(replyDesc, replyMeterFeature, replyGroupFeatures, replyTableFeatures, replyPortDescription));
+
+        Futures.addCallback(deviceFeaturesFuture, new FutureCallback<List<RpcResult<List<MultipartReply>>>>() {
             @Override
-            public void onSuccess(final List<Collection<MultipartReply>> result) {
-                // FIXME : add statistics
-                rpcManager.deviceConnected(deviceContext);
-                deviceContext.submitTransaction();
+            public void onSuccess(final List<RpcResult<List<MultipartReply>>> result) {
+                // wake up statistics
+                deviceInitPhaseHandler.onDeviceContextLevelUp(deviceContext);
             }
 
             @Override
@@ -147,11 +188,6 @@ public class DeviceManagerImpl implements DeviceManager {
         });
     }
 
-    @Override
-    public void addRequestContextReadyHandler(final DeviceContextReadyHandler deviceContextReadyHandler) {
-        // TODO Auto-generated method stub
-    }
-
     @Override
     public TranslatorLibrary oook() {
         return translatorLibrary;
@@ -162,28 +198,30 @@ public class DeviceManagerImpl implements DeviceManager {
         this.translatorLibrary = translatorLibrary;
     }
 
-    private ListenableFuture<Collection<MultipartReply>> getNodeStaticInfo(final Xid xid,
-                                                                           final MultiMsgCollector multiMsgCollector, final MultipartType type, final DeviceContext dContext,
-                                                                           final InstanceIdentifier<Node> nodeII, final short version) {
-        final ListenableFuture<Collection<MultipartReply>> future = multiMsgCollector.registerMultipartMsg(xid.getValue());
+    private ListenableFuture<RpcResult<List<MultipartReply>>> getNodeStaticInfo(final MultiMsgCollector multiMsgCollector, final MultipartType type, final DeviceContext deviceContext,
+                                                                                final InstanceIdentifier<Node> nodeII, final short version) {
 
-        RequestContext<List<MultipartReply>> requestContext = dummyRequestContextStack.createRequestContext();
-        dContext.hookRequestCtx(xid, requestContext);
+        final Xid xid = deviceContext.getNextXid();
+        final RequestContext<List<MultipartReply>> requestContext = dummyRequestContextStack.createRequestContext();
+        requestContext.setXid(xid);
+        multiMsgCollector.registerMultipartXid(xid.getValue());
         Futures.addCallback(requestContext.getFuture(), new FutureCallback<RpcResult<List<MultipartReply>>>() {
             @Override
             public void onSuccess(final RpcResult<List<MultipartReply>> rpcResult) {
-                List<MultipartReply> result = rpcResult.getResult();
+                final List<MultipartReply> result = rpcResult.getResult();
                 if (result != null) {
-                    translateAndWriteReply(type, dContext, nodeII, result);
+                    translateAndWriteReply(type, deviceContext, nodeII, result);
                 } else {
-                    Iterator<RpcError> rpcErrorIterator = rpcResult.getErrors().iterator();
+                    final Iterator<RpcError> rpcErrorIterator = rpcResult.getErrors().iterator();
                     while (rpcErrorIterator.hasNext()) {
-                        Throwable t = rpcErrorIterator.next().getCause();
-                        LOG.info("Failed to retrieve static node {} info: {}", type, t.getMessage());
-                        LOG.trace("Detailed error:", t);
+                        final RpcError rpcError = rpcErrorIterator.next();
+                        LOG.info("Failed to retrieve static node {} info: {}", type, rpcError.getMessage());
+                        if (null != rpcError.getCause()) {
+                            LOG.trace("Detailed error:", rpcError.getCause());
+                        }
                     }
-                    if (MultipartType.OFPMPTABLE.equals(type)) {
-                        makeEmptyTables(dContext, nodeII, dContext.getPrimaryConnectionContext().getFeatures().getTables());
+                    if (MultipartType.OFPMPTABLEFEATURES.equals(type)) {
+                        makeEmptyTables(deviceContext, nodeII, deviceContext.getPrimaryConnectionContext().getFeatures().getTables());
                     }
                 }
             }
@@ -194,20 +232,12 @@ public class DeviceManagerImpl implements DeviceManager {
             }
         });
 
-        final Future<RpcResult<Void>> rpcFuture = dContext.getPrimaryConnectionContext().getConnectionAdapter()
-                .multipartRequest(MultipartRequestInputFactory.makeMultipartRequestInput(xid.getValue(), version, type));
-        Futures.addCallback(JdkFutureAdapters.listenInPoolThread(rpcFuture), new FutureCallback<RpcResult<Void>>() {
-            @Override
-            public void onSuccess(final RpcResult<Void> result) {
-                // NOOP
-            }
+        final ListenableFuture<RpcResult<Void>> rpcFuture = JdkFutureAdapters.listenInPoolThread(deviceContext.getPrimaryConnectionContext().getConnectionAdapter()
+                .multipartRequest(MultipartRequestInputFactory.makeMultipartRequestInput(xid.getValue(), version, type)));
+        final OFJResult2RequestCtxFuture OFJResult2RequestCtxFuture = new OFJResult2RequestCtxFuture(requestContext, deviceContext);
+        OFJResult2RequestCtxFuture.processResultFromOfJava(rpcFuture);
 
-            @Override
-            public void onFailure(final Throwable t) {
-                future.cancel(true);
-            }
-        });
-        return future;
+        return requestContext.getFuture();
     }
 
     // FIXME : remove after ovs tableFeatures fix
@@ -215,7 +245,8 @@ public class DeviceManagerImpl implements DeviceManager {
         for (int i = 0; i < nrOfTables; i++) {
             final short tId = (short) i;
             final InstanceIdentifier<Table> tableII = nodeII.augmentation(FlowCapableNode.class).child(Table.class, new TableKey(tId));
-            dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tableII, new TableBuilder().setId(tId).build());
+            final TableBuilder tableBuilder = new TableBuilder().setId(tId).addAugmentation(FlowTableStatisticsData.class, new FlowTableStatisticsDataBuilder().build());
+            dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tableII, tableBuilder.build());
         }
     }
 
@@ -239,7 +270,9 @@ public class DeviceManagerImpl implements DeviceManager {
                     for (final TableFeatures table : tables) {
                         final Short tableId = table.getTableId();
                         final InstanceIdentifier<Table> tableII = nodeII.augmentation(FlowCapableNode.class).child(Table.class, new TableKey(tableId));
-                        dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tableII, new TableBuilder().setId(tableId).setTableFeatures(Collections.singletonList(table)).build());
+                        final TableBuilder tableBuilder = new TableBuilder().setId(tableId).setTableFeatures(Collections.singletonList(table));
+                        tableBuilder.addAugmentation(FlowTableStatisticsData.class, new FlowTableStatisticsDataBuilder().build());
+                        dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tableII, tableBuilder.build());
                     }
                     break;
 
@@ -249,6 +282,9 @@ public class DeviceManagerImpl implements DeviceManager {
                     final NodeMeterFeatures mFeature = NodeStaticReplyTranslatorUtil.nodeMeterFeatureTranslator(meterFeatures);
                     final InstanceIdentifier<NodeMeterFeatures> mFeatureII = nodeII.augmentation(NodeMeterFeatures.class);
                     dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, mFeatureII, mFeature);
+                    if (0L < mFeature.getMeterFeatures().getMaxMeter().getValue()) {
+                        dContext.getDeviceState().isMetersAvailable();
+                    }
                     break;
 
                 case OFPMPGROUPFEATURES:
@@ -257,11 +293,30 @@ public class DeviceManagerImpl implements DeviceManager {
                     final NodeGroupFeatures gFeature = NodeStaticReplyTranslatorUtil.nodeGroupFeatureTranslator(groupFeatures);
                     final InstanceIdentifier<NodeGroupFeatures> gFeatureII = nodeII.augmentation(NodeGroupFeatures.class);
                     dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, gFeatureII, gFeature);
+                    dContext.getDeviceState().groupIsAvailable();
                     break;
 
+                case OFPMPPORTDESC:
+                    Preconditions.checkArgument(body instanceof MultipartReplyPortDescCase);
+                    final MultipartReplyPortDesc portDesc = ((MultipartReplyPortDescCase) body).getMultipartReplyPortDesc();
+                    for (final Ports port : portDesc.getPorts()) {
+                        final BigInteger dataPathId = dContext.getPrimaryConnectionContext().getFeatures().getDatapathId();
+                        final NodeConnectorUpdated portUpd = NodeStaticReplyTranslatorUtil.nodePortDescTranslator(port, dataPathId, dContext.getDeviceState().getVersion());
+                        final InstanceIdentifier<NodeConnector> connectorII = nodeII.child(NodeConnector.class, new NodeConnectorKey(portUpd.getId()));
+                        final NodeConnector connector = new NodeConnectorBuilder(portUpd).addAugmentation(FlowCapableNodeConnectorStatisticsData.class,
+                                new FlowCapableNodeConnectorStatisticsDataBuilder().build()).build();
+                        dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, connectorII, connector);
+                        //FlowCapableNodeConnectorBuilder
+                    }
+
                 default:
                     throw new IllegalArgumentException("Unnexpected MultipartType " + type);
             }
         }
     }
+
+    @Override
+    public void setNotificationService(final NotificationProviderService notificationServiceParam) {
+        notificationService = notificationServiceParam;
+    }
 }