Switch to MD-SAL APIs
[openflowplugin.git] / applications / forwardingrules-manager / src / main / java / org / opendaylight / openflowplugin / applications / frm / impl / GroupForwarder.java
index f5ccb19947c6bea17c8f6da4681c104b4c0a6a56..e2ec86f67badea0399505d99ee6d994fe6f07b82 100644 (file)
@@ -1,4 +1,4 @@
-/**
+/*
  * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
@@ -7,25 +7,31 @@
  */
 package org.opendaylight.openflowplugin.applications.frm.impl;
 
-import com.google.common.base.Preconditions;
-import com.google.common.util.concurrent.CheckedFuture;
+import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.getActiveBundle;
+import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.getNodeIdFromNodeIdentifier;
+
+import com.google.common.util.concurrent.FluentFuture;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.MoreExecutors;
 import java.util.concurrent.Future;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.infrautils.utils.concurrent.JdkFutures;
+import org.opendaylight.mdsal.binding.api.DataBroker;
+import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
+import org.opendaylight.mdsal.binding.api.WriteTransaction;
+import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
-import org.opendaylight.openflowplugin.common.wait.SimpleTaskRetryLooper;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupInput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupInputBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupOutput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.RemoveGroupInputBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.RemoveGroupOutput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupInput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupInputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.group.update.OriginalGroupBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.group.update.UpdatedGroupBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
@@ -34,9 +40,11 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroup;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroupBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroupKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleId;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.common.RpcResult;
@@ -45,29 +53,30 @@ import org.slf4j.LoggerFactory;
 
 /**
  * GroupForwarder It implements
- * {@link org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener}
+ * {@link org.opendaylight.mdsal.binding.api.DataTreeChangeListener}
  * for WildCardedPath to {@link Group} and ForwardingRulesCommiter interface for
  * methods: add, update and remove {@link Group} processing for
- * {@link org.opendaylight.controller.md.sal.binding.api.DataTreeModification}.
+ * {@link org.opendaylight.mdsal.binding.api.DataTreeModification}.
  */
 public class GroupForwarder extends AbstractListeningCommiter<Group> {
 
     private static final Logger LOG = LoggerFactory.getLogger(GroupForwarder.class);
-    private final DataBroker dataBroker;
     private ListenerRegistration<GroupForwarder> listenerRegistration;
+    private final BundleGroupForwarder bundleGroupForwarder;
 
-    @SuppressWarnings("IllegalCatch")
     public GroupForwarder(final ForwardingRulesManager manager, final DataBroker db) {
-        super(manager);
-        dataBroker = Preconditions.checkNotNull(db, "DataBroker can not be null!");
-        final DataTreeIdentifier<Group> treeId = new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,
+        super(manager, db);
+        this.bundleGroupForwarder = new BundleGroupForwarder(manager);
+    }
+
+    @SuppressWarnings("IllegalCatch")
+    @Override
+    public void registerListener() {
+        final DataTreeIdentifier<Group> treeId = DataTreeIdentifier.create(LogicalDatastoreType.CONFIGURATION,
                 getWildCardPath());
 
         try {
-            SimpleTaskRetryLooper looper = new SimpleTaskRetryLooper(ForwardingRulesManagerImpl.STARTUP_LOOP_TICK,
-                    ForwardingRulesManagerImpl.STARTUP_LOOP_MAX_RETRIES);
-            listenerRegistration = looper
-                    .loopUntilNoException(() -> db.registerDataTreeChangeListener(treeId, GroupForwarder.this));
+            listenerRegistration = dataBroker.registerDataTreeChangeListener(treeId, GroupForwarder.this);
         } catch (final Exception e) {
             LOG.warn("FRM Group DataTreeChange listener registration fail!");
             LOG.debug("FRM Group DataTreeChange listener registration fail ..", e);
@@ -75,6 +84,11 @@ public class GroupForwarder extends AbstractListeningCommiter<Group> {
         }
     }
 
+    @Override
+    public  void deregisterListener() {
+        close();
+    }
+
     @Override
     public void close() {
         if (listenerRegistration != null) {
@@ -92,14 +106,25 @@ public class GroupForwarder extends AbstractListeningCommiter<Group> {
     @Override
     public void remove(final InstanceIdentifier<Group> identifier, final Group removeDataObj,
             final InstanceIdentifier<FlowCapableNode> nodeIdent) {
+        BundleId bundleId = getActiveBundle(nodeIdent, provider);
+        if (bundleId != null) {
+            bundleGroupForwarder.remove(identifier, removeDataObj, nodeIdent, bundleId);
+        } else {
+            final Group group = removeDataObj;
+            final RemoveGroupInputBuilder builder = new RemoveGroupInputBuilder(group);
+            final NodeId nodeId = getNodeIdFromNodeIdentifier(nodeIdent);
 
-        final Group group = removeDataObj;
-        final RemoveGroupInputBuilder builder = new RemoveGroupInputBuilder(group);
+            builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
+            builder.setGroupRef(new GroupRef(identifier));
+            builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
 
-        builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
-        builder.setGroupRef(new GroupRef(identifier));
-        builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
-        this.provider.getSalGroupService().removeGroup(builder.build());
+            final ListenableFuture<RpcResult<RemoveGroupOutput>> resultFuture =
+                    this.provider.getSalGroupService().removeGroup(builder.build());
+            Futures.addCallback(resultFuture,
+                    new RemoveGroupCallBack(removeDataObj.getGroupId().getValue(), nodeId),
+                    MoreExecutors.directExecutor());
+            JdkFutures.addErrorLogging(resultFuture, LOG, "removeGroup");
+        }
     }
 
     // TODO: Pull this into ForwardingRulesCommiter and override it here
@@ -119,31 +144,56 @@ public class GroupForwarder extends AbstractListeningCommiter<Group> {
     @Override
     public void update(final InstanceIdentifier<Group> identifier, final Group original, final Group update,
             final InstanceIdentifier<FlowCapableNode> nodeIdent) {
-
-        final Group originalGroup = original;
-        final Group updatedGroup = update;
-        final UpdateGroupInputBuilder builder = new UpdateGroupInputBuilder();
-
-        builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
-        builder.setGroupRef(new GroupRef(identifier));
-        builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
-        builder.setUpdatedGroup(new UpdatedGroupBuilder(updatedGroup).build());
-        builder.setOriginalGroup(new OriginalGroupBuilder(originalGroup).build());
-
-        this.provider.getSalGroupService().updateGroup(builder.build());
+        BundleId bundleId = getActiveBundle(nodeIdent, provider);
+        if (bundleId != null) {
+            bundleGroupForwarder.update(identifier, original, update, nodeIdent, bundleId);
+        } else {
+            final NodeId nodeId = getNodeIdFromNodeIdentifier(nodeIdent);
+            nodeConfigurator.enqueueJob(nodeId.getValue(), () -> {
+                final Group originalGroup = original;
+                final Group updatedGroup = update;
+                final UpdateGroupInputBuilder builder = new UpdateGroupInputBuilder();
+                builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
+                builder.setGroupRef(new GroupRef(identifier));
+                builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
+                builder.setUpdatedGroup(new UpdatedGroupBuilder(updatedGroup).build());
+                builder.setOriginalGroup(new OriginalGroupBuilder(originalGroup).build());
+                UpdateGroupInput updateGroupInput = builder.build();
+                final ListenableFuture<RpcResult<UpdateGroupOutput>> resultFuture;
+                resultFuture = this.provider.getSalGroupService().updateGroup(updateGroupInput);
+                JdkFutures.addErrorLogging(resultFuture, LOG, "updateGroup");
+                Futures.addCallback(resultFuture,
+                        new UpdateGroupCallBack(updateGroupInput.getOriginalGroup().getGroupId().getValue(), nodeId),
+                        MoreExecutors.directExecutor());
+                return resultFuture;
+            });
+        }
     }
 
     @Override
-    public Future<RpcResult<AddGroupOutput>> add(final InstanceIdentifier<Group> identifier, final Group addDataObj,
+    public Future<? extends RpcResult<?>> add(final InstanceIdentifier<Group> identifier, final Group addDataObj,
             final InstanceIdentifier<FlowCapableNode> nodeIdent) {
-
-        final Group group = addDataObj;
-        final AddGroupInputBuilder builder = new AddGroupInputBuilder(group);
-
-        builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
-        builder.setGroupRef(new GroupRef(identifier));
-        builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
-        return this.provider.getSalGroupService().addGroup(builder.build());
+        BundleId bundleId = getActiveBundle(nodeIdent, provider);
+        if (bundleId != null) {
+            return bundleGroupForwarder.add(identifier, addDataObj, nodeIdent, bundleId);
+        } else {
+            final NodeId nodeId = getNodeIdFromNodeIdentifier(nodeIdent);
+            return nodeConfigurator
+                    .enqueueJob(nodeId.getValue(), () -> {
+                        final Group group = addDataObj;
+                        final AddGroupInputBuilder builder = new AddGroupInputBuilder(group);
+                        builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
+                        builder.setGroupRef(new GroupRef(identifier));
+                        builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
+                        AddGroupInput addGroupInput = builder.build();
+                        final ListenableFuture<RpcResult<AddGroupOutput>> resultFuture;
+                        resultFuture = this.provider.getSalGroupService().addGroup(addGroupInput);
+                        Futures.addCallback(resultFuture,
+                                new AddGroupCallBack(addGroupInput.getGroupId().getValue(), nodeId),
+                                MoreExecutors.directExecutor());
+                        return resultFuture;
+                    });
+        }
     }
 
     @Override
@@ -166,14 +216,14 @@ public class GroupForwarder extends AbstractListeningCommiter<Group> {
         writeTransaction.put(LogicalDatastoreType.CONFIGURATION, getStaleGroupInstanceIdentifier(staleGroup, nodeIdent),
                 staleGroup, false);
 
-        CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTransaction.submit();
+        FluentFuture<?> submitFuture = writeTransaction.commit();
         handleStaleGroupResultFuture(submitFuture);
     }
 
-    private void handleStaleGroupResultFuture(CheckedFuture<Void, TransactionCommitFailedException> submitFuture) {
-        Futures.addCallback(submitFuture, new FutureCallback<Void>() {
+    private void handleStaleGroupResultFuture(FluentFuture<?> submitFuture) {
+        submitFuture.addCallback(new FutureCallback<Object>() {
             @Override
-            public void onSuccess(Void result) {
+            public void onSuccess(Object result) {
                 LOG.debug("Stale Group creation success");
             }
 
@@ -181,7 +231,7 @@ public class GroupForwarder extends AbstractListeningCommiter<Group> {
             public void onFailure(Throwable throwable) {
                 LOG.error("Stale Group creation failed {}", throwable);
             }
-        });
+        }, MoreExecutors.directExecutor());
 
     }
 
@@ -191,4 +241,82 @@ public class GroupForwarder extends AbstractListeningCommiter<Group> {
         return nodeIdent.child(StaleGroup.class, new StaleGroupKey(new GroupId(staleGroup.getGroupId())));
     }
 
+    private final class AddGroupCallBack implements FutureCallback<RpcResult<AddGroupOutput>> {
+        private final Long groupId;
+        private final NodeId nodeId;
+
+        private AddGroupCallBack(final Long groupId, final NodeId nodeId) {
+            this.groupId = groupId;
+            this.nodeId = nodeId;
+        }
+
+        @Override
+        public void onSuccess(RpcResult<AddGroupOutput> result) {
+            if (result.isSuccessful()) {
+                provider.getDevicesGroupRegistry().storeGroup(nodeId, groupId);
+                LOG.debug("Group add with id {} finished without error for node {}", groupId, nodeId);
+            } else {
+                LOG.debug("Group add with id {} failed for node {} with error {}", groupId, nodeId,
+                        result.getErrors());
+            }
+        }
+
+        @Override
+        public void onFailure(Throwable throwable) {
+            LOG.error("Service call for adding group {} failed for node with error {}", groupId, nodeId, throwable);
+        }
+    }
+
+    private final class UpdateGroupCallBack implements FutureCallback<RpcResult<UpdateGroupOutput>> {
+        private final Long groupId;
+        private final NodeId nodeId;
+
+        private UpdateGroupCallBack(final Long groupId, final NodeId nodeId) {
+            this.groupId = groupId;
+            this.nodeId = nodeId;
+        }
+
+        @Override
+        public void onSuccess(RpcResult<UpdateGroupOutput> result) {
+            if (result.isSuccessful()) {
+                provider.getDevicesGroupRegistry().storeGroup(nodeId, groupId);
+                LOG.debug("Group update with id {} finished without error for node {}", groupId, nodeId);
+            } else {
+                LOG.debug("Group update with id {} failed for node {} with error {}", groupId, nodeId,
+                        result.getErrors().toString());
+            }
+        }
+
+        @Override
+        public void onFailure(Throwable throwable) {
+            LOG.error("Service call for updating group {} failed for node {} with", groupId, nodeId,
+                    throwable);
+        }
+    }
+
+    private final class RemoveGroupCallBack implements FutureCallback<RpcResult<RemoveGroupOutput>> {
+        private final Long groupId;
+        private final NodeId nodeId;
+
+        private RemoveGroupCallBack(final Long groupId, final NodeId nodeId) {
+            this.groupId = groupId;
+            this.nodeId = nodeId;
+        }
+
+        @Override
+        public void onSuccess(RpcResult<RemoveGroupOutput> result) {
+            if (result.isSuccessful()) {
+                LOG.debug("Group remove with id {} finished without error for node {}", groupId, nodeId);
+                provider.getDevicesGroupRegistry().removeGroup(nodeId, groupId);
+            } else {
+                LOG.debug("Group remove with id {} failed for node {} with error {}", groupId, nodeId,
+                        result.getErrors().toString());
+            }
+        }
+
+        @Override
+        public void onFailure(Throwable throwable) {
+            LOG.error("Service call for removing group {} failed for node with error {}", groupId, nodeId, throwable);
+        }
+    }
 }