ELAN FT Support for BE
[vpnservice.git] / mdsalutil / mdsalutil-impl / src / main / java / org / opendaylight / vpnservice / mdsalutil / internal / MDSALManager.java
index 20e74528831cc64eb1912d173d5e38f28f4a7be3..9c2915a0740932e78c5a2087ad628684219fa0a6 100644 (file)
@@ -1,30 +1,28 @@
 /*
- * Copyright (c) 2013 Ericsson AB.  All rights reserved.
+ * Copyright (c) 2015 - 2016 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
- *
  */
 
 package org.opendaylight.vpnservice.mdsalutil.internal;
 
 import java.math.BigInteger;
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.List;
-import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
 
 import org.opendaylight.vpnservice.mdsalutil.ActionInfo;
 import org.opendaylight.vpnservice.mdsalutil.ActionType;
 import org.opendaylight.vpnservice.mdsalutil.FlowEntity;
 import org.opendaylight.vpnservice.mdsalutil.GroupEntity;
 import org.opendaylight.vpnservice.mdsalutil.MDSALUtil;
-import org.opendaylight.vpnservice.mdsalutil.interfaces.IMdsalApiManager;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Match;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
 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.inventory.rev130819.tables.table.Flow;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
@@ -46,6 +44,7 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.opendaylight.vpnservice.mdsalutil.*;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
@@ -63,10 +62,8 @@ public class MDSALManager implements AutoCloseable {
     private DataBroker m_dataBroker;
 
     private PacketProcessingService m_packetProcessingService;
-
-    private final AtomicInteger m_atomicInteger = new AtomicInteger();
-
-    //TODO : IF ID MANAGER IS RQD
+    private ConcurrentMap<FlowInfoKey, Runnable> flowMap = new ConcurrentHashMap<FlowInfoKey, Runnable>();
+    private ConcurrentMap<GroupInfoKey, Runnable> groupMap = new ConcurrentHashMap<GroupInfoKey, Runnable> ();
 
     /**
      * Writes the flows and Groups to the MD SAL DataStore
@@ -80,61 +77,35 @@ public class MDSALManager implements AutoCloseable {
     public MDSALManager(final DataBroker db, PacketProcessingService pktProcService) {
         m_dataBroker = db;
         m_packetProcessingService = pktProcService;
-
+        s_logger.info( "MDSAL Manager Initialized ") ;
     }
 
-
     @Override
     public void close() throws Exception {
         s_logger.info("MDSAL Manager Closed");
     }
 
-
-    public void printTest() {
-
-        s_logger.info(" INTER MODULECOMMUNICATION IS WORKING!!!!");
-    }
-
     public void installFlow(FlowEntity flowEntity) {
 
         try {
-            s_logger.info("within installFlow {}", flowEntity.getDpnId());
+            s_logger.trace("InstallFlow for flowEntity {} ", flowEntity);
 
             if (flowEntity.getCookie() == null) {
-              //  s_logger.info("Helium_sync: Cookie is null");
-                flowEntity.setCookie(new BigInteger("0110000", 16));
+               flowEntity.setCookie(new BigInteger("0110000", 16));
             }
 
             FlowKey flowKey = new FlowKey( new FlowId(flowEntity.getFlowId()) );
 
             FlowBuilder flowbld = flowEntity.getFlowBuilder();
 
-            Flow flow = flowbld.build() ;
-
             Node nodeDpn = buildDpnNode(flowEntity.getDpnId());
-            InstanceIdentifier<Node> nodeInstanceId = InstanceIdentifier.builder(Nodes.class)
-                    .child(Node.class, nodeDpn.getKey()).build();
-
             InstanceIdentifier<Flow> flowInstanceId = InstanceIdentifier.builder(Nodes.class)
                     .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
                     .child(Table.class, new TableKey(flowEntity.getTableId())).child(Flow.class,flowKey).build();
 
-            String sTransactionUri = generateTransactionUri();
-
-            TableKey tableKey = new TableKey(flowEntity.getTableId() );
-            InstanceIdentifier<Table> tableInstanceId = InstanceIdentifier.create(Nodes.class).child(Node.class, nodeDpn.getKey())
-                    .augmentation(FlowCapableNode.class).child(Table.class, tableKey);
-            Table table = new TableBuilder().setKey(tableKey).setFlow(Collections.<Flow>emptyList()).build();
-
             WriteTransaction modification = m_dataBroker.newWriteOnlyTransaction();
 
-            //CHECK IF RQD
-           // modification.put(LogicalDatastoreType.CONFIGURATION, nodeInstanceId, nodeDpn, true);
-
-
-            modification.put(LogicalDatastoreType.CONFIGURATION, tableInstanceId, table);
-
-            modification.put(LogicalDatastoreType.CONFIGURATION, flowInstanceId, flowbld.build());
+            modification.put(LogicalDatastoreType.CONFIGURATION, flowInstanceId, flowbld.build(),true );
 
             CheckedFuture<Void,TransactionCommitFailedException> submitFuture  = modification.submit();
 
@@ -143,7 +114,7 @@ public class MDSALManager implements AutoCloseable {
                 @Override
                 public void onSuccess(final Void result) {
                     // Commited successfully
-                    s_logger.info( "Install Flow -- Committedsuccessfully ") ;
+                    s_logger.debug( "Install Flow -- Committedsuccessfully ") ;
                 }
 
                 @Override
@@ -160,26 +131,34 @@ public class MDSALManager implements AutoCloseable {
                 }
             });
         } catch (Exception e) {
-            s_logger.error("Could not install flow: {}, exception: {}", flowEntity, e.getMessage());
+            s_logger.error("Could not install flow: {}", flowEntity, e);
         }
     }
 
+    public CheckedFuture<Void,TransactionCommitFailedException> installFlow(BigInteger dpId, Flow flow) {
+        FlowKey flowKey = new FlowKey( new FlowId(flow.getId()) );
+        Node nodeDpn = buildDpnNode(dpId);
+        InstanceIdentifier<Flow> flowInstanceId = InstanceIdentifier.builder(Nodes.class)
+                .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
+                .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class,flowKey).build();
+        WriteTransaction modification = m_dataBroker.newWriteOnlyTransaction();
+        modification.put(LogicalDatastoreType.CONFIGURATION, flowInstanceId, flow, true);
+        return modification.submit();
+    }
+
     public void installGroup(GroupEntity groupEntity) {
         try {
             Group group = groupEntity.getGroupBuilder().build();
 
             Node nodeDpn = buildDpnNode(groupEntity.getDpnId());
-            InstanceIdentifier<Node> nodeInstanceId = InstanceIdentifier.builder(Nodes.class)
-                    .child(Node.class, nodeDpn.getKey()).build();
+
             InstanceIdentifier<Group> groupInstanceId = InstanceIdentifier.builder(Nodes.class)
                     .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
                     .child(Group.class, new GroupKey(new GroupId(groupEntity.getGroupId()))).build();
 
             WriteTransaction modification = m_dataBroker.newWriteOnlyTransaction();
 
-            //CHECK IF RQD
-         //   modification.put(LogicalDatastoreType.CONFIGURATION, nodeInstanceId, nodeDpn);
-            modification.put(LogicalDatastoreType.CONFIGURATION, groupInstanceId, group);
+            modification.put(LogicalDatastoreType.CONFIGURATION, groupInstanceId, group, true);
 
             CheckedFuture<Void,TransactionCommitFailedException> submitFuture  = modification.submit();
 
@@ -187,7 +166,7 @@ public class MDSALManager implements AutoCloseable {
                 @Override
                 public void onSuccess(final Void result) {
                     // Commited successfully
-                    s_logger.info( "Install Group -- Committedsuccessfully ") ;
+                    s_logger.debug( "Install Group -- Committedsuccessfully ") ;
                 }
 
                 @Override
@@ -204,13 +183,14 @@ public class MDSALManager implements AutoCloseable {
                 }
              });
            } catch (Exception e) {
-            s_logger.error("Could not install Group: {}, exception: {}", groupEntity, e.getMessage());
+            s_logger.error("Could not install Group: {}", groupEntity, e);
             throw e;
         }
     }
 
     public void removeFlow(FlowEntity flowEntity) {
         try {
+            s_logger.debug("Remove flow {}",flowEntity);
             Node nodeDpn = buildDpnNode(flowEntity.getDpnId());
             FlowKey flowKey = new FlowKey(new FlowId(flowEntity.getFlowId()));
             InstanceIdentifier<Flow> flowInstanceId = InstanceIdentifier.builder(Nodes.class)
@@ -219,7 +199,7 @@ public class MDSALManager implements AutoCloseable {
 
 
                 WriteTransaction modification = m_dataBroker.newWriteOnlyTransaction();
-                modification.delete(LogicalDatastoreType.CONFIGURATION,flowInstanceId );
+                modification.delete(LogicalDatastoreType.CONFIGURATION,flowInstanceId);
 
                 CheckedFuture<Void,TransactionCommitFailedException> submitFuture  = modification.submit();
 
@@ -227,7 +207,7 @@ public class MDSALManager implements AutoCloseable {
                     @Override
                     public void onSuccess(final Void result) {
                         // Commited successfully
-                        s_logger.info( "Delete Flow -- Committedsuccessfully ") ;
+                        s_logger.debug( "Delete Flow -- Committedsuccessfully ") ;
                     }
 
                     @Override
@@ -244,10 +224,22 @@ public class MDSALManager implements AutoCloseable {
 
                 });
         } catch (Exception e) {
-            s_logger.error("Could not remove Flow: {}, exception: {}", flowEntity, e.getMessage());
+            s_logger.error("Could not remove Flow: {}", flowEntity, e);
         }
     }
 
+    public CheckedFuture<Void,TransactionCommitFailedException> removeFlowNew(BigInteger dpnId, Flow flowEntity) {
+        s_logger.debug("Remove flow {}",flowEntity);
+        Node nodeDpn = buildDpnNode(dpnId);
+        FlowKey flowKey = new FlowKey(new FlowId(flowEntity.getId()));
+        InstanceIdentifier<Flow> flowInstanceId = InstanceIdentifier.builder(Nodes.class)
+                    .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
+                    .child(Table.class, new TableKey(flowEntity.getTableId())).child(Flow.class, flowKey).build();
+        WriteTransaction  modification = m_dataBroker.newWriteOnlyTransaction();
+        modification.delete(LogicalDatastoreType.CONFIGURATION,flowInstanceId );
+        return modification.submit();
+    }
+
     public void removeGroup(GroupEntity groupEntity) {
         try {
             Node nodeDpn = buildDpnNode(groupEntity.getDpnId());
@@ -265,7 +257,7 @@ public class MDSALManager implements AutoCloseable {
                 @Override
                 public void onSuccess(final Void result) {
                     // Commited successfully
-                    s_logger.info( "Install Group -- Committedsuccessfully ") ;
+                    s_logger.debug( "Install Group -- Committedsuccessfully ") ;
                 }
 
                 @Override
@@ -281,7 +273,7 @@ public class MDSALManager implements AutoCloseable {
                 }
             });
         } catch (Exception e) {
-            s_logger.error("Could not remove Group: {}, exception: {}", groupEntity, e.getMessage());
+            s_logger.error("Could not remove Group: {}", groupEntity, e);
         }
     }
 
@@ -290,44 +282,23 @@ public class MDSALManager implements AutoCloseable {
         installGroup(groupEntity);
     }
 
-    private String generateTransactionUri() {
-        long lTransactionIdOut = m_atomicInteger.incrementAndGet();
-
-        // TO DO Introduce this later
-      //  return "" + (lTransactionIdOut | m_lTransactionIdPrefix);
-        return "" + (lTransactionIdOut );
-    }
-/*
-    private String generateTransactionUriForFlow(long nTransactionId) {
-        long lTransactionIdOut = m_atomicInteger.incrementAndGet();
-        return Long.toString((lTransactionIdOut | m_lTransactionIdPrefix)) + EUtil.TRANSACTION_ID_SEPARATOR
-                + Long.toString(nTransactionId);
-    }
-*/
-
-    public void sendPacketOut(long lDpnId, int groupId, byte[] payload) {
+    public void sendPacketOut(BigInteger dpnId, int groupId, byte[] payload) {
 
         List<ActionInfo> actionInfos = new ArrayList<ActionInfo>();
         actionInfos.add(new ActionInfo(ActionType.group, new String[] { String.valueOf(groupId) }));
 
-        sendPacketOutWithActions(lDpnId, groupId, payload, actionInfos);
+        sendPacketOutWithActions(dpnId, groupId, payload, actionInfos);
     }
 
-    public void sendPacketOutWithActions(long lDpnId, long groupId, byte[] payload, List<ActionInfo> actionInfos) {
+    public void sendPacketOutWithActions(BigInteger dpnId, long groupId, byte[] payload, List<ActionInfo> actionInfos) {
 
-        m_packetProcessingService.transmitPacket(MDSALUtil.getPacketOut(actionInfos, payload, lDpnId,
-                getNodeConnRef("openflow:" + lDpnId, "0xfffffffd")));
+        m_packetProcessingService.transmitPacket(MDSALUtil.getPacketOut(actionInfos, payload, dpnId,
+                getNodeConnRef("openflow:" + dpnId, "0xfffffffd")));
     }
 
-    public void sendARPPacketOutWithActions(long lDpnId, byte[] payload, List<ActionInfo> actions) {
-        m_packetProcessingService.transmitPacket(MDSALUtil.getPacketOut(actions, payload, lDpnId,
-                getNodeConnRef("openflow:" + lDpnId, "0xfffffffd")));
-    }
-
-    private NodeKey getNodeKey(long dpId) {
-        String nodeId = "openflow:" + dpId;
-        NodeKey nodeKey = new NodeKey(new NodeId(nodeId));
-        return nodeKey;
+    public void sendARPPacketOutWithActions(BigInteger dpnId, byte[] payload, List<ActionInfo> actions) {
+        m_packetProcessingService.transmitPacket(MDSALUtil.getPacketOut(actions, payload, dpnId,
+                getNodeConnRef("openflow:" + dpnId, "0xfffffffd")));
     }
 
     public InstanceIdentifier<Node> nodeToInstanceId(Node node) {
@@ -353,16 +324,71 @@ public class MDSALManager implements AutoCloseable {
         return _nodeConnectorRef;
     }
 
-    private long getDpnIdFromNodeName(String nodeName) {
-        String dpId = nodeName.substring(nodeName.lastIndexOf(":") + 1);
-        return Long.parseLong(dpId);
-    }
-
-    private Node buildDpnNode(long lDpnId) {
-        NodeId nodeId = new NodeId("openflow:" + lDpnId);
+    private Node buildDpnNode(BigInteger dpnId) {
+        NodeId nodeId = new NodeId("openflow:" + dpnId);
         Node nodeDpn = new NodeBuilder().setId(nodeId).setKey(new NodeKey(nodeId)).build();
 
         return nodeDpn;
     }
 
+    public void syncSetUpFlow(FlowEntity flowEntity, long delay, boolean isRemove) {
+        s_logger.trace("syncSetUpFlow for flowEntity {} ", flowEntity);
+        if (flowEntity.getCookie() == null) {
+            flowEntity.setCookie(new BigInteger("0110000", 16));
+        }
+        Flow flow = flowEntity.getFlowBuilder().build();
+        String flowId = flowEntity.getFlowId();
+        BigInteger dpId = flowEntity.getDpnId();
+        short tableId = flowEntity.getTableId();
+        Match matches = flow.getMatch();
+        FlowKey flowKey = new FlowKey( new FlowId(flowId));
+        Node nodeDpn = buildDpnNode(dpId);
+        InstanceIdentifier<Flow> flowInstanceId = InstanceIdentifier.builder(Nodes.class)
+                .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
+                .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
+        Runnable notifyTask = new NotifyTask();
+        FlowInfoKey flowInfoKey = new FlowInfoKey(dpId, tableId, matches, flowId);
+        synchronized (flowInfoKey.toString().intern()) {
+            flowMap.put(flowInfoKey, notifyTask);
+            if (isRemove) {
+                MDSALUtil.syncDelete(m_dataBroker, LogicalDatastoreType.CONFIGURATION, flowInstanceId);
+            } else {
+                MDSALUtil.syncWrite(m_dataBroker, LogicalDatastoreType.CONFIGURATION, flowInstanceId, flow);
+            }
+            synchronized (notifyTask) {
+                try {
+                    notifyTask.wait(delay);
+                } catch (InterruptedException e){}
+            }
+        }
+    }
+
+    public void syncSetUpGroup(GroupEntity groupEntity, long delayTime, boolean isRemove) {
+        s_logger.trace("syncSetUpGroup for groupEntity {} ", groupEntity);
+        Group group = groupEntity.getGroupBuilder().build();
+        BigInteger dpId = groupEntity.getDpnId();
+        Node nodeDpn = buildDpnNode(dpId);
+        long groupId = groupEntity.getGroupId();
+        GroupKey groupKey = new GroupKey(new GroupId(groupId));
+        InstanceIdentifier<Group> groupInstanceId = InstanceIdentifier.builder(Nodes.class)
+                .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
+                .child(Group.class, groupKey).build();
+        Runnable notifyTask = new NotifyTask();
+        GroupInfoKey groupInfoKey = new GroupInfoKey(dpId, groupId);
+        synchronized (groupInfoKey.toString().intern()) {
+            s_logger.trace("syncsetupGroupKey groupKey {}", groupInfoKey);
+            groupMap.put(groupInfoKey, notifyTask);
+            if (isRemove) {
+                MDSALUtil.syncDelete(m_dataBroker, LogicalDatastoreType.CONFIGURATION, groupInstanceId);
+            } else {
+                MDSALUtil.syncWrite(m_dataBroker, LogicalDatastoreType.CONFIGURATION, groupInstanceId, group);
+            }
+            synchronized (notifyTask) {
+                try {
+                    notifyTask.wait(delayTime);
+                } catch (InterruptedException e){}
+            }
+        }
+    }
+
 }