Merge "added containermanager shell feature"
[controller.git] / opendaylight / containermanager / implementation / src / main / java / org / opendaylight / controller / containermanager / internal / ContainerManager.java
index 19341459b138274d084c9f30347617c95406a834..98378e81354742327e912199a44619febbaa5905 100644 (file)
@@ -9,7 +9,6 @@
 
 package org.opendaylight.controller.containermanager.internal;
 
-import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.ObjectInputStream;
@@ -24,21 +23,29 @@ import java.util.Locale;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.CopyOnWriteArrayList;
 
 import org.eclipse.osgi.framework.console.CommandInterpreter;
 import org.eclipse.osgi.framework.console.CommandProvider;
+import org.opendaylight.controller.appauth.authorization.Authorization;
 import org.opendaylight.controller.clustering.services.CacheConfigException;
 import org.opendaylight.controller.clustering.services.CacheExistException;
 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
 import org.opendaylight.controller.clustering.services.IClusterGlobalServices;
 import org.opendaylight.controller.clustering.services.IClusterServices;
+import org.opendaylight.controller.configuration.ConfigurationObject;
 import org.opendaylight.controller.configuration.IConfigurationAware;
 import org.opendaylight.controller.configuration.IConfigurationService;
+import org.opendaylight.controller.containermanager.ContainerChangeEvent;
+import org.opendaylight.controller.containermanager.ContainerConfig;
+import org.opendaylight.controller.containermanager.ContainerData;
+import org.opendaylight.controller.containermanager.ContainerFlowChangeEvent;
+import org.opendaylight.controller.containermanager.ContainerFlowConfig;
 import org.opendaylight.controller.containermanager.IContainerAuthorization;
 import org.opendaylight.controller.containermanager.IContainerManager;
+import org.opendaylight.controller.containermanager.IContainerManagerShell;
+import org.opendaylight.controller.containermanager.NodeConnectorsChangeEvent;
 import org.opendaylight.controller.sal.authorization.AppRoleLevel;
 import org.opendaylight.controller.sal.authorization.Privilege;
 import org.opendaylight.controller.sal.authorization.Resource;
@@ -56,8 +63,6 @@ import org.opendaylight.controller.sal.utils.GlobalConstants;
 import org.opendaylight.controller.sal.utils.IObjectReader;
 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
 import org.opendaylight.controller.sal.utils.NodeCreator;
-import org.opendaylight.controller.sal.utils.ObjectReader;
-import org.opendaylight.controller.sal.utils.ObjectWriter;
 import org.opendaylight.controller.sal.utils.ServiceHelper;
 import org.opendaylight.controller.sal.utils.Status;
 import org.opendaylight.controller.sal.utils.StatusCode;
@@ -65,22 +70,14 @@ import org.opendaylight.controller.topologymanager.ITopologyManager;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import org.opendaylight.controller.appauth.authorization.Authorization;
-import org.opendaylight.controller.containermanager.ContainerFlowChangeEvent;
-import org.opendaylight.controller.containermanager.ContainerFlowConfig;
-import org.opendaylight.controller.containermanager.NodeConnectorsChangeEvent;
-import org.opendaylight.controller.containermanager.ContainerChangeEvent;
-import org.opendaylight.controller.containermanager.ContainerConfig;
-import org.opendaylight.controller.containermanager.ContainerData;
-
 public class ContainerManager extends Authorization<String> implements IContainerManager, IObjectReader,
         CommandProvider, ICacheUpdateAware<String, Object>, IContainerInternal, IContainerAuthorization,
-        IConfigurationAware {
+        IConfigurationAware, IContainerManagerShell {
     private static final Logger logger = LoggerFactory.getLogger(ContainerManager.class);
-    private static String ROOT = GlobalConstants.STARTUPHOME.toString();
-    private static String containersFileName = ROOT + "containers.conf";
+    private static String CONTAINERS_FILE_NAME = "containers.conf";
     private static final String allContainersGroup = "allContainers";
     private IClusterGlobalServices clusterServices;
+    private IConfigurationService configurationService;
     /*
      * Collection containing the configuration objects. This is configuration
      * world: container names (also the map key) are maintained as they were
@@ -172,6 +169,16 @@ public class ContainerManager extends Authorization<String> implements IContaine
         }
     }
 
+    public void setConfigurationService(IConfigurationService service) {
+        logger.trace("Got configuration service set request {}", service);
+        this.configurationService = service;
+    }
+
+    public void unsetConfigurationService(IConfigurationService service) {
+        logger.trace("Got configuration service UNset request");
+        this.configurationService = null;
+    }
+
     private void allocateCaches() {
         logger.debug("Container Manager allocating caches");
 
@@ -291,7 +298,7 @@ public class ContainerManager extends Authorization<String> implements IContaine
         createDefaultAuthorizationGroups();
 
         // Read startup configuration and create local database
-        loadConfigurations();
+        loadContainerConfig();
     }
 
     public void destroy() {
@@ -621,9 +628,9 @@ public class ContainerManager extends Authorization<String> implements IContaine
                     String msg = null;
                     ContainerData other = containerData.get(otherContainerName);
                     if (flowSpecList.isEmpty()) {
-                        msg = String.format("Port %s is shared and flow spec is emtpy for this container", port);
+                        msg = String.format("Port %s is shared and flow spec is empty for this container", port);
                     } else if (other.isFlowSpecEmpty()) {
-                        msg = String.format("Port %s is shared and flow spec is emtpy for the other container", port);
+                        msg = String.format("Port %s is shared and flow spec is empty for the other container", port);
                     } else if (!checkCommonContainerFlow(flowSpecList, other.getContainerFlowSpecs()).isSuccess()) {
                         msg = String.format("Port %s is shared and other container has common flow spec", port);
                     }
@@ -729,49 +736,19 @@ public class ContainerManager extends Authorization<String> implements IContaine
         return flowSpecConfig;
     }
 
-    private void loadConfigurations() {
-        /*
-         * Read containers, container flows and finally containers' entries from file
-         * and program the database accordingly
-         */
-        if (containerConfigs.isEmpty()) {
-            loadContainerConfig();
-        }
-    }
-
     private Status saveContainerConfig() {
         return saveContainerConfigLocal();
     }
 
     public Status saveContainerConfigLocal() {
-        ObjectWriter objWriter = new ObjectWriter();
+        Status status = configurationService.persistConfiguration(
+                new ArrayList<ConfigurationObject>(containerConfigs.values()), CONTAINERS_FILE_NAME);
 
-        Status status = objWriter.write(new ConcurrentHashMap<String, ContainerConfig>(containerConfigs), containersFileName);
         if (!status.isSuccess()) {
             return new Status(StatusCode.INTERNALERROR, "Failed to save container configurations: "
                     + status.getDescription());
         }
-        return new Status(StatusCode.SUCCESS);
-    }
-
-    private void removeComponentsStartUpfiles(String containerName) {
-        String startupLocation = String.format("./%s", GlobalConstants.STARTUPHOME.toString());
-        String containerPrint = String.format("_%s.", containerName.toLowerCase(Locale.ENGLISH));
-
-        File directory = new File(startupLocation);
-        String[] fileList = directory.list();
-
-        logger.trace("Deleteing startup configuration files for container {}", containerName);
-        if (fileList != null) {
-            for (String fileName : fileList) {
-                if (fileName.contains(containerPrint)) {
-                    String fullPath = String.format("%s/%s", startupLocation, fileName);
-                    File file = new File(fullPath);
-                    boolean done = file.delete();
-                    logger.trace("{} {}", (done ? "Deleted: " : "Failed to delete: "), fileName);
-                }
-            }
-        }
+        return status;
     }
 
     /**
@@ -897,7 +874,7 @@ public class ContainerManager extends Authorization<String> implements IContaine
      */
     private void notifyContainerModeChange(boolean lastActionDelete, boolean notifyLocal) {
         if (lastActionDelete == false && containerConfigs.size() == 1) {
-            logger.info("First container Creation. Inform listeners");
+            logger.trace("First container Creation. Inform listeners");
             synchronized (this.iContainerListener) {
                 for (IContainerListener i : this.iContainerListener) {
                     i.containerModeUpdated(UpdateType.ADDED);
@@ -911,7 +888,7 @@ public class ContainerManager extends Authorization<String> implements IContaine
                 }
             }
         } else if (lastActionDelete == true && containerConfigs.isEmpty()) {
-            logger.info("Last container Deletion. Inform listeners");
+            logger.trace("Last container Deletion. Inform listeners");
             synchronized (this.iContainerListener) {
                 for (IContainerListener i : this.iContainerListener) {
                     i.containerModeUpdated(UpdateType.REMOVED);
@@ -929,7 +906,7 @@ public class ContainerManager extends Authorization<String> implements IContaine
 
     private Status addRemoveContainerEntries(String containerName, List<String> nodeConnectorsString, boolean delete) {
         // Construct action message
-        String action = String.format("Node conenctor(s) %s container %s: %s", delete ? "removal from" : "addition to",
+        String action = String.format("Node connector(s) %s container %s: %s", delete ? "removal from" : "addition to",
                 containerName, nodeConnectorsString);
 
         // Validity Check
@@ -1191,19 +1168,6 @@ public class ContainerManager extends Authorization<String> implements IContaine
             return status;
         }
 
-        /*
-         * This is a quick fix until configuration service becomes the
-         * centralized configuration management place. Here container manager will
-         * remove the startup files for all the bundles that are present in the
-         * container being deleted. Do the cleanup here in Container manger as do not
-         * want to put this temporary code in Configuration manager yet which is
-         * ODL.
-         */
-        if (delete) {
-            // TODO: remove when Config Mgr takes over
-            removeComponentsStartUpfiles(containerName);
-        }
-
         /*
          * Update Configuration: This will trigger the notifications on cache
          * update callback locally and on the other cluster nodes
@@ -1336,18 +1300,9 @@ public class ContainerManager extends Authorization<String> implements IContaine
         return ois.readObject();
     }
 
-    @SuppressWarnings("unchecked")
     private void loadContainerConfig() {
-        ObjectReader objReader = new ObjectReader();
-        ConcurrentMap<String, ContainerConfig> configMap = (ConcurrentMap<String, ContainerConfig>) objReader.read(this,
-                containersFileName);
-
-        if (configMap == null) {
-            return;
-        }
-
-        for (Map.Entry<String, ContainerConfig> configEntry : configMap.entrySet()) {
-            addContainer(configEntry.getValue());
+        for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, CONTAINERS_FILE_NAME)) {
+            addContainer((ContainerConfig) conf);
         }
     }
 
@@ -1665,4 +1620,286 @@ public class ContainerManager extends Authorization<String> implements IContaine
     public boolean inContainerMode() {
         return this.containerConfigs.size() > 0;
     }
+
+    public List<String> psc() {
+        List<String> result = new ArrayList<String>();
+        for (Map.Entry<String, ContainerConfig> entry : containerConfigs.entrySet()) {
+            ContainerConfig sc = entry.getValue();
+            result.add(String.format("%s: %s", sc.getContainerName(), sc.toString()));
+        }
+        result.add("Total number of containers: " + containerConfigs.entrySet().size());
+        return result;
+    }
+
+    public List<String> pfc() {
+        List<String> result = new ArrayList<String>();
+        for (Map.Entry<String, ContainerConfig> entry : containerConfigs.entrySet()) {
+            ContainerConfig sc = entry.getValue();
+            result.add(String.format("%s: %s", sc.getContainerName(), sc.getContainerFlowConfigs()));
+        }
+        return result;
+    }
+
+    public List<String> psd() {
+        List<String> result = new ArrayList<String>();
+        for (String containerName : containerData.keySet()) {
+            ContainerData sd = containerData.get(containerName);
+            for (Node sid : sd.getSwPorts().keySet()) {
+                Set<NodeConnector> s = sd.getSwPorts().get(sid);
+                result.add("\t" + sid + " : " + s);
+            }
+
+            for (ContainerFlow s : sd.getContainerFlowSpecs()) {
+                result.add("\t" + s.toString());
+            }
+        }
+        return result;
+    }
+
+    public List<String> psp() {
+        List<String> result = new ArrayList<String>();
+        for (NodeConnector sp : nodeConnectorToContainers.keySet()) {
+            result.add(nodeConnectorToContainers.get(sp).toString());
+        }
+        return result;
+    }
+
+    public List<String> psm() {
+        List<String> result = new ArrayList<String>();
+        for (Node sp : nodeToContainers.keySet()) {
+            result.add(nodeToContainers.get(sp).toString());
+        }
+        return result;
+    }
+
+    public List<String> addContainer(String arg1, String arg2) {
+        List<String> result = new ArrayList<String>();
+        String containerName = arg1;
+        if (containerName == null) {
+            result.add("Container Name not specified");
+            return result;
+        }
+        String staticVlan = arg2;
+        ContainerConfig containerConfig = new ContainerConfig(containerName, staticVlan, null, null);
+        result.add((this.addRemoveContainer(containerConfig, false)).toString());
+        return result;
+    }
+
+    public List<String> createContainer(String arg1, String arg2) {
+        List<String> result = new ArrayList<String>();
+        String containerName = arg1;
+        if (containerName == null) {
+            result.add("Container Name not specified");
+            return result;
+        }
+        String staticVlan = arg2;
+        if (staticVlan == null) {
+            result.add("Static Vlan not specified");
+            return result;
+        }
+        List<String> ports = new ArrayList<String>();
+        for (long l = 1L; l < 10L; l++) {
+            ports.add(NodeConnectorCreator.createOFNodeConnector((short) 1, NodeCreator.createOFNode(l)).toString());
+        }
+        List<ContainerFlowConfig> cFlowList = new ArrayList<ContainerFlowConfig>();
+        cFlowList.add(this.createSampleContainerFlowConfig("tcp", true));
+        ContainerConfig containerConfig = new ContainerConfig(containerName, staticVlan, ports, cFlowList);
+        result.add((this.addRemoveContainer(containerConfig, false)).toString());
+        return result;
+    }
+
+    public List<String> removeContainerShell(String arg1) {
+        List<String> result = new ArrayList<String>();
+        String containerName = arg1;
+        if (containerName == null) {
+            result.add("Container Name not specified");
+            return result;
+        }
+        ContainerConfig containerConfig = new ContainerConfig(containerName, "", null, null);
+        result.add((this.addRemoveContainer(containerConfig, true)).toString());
+        return result;
+    }
+
+    public List<String> addContainerEntry(String arg1, String arg2, String arg3) {
+        List<String> result = new ArrayList<String>();
+        String containerName = arg1;
+        if (containerName == null) {
+            result.add("Container Name not specified");
+            return result;
+        }
+        String nodeId = arg2;
+        if (nodeId == null) {
+            result.add("Node Id not specified");
+            return result;
+        }
+        String portId = arg3;
+        if (portId == null) {
+            result.add("Port not specified");
+            return result;
+        }
+        Node node = NodeCreator.createOFNode(Long.valueOf(nodeId));
+        Short port = Short.valueOf(portId);
+        NodeConnector nc = NodeConnectorCreator.createOFNodeConnector(port, node);
+        List<String> portList = new ArrayList<String>(1);
+        portList.add(nc.toString());
+        result.add((this.addRemoveContainerEntries(containerName, portList, false)).toString());
+        return result;
+    }
+
+    public List<String> removeContainerEntry(String arg1, String arg2, String arg3) {
+        List<String> result = new ArrayList<String>();
+        String containerName = arg1;
+        if (containerName == null) {
+            result.add("Container Name not specified");
+            return result;
+        }
+        String nodeId = arg2;
+        if (nodeId == null) {
+            result.add("Node Id not specified");
+            return result;
+        }
+        String portId = arg3;
+        if (portId == null) {
+            result.add("Port not specified");
+            return result;
+        }
+        Node node = NodeCreator.createOFNode(Long.valueOf(nodeId));
+        Short port = Short.valueOf(portId);
+        NodeConnector nc = NodeConnectorCreator.createOFNodeConnector(port, node);
+        List<String> portList = new ArrayList<String>(1);
+        portList.add(nc.toString());
+        result.add((this.addRemoveContainerEntries(containerName, portList, true)).toString());
+        return result;
+    }
+    public List<String> addContainerFlow(String arg1, String arg2, String arg3) {
+        List<String> result = new ArrayList<String>();
+        String containerName = arg1;
+        if (containerName == null) {
+            result.add("Container Name not specified");
+            return result;
+        }
+        String cflowName = arg2;
+        if (cflowName == null) {
+            result.add("cflowName not specified");
+            return result;
+        }
+        String unidirectional = arg3;
+        boolean boolUnidirectional = Boolean.parseBoolean(unidirectional);
+        List<ContainerFlowConfig> list = new ArrayList<ContainerFlowConfig>();
+        list.add(createSampleContainerFlowConfig(cflowName, boolUnidirectional));
+        result.add((this.addRemoveContainerFlow(containerName, list, false)).toString());
+        return result;
+    }
+
+    public List<String> removeContainerFlow(String arg1, String arg2) {
+        List<String> result = new ArrayList<String>();
+        String containerName = arg1;
+        if (containerName == null) {
+            result.add("Container Name not specified");
+            return result;
+        }
+        String cflowName = arg2;
+        if (cflowName == null) {
+            result.add("cflowName not specified");
+            return result;
+        }
+        Set<String> set = new HashSet<String>(1);
+        set.add(cflowName);
+        result.add((this.removeContainerFlows(containerName, set)).toString());
+        return result;
+    }
+
+    public List<String> containermgrGetRoles() {
+        List<String> result = new ArrayList<String>();
+        result.add("Configured roles for Container Mgr:");
+        List<String> list = this.getRoles();
+        for (String role : list) {
+            result.add(role + "\t" + roles.get(role));
+        }
+        return result;
+    }
+
+    public List<String> containermgrGetAuthorizedGroups(String arg1) {
+        List<String> result = new ArrayList<String>();
+        String roleName = arg1;
+        if (roleName == null || roleName.trim().isEmpty()) {
+            result.add("Invalid argument");
+            result.add("mmGetAuthorizedGroups <role_name>");
+            return result;
+        }
+        result.add("Resource Groups associated to role " + roleName + ":");
+        List<ResourceGroup> list = this.getAuthorizedGroups(roleName);
+        for (ResourceGroup group : list) {
+            result.add(group.toString());
+        }
+        return result;
+    }
+    public List<String> containermgrGetAuthorizedResources(String arg1) {
+        List<String> result = new ArrayList<String>();
+        String roleName = arg1;
+        if (roleName == null || roleName.trim().isEmpty()) {
+            result.add("Invalid argument");
+            result.add("mmGetAuthorizedResources <role_name>");
+            return result;
+        }
+        result.add("Resource associated to role " + roleName + ":");
+        List<Resource> list = this.getAuthorizedResources(roleName);
+        for (Resource resource : list) {
+            result.add(resource.toString());
+        }
+        return result;
+    }
+    public List<String> containermgrGetResourcesForGroup(String arg1) {
+        List<String> result = new ArrayList<String>();
+        String groupName = arg1;
+        if (groupName == null || groupName.trim().isEmpty()) {
+            result.add("Invalid argument");
+            result.add("containermgrResourcesForGroup <group_name>");
+            return result;
+        }
+        result.add("Group " + groupName + " contains the following resources:");
+        List<Object> resources = this.getResources(groupName);
+        for (Object resource : resources) {
+            result.add(resource.toString());
+        }
+        return result;
+    }
+    public List<String> containermgrGetUserLevel(String arg1) {
+        List<String> result = new ArrayList<String>();
+        String userName = arg1;
+        if (userName == null || userName.trim().isEmpty()) {
+            result.add("Invalid argument");
+            result.add("containermgrGetUserLevel <user_name>");
+            return result;
+        }
+        result.add("User " + userName + " has level: " + this.getUserLevel(userName));
+        return result;
+    }
+    public List<String> containermgrGetUserResources(String arg1) {
+        List<String> result = new ArrayList<String>();
+        String userName = arg1;
+        if (userName == null || userName.trim().isEmpty()) {
+            result.add("Invalid argument");
+            result.add("containermgrGetUserResources <user_name>");
+            return result;
+        }
+        result.add("User " + userName + " owns the following resources: ");
+        Set<Resource> resources = this.getAllResourcesforUser(userName);
+        for (Resource resource : resources) {
+            result.add(resource.toString());
+        }
+        return result;
+    }
+    public List<String> saveConfig() {
+        List<String> result = new ArrayList<String>();
+        Status status = new Status(StatusCode.NOSERVICE, "Configuration service not reachable");
+
+        IConfigurationService configService = (IConfigurationService) ServiceHelper.getGlobalInstance(
+                IConfigurationService.class, this);
+        if (configService != null) {
+            status = configService.saveConfigurations();
+        }
+        result.add(status.toString());
+        return result;
+    }
 }