Merge "Declare a property for commons-lang version in poms and use it."
[controller.git] / opendaylight / containermanager / implementation / src / main / java / org / opendaylight / controller / containermanager / internal / ContainerManager.java
1
2 /*
3  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
4  *
5  * This program and the accompanying materials are made available under the
6  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  * and is available at http://www.eclipse.org/legal/epl-v10.html
8  */
9
10 package org.opendaylight.controller.containermanager.internal;
11
12 import java.io.File;
13 import java.io.FileNotFoundException;
14 import java.io.IOException;
15 import java.io.ObjectInputStream;
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.EnumSet;
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.Iterator;
22 import java.util.List;
23 import java.util.Locale;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.Set;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.ConcurrentMap;
29 import java.util.concurrent.CopyOnWriteArrayList;
30
31 import org.eclipse.osgi.framework.console.CommandInterpreter;
32 import org.eclipse.osgi.framework.console.CommandProvider;
33 import org.opendaylight.controller.clustering.services.CacheConfigException;
34 import org.opendaylight.controller.clustering.services.CacheExistException;
35 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
36 import org.opendaylight.controller.clustering.services.IClusterGlobalServices;
37 import org.opendaylight.controller.clustering.services.IClusterServices;
38 import org.opendaylight.controller.configuration.IConfigurationAware;
39 import org.opendaylight.controller.configuration.IConfigurationService;
40 import org.opendaylight.controller.containermanager.IContainerAuthorization;
41 import org.opendaylight.controller.containermanager.IContainerManager;
42 import org.opendaylight.controller.sal.authorization.AppRoleLevel;
43 import org.opendaylight.controller.sal.authorization.Privilege;
44 import org.opendaylight.controller.sal.authorization.Resource;
45 import org.opendaylight.controller.sal.authorization.ResourceGroup;
46 import org.opendaylight.controller.sal.authorization.UserLevel;
47 import org.opendaylight.controller.sal.core.ContainerFlow;
48 import org.opendaylight.controller.sal.core.IContainerAware;
49 import org.opendaylight.controller.sal.core.IContainerListener;
50 import org.opendaylight.controller.sal.core.Node;
51 import org.opendaylight.controller.sal.core.NodeConnector;
52 import org.opendaylight.controller.sal.core.UpdateType;
53 import org.opendaylight.controller.sal.match.Match;
54 import org.opendaylight.controller.sal.utils.GlobalConstants;
55 import org.opendaylight.controller.sal.utils.IObjectReader;
56 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
57 import org.opendaylight.controller.sal.utils.NodeCreator;
58 import org.opendaylight.controller.sal.utils.ObjectReader;
59 import org.opendaylight.controller.sal.utils.ObjectWriter;
60 import org.opendaylight.controller.sal.utils.ServiceHelper;
61 import org.opendaylight.controller.sal.utils.Status;
62 import org.opendaylight.controller.sal.utils.StatusCode;
63 import org.opendaylight.controller.topologymanager.ITopologyManager;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 import org.opendaylight.controller.appauth.authorization.Authorization;
68 import org.opendaylight.controller.containermanager.ContainerFlowChangeEvent;
69 import org.opendaylight.controller.containermanager.ContainerFlowConfig;
70 import org.opendaylight.controller.containermanager.NodeConnectorsChangeEvent;
71 import org.opendaylight.controller.containermanager.ContainerChangeEvent;
72 import org.opendaylight.controller.containermanager.ContainerConfig;
73 import org.opendaylight.controller.containermanager.ContainerData;
74
75 public class ContainerManager extends Authorization<String> implements IContainerManager, IObjectReader,
76         CommandProvider, ICacheUpdateAware<String, Object>, IContainerInternal, IContainerAuthorization,
77         IConfigurationAware {
78     private static final Logger logger = LoggerFactory.getLogger(ContainerManager.class);
79     private static String ROOT = GlobalConstants.STARTUPHOME.toString();
80     private static String containersFileName = ROOT + "containers.conf";
81     private static final String allContainersGroup = "allContainers";
82     private IClusterGlobalServices clusterServices;
83     /*
84      * Collection containing the configuration objects. This is configuration
85      * world: container names (also the map key) are maintained as they were
86      * configured by user, same case
87      */
88     private ConcurrentMap<String, ContainerConfig> containerConfigs;
89     private ConcurrentMap<String, ContainerData> containerData;
90     private ConcurrentMap<NodeConnector, CopyOnWriteArrayList<String>> nodeConnectorToContainers;
91     private ConcurrentMap<Node, Set<String>> nodeToContainers;
92     private ConcurrentMap<String, Object> containerChangeEvents;
93     private final Set<IContainerAware> iContainerAware = Collections.synchronizedSet(new HashSet<IContainerAware>());
94     private final Set<IContainerListener> iContainerListener = Collections
95             .synchronizedSet(new HashSet<IContainerListener>());
96
97     void setIContainerListener(IContainerListener s) {
98         if (this.iContainerListener != null) {
99             this.iContainerListener.add(s);
100             /*
101              * At boot with startup, containers are created before listeners have
102              * joined. Replaying here the first container creation notification for
103              * the joining listener when containers are already present. Also
104              * replaying all the node connectors and container flows additions
105              * to the existing containers.
106              */
107             if (!this.containerData.isEmpty()) {
108                 s.containerModeUpdated(UpdateType.ADDED);
109             }
110             for (ConcurrentMap.Entry<NodeConnector, CopyOnWriteArrayList<String>> entry : nodeConnectorToContainers
111                     .entrySet()) {
112                 NodeConnector port = entry.getKey();
113                 for (String container : entry.getValue()) {
114                     s.nodeConnectorUpdated(container, port, UpdateType.ADDED);
115                 }
116             }
117             for (Map.Entry<String, ContainerData> container : containerData.entrySet()) {
118                 for (ContainerFlow cFlow : container.getValue().getContainerFlowSpecs()) {
119                     s.containerFlowUpdated(container.getKey(), cFlow, cFlow, UpdateType.ADDED);
120                 }
121             }
122         }
123     }
124
125     void unsetIContainerListener(IContainerListener s) {
126         if (this.iContainerListener != null) {
127             this.iContainerListener.remove(s);
128         }
129     }
130
131     public void setIContainerAware(IContainerAware iContainerAware) {
132         if (!this.iContainerAware.contains(iContainerAware)) {
133             this.iContainerAware.add(iContainerAware);
134             // Now call the container creation for all the known containers so far
135             for (String container : getContainerNameList()) {
136                 iContainerAware.containerCreate(container.toLowerCase(Locale.ENGLISH));
137             }
138         }
139     }
140
141     public void unsetIContainerAware(IContainerAware iContainerAware) {
142         this.iContainerAware.remove(iContainerAware);
143         // There is no need to do cleanup of the component when
144         // unregister because it will be taken care by the Containerd
145         // component itself
146     }
147
148     public void setClusterServices(IClusterGlobalServices i) {
149         this.clusterServices = i;
150         logger.debug("IClusterServices set");
151     }
152
153     public void unsetClusterServices(IClusterGlobalServices i) {
154         if (this.clusterServices == i) {
155             this.clusterServices = null;
156             logger.debug("IClusterServices Unset");
157         }
158     }
159
160     private void allocateCaches() {
161         logger.debug("Container Manager allocating caches");
162
163         if (clusterServices == null) {
164             logger.warn("un-initialized Cluster Services, can't allocate caches");
165             return;
166         }
167         try {
168             clusterServices.createCache("containermgr.containerConfigs", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
169
170             clusterServices.createCache("containermgr.event.containerChange",
171                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
172
173             clusterServices.createCache("containermgr.containerData", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
174
175             clusterServices.createCache("containermgr.nodeConnectorToContainers",
176                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
177
178             clusterServices.createCache("containermgr.nodeToContainers", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
179
180             clusterServices.createCache("containermgr.containerGroups", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
181
182             clusterServices.createCache("containermgr.containerAuthorizations",
183                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
184
185             clusterServices.createCache("containermgr.roles", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
186         } catch (CacheConfigException cce) {
187             logger.error("Cache configuration invalid - check cache mode");
188         } catch (CacheExistException ce) {
189             logger.error("Cache already exits - destroy and recreate if needed");
190         }
191     }
192
193     @SuppressWarnings({ "unchecked" })
194     private void retrieveCaches() {
195         logger.debug("Container Manager retrieving caches");
196
197         if (clusterServices == null) {
198             logger.warn("un-initialized Cluster Services, can't retrieve caches");
199             return;
200         }
201
202         containerConfigs = (ConcurrentMap<String, ContainerConfig>) clusterServices.getCache("containermgr.containerConfigs");
203
204         containerChangeEvents = (ConcurrentMap<String, Object>) clusterServices.getCache("containermgr.event.containerChange");
205
206         containerData = (ConcurrentMap<String, ContainerData>) clusterServices.getCache("containermgr.containerData");
207
208         nodeConnectorToContainers = (ConcurrentMap<NodeConnector, CopyOnWriteArrayList<String>>) clusterServices
209                 .getCache("containermgr.nodeConnectorToContainers");
210
211         nodeToContainers = (ConcurrentMap<Node, Set<String>>) clusterServices.getCache("containermgr.nodeToContainers");
212
213         resourceGroups = (ConcurrentMap<String, Set<String>>) clusterServices.getCache("containermgr.containerGroups");
214
215         groupsAuthorizations = (ConcurrentMap<String, Set<ResourceGroup>>) clusterServices
216                 .getCache("containermgr.containerAuthorizations");
217
218         roles = (ConcurrentMap<String, AppRoleLevel>) clusterServices.getCache("containermgr.roles");
219
220         if (containerConfigs.size() > 0) {
221             for (Map.Entry<String, ContainerConfig> entry : containerConfigs.entrySet()) {
222                 notifyContainerChangeInternal(entry.getValue(), UpdateType.ADDED);
223             }
224         }
225     }
226
227     @Override
228     public void entryCreated(String containerName, String cacheName, boolean originLocal) {
229
230     }
231
232     @Override
233     public void entryUpdated(String key, Object value, String cacheName, boolean originLocal) {
234         if (!originLocal) {
235             if (value instanceof NodeConnectorsChangeEvent) {
236                 NodeConnectorsChangeEvent event = (NodeConnectorsChangeEvent) value;
237                 List<NodeConnector> ncList = event.getNodeConnectors();
238                 notifyContainerEntryChangeInternal(key, ncList, event.getUpdateType());
239             } else if (value instanceof ContainerFlowChangeEvent) {
240                 ContainerFlowChangeEvent event = (ContainerFlowChangeEvent) value;
241                 notifyCFlowChangeInternal(key, event.getConfigList(), event.getUpdateType());
242             } else if (value instanceof ContainerChangeEvent) {
243                 ContainerChangeEvent event = (ContainerChangeEvent) value;
244                 notifyContainerChangeInternal(event.getConfig(), event.getUpdateType());
245             }
246         }
247     }
248
249     @Override
250     public void entryDeleted(String containerName, String cacheName, boolean originLocal) {
251     }
252
253     public ContainerManager() {
254     }
255
256     public void init() {
257
258     }
259
260     public void start() {
261         // Get caches from cluster manager
262         allocateCaches();
263         retrieveCaches();
264
265         // Allocates default groups and association to default roles
266         createDefaultAuthorizationGroups();
267
268         // Read startup configuration and create local database
269         loadConfigurations();
270     }
271
272     public void destroy() {
273         // Clear local states
274         this.iContainerAware.clear();
275         this.iContainerListener.clear();
276     }
277
278     /**
279      * Adds/Remove the list of flow specs to/from the specified container. This
280      * function is supposed to be called after all the validation checks have
281      * already been run on the proposed configuration.
282      */
283     private Status updateContainerFlow(String containerName, List<ContainerFlowConfig> confList, boolean delete) {
284         ContainerData container = getContainerByName(containerName);
285         if (container == null) {
286             return new Status(StatusCode.GONE, "Container not present");
287         }
288
289         for (ContainerFlowConfig conf : confList) {
290             // Validation was fine. Modify the database now.
291             for (Match match : conf.getMatches()) {
292                 ContainerFlow cFlow = new ContainerFlow(match);
293                 if (delete) {
294                     logger.trace("Removing Flow Spec %s from Container {}", conf.getName(), containerName);
295                     container.deleteFlowSpec(cFlow);
296                 } else {
297                     logger.trace("Adding Flow Spec %s to Container {}", conf.getName(), containerName);
298                     container.addFlowSpec(cFlow);
299
300                 }
301                 // Update Database
302                 putContainerDataByName(containerName, container);
303             }
304         }
305         return new Status(StatusCode.SUCCESS);
306     }
307
308     /**
309      * Adds/Remove this container to/from the Container database, no updates are going
310      * to be generated here other that the destroying and creation of the container.
311      * This function is supposed to be called after all the validation checks
312      * have already been run on the configuration object
313      */
314     private Status updateContainerDatabase(ContainerConfig containerConf, boolean delete) {
315         /*
316          * Back-end world here, container names are all stored in lower case
317          */
318         String containerName = containerConf.getContainerName();
319         ContainerData container = getContainerByName(containerName);
320         if (delete && container == null) {
321             return new Status(StatusCode.NOTFOUND, "Container is not present");
322         }
323         if (!delete && container != null) {
324             // A container with the same (lower case) name already exists
325             return new Status(StatusCode.CONFLICT, "A container with the same name already exists");
326         }
327         if (delete) {
328             logger.debug("Removing container {}", containerName);
329             removeNodeToContainersMapping(container);
330             removeNodeConnectorToContainersMapping(container);
331             removeContainerDataByName(containerName);
332         } else {
333             logger.debug("Adding container {}", containerName);
334             container = new ContainerData(containerConf);
335             putContainerDataByName(containerName, container);
336
337             // If flow specs are specified, add them
338             if (containerConf.hasFlowSpecs()) {
339                 updateContainerFlow(containerName, containerConf.getContainerFlowConfigs(), delete);
340             }
341
342             // If ports are specified, add them
343             if (!containerConf.getPortList().isEmpty()) {
344                 updateContainerEntryDatabase(containerName, containerConf.getPortList(), delete);
345             }
346         }
347         return new Status(StatusCode.SUCCESS);
348     }
349
350     private void removeNodeConnectorToContainersMapping(ContainerData container) {
351         Iterator<Entry<NodeConnector, CopyOnWriteArrayList<String>>> it = nodeConnectorToContainers.entrySet().iterator();
352         String containerName = container.getContainerName();
353         for (; it.hasNext();) {
354             Entry<NodeConnector, CopyOnWriteArrayList<String>> entry = it.next();
355             final NodeConnector nc = entry.getKey();
356             final CopyOnWriteArrayList<String> slist = entry.getValue();
357             for (final String sdata : slist) {
358                 if (sdata.equalsIgnoreCase(containerName)) {
359                     logger.debug("Removing NodeConnector->Containers mapping, nodeConnector: {}", nc);
360                     slist.remove(containerName);
361                     if (slist.isEmpty()) {
362                         nodeConnectorToContainers.remove(nc);
363                     } else {
364                         nodeConnectorToContainers.put(nc, slist);
365                     }
366                     break;
367                 }
368             }
369         }
370     }
371
372     private void removeNodeToContainersMapping(ContainerData container) {
373         for (Entry<Node, Set<String>> entry : nodeToContainers.entrySet()) {
374             Node node = entry.getKey();
375             for (String sdata : entry.getValue()) {
376                 if (sdata.equals(container.getContainerName())) {
377                     logger.debug("Removing Node->Containers mapping, node {} container {}", node, sdata);
378                     Set<String> value = nodeToContainers.get(node);
379                     value.remove(sdata);
380                     nodeToContainers.put(node, value);
381                     break;
382                 }
383             }
384         }
385     }
386
387     /**
388      * Adds/Remove container data to/from the container. This function is supposed to be
389      * called after all the validation checks have already been run on the
390      * configuration object
391      */
392     private Status updateContainerEntryDatabase(String containerName, List<NodeConnector> nodeConnectors, boolean delete) {
393         ContainerData container = getContainerByName(containerName);
394         // Presence check
395         if (container == null) {
396             return new Status(StatusCode.NOTFOUND, "Container Not Found");
397         }
398
399         // Check changes in the portlist
400         for (NodeConnector port : nodeConnectors) {
401             Node node = port.getNode();
402             if (delete) {
403                 container.removePortFromSwitch(port);
404                 putContainerDataByName(containerName, container);
405
406                 /* remove <sp> - container mapping */
407                 if (nodeConnectorToContainers.containsKey(port)) {
408                     nodeConnectorToContainers.remove(port);
409                 }
410                 /*
411                  * If no more ports in the switch, remove switch from container
412                  * Generate switchRemoved Event
413                  */
414                 if (container.portListEmpty(node)) {
415                     logger.debug("Port List empty for switch {}", node);
416                     putContainerDataByName(containerName, container);
417                     // remove node->containers mapping
418                     Set<String> slist = nodeToContainers.get(node);
419                     if (slist != null) {
420                         logger.debug("Removing container from switch-container list. node{}, container{}", node, containerName);
421                         slist.remove(container.getContainerName());
422                         nodeToContainers.put(node, slist);
423                         if (slist.isEmpty()) {
424                             logger.debug("Container list empty for switch {}. removing switch-container mapping", node);
425                             nodeToContainers.remove(node);
426                         }
427                     }
428                 }
429             } else {
430                 if (container.isSwitchInContainer(node) == false) {
431                     Set<String> value = nodeToContainers.get(node);
432                     // Add node->containers mapping
433                     if (value == null) {
434                         value = new HashSet<String>();
435                         logger.debug("Creating new Container Set for switch {}", node);
436                     }
437                     value.add(container.getContainerName());
438                     nodeToContainers.put(node, value);
439                 }
440                 container.addPortToSwitch(port);
441                 putContainerDataByName(containerName, container);
442
443                 // added nc->containers mapping
444                 CopyOnWriteArrayList<String> slist = nodeConnectorToContainers.get(port);
445                 if (slist == null) {
446                     slist = new CopyOnWriteArrayList<String>();
447                 }
448                 slist.add(container.getContainerName());
449                 nodeConnectorToContainers.put(port, slist);
450             }
451         }
452         return new Status(StatusCode.SUCCESS);
453     }
454
455     private Status validateContainerFlowAddRemoval(String containerName, ContainerFlow cFlow, boolean delete) {
456         /*
457          * It used to be the comment below: ~~~~~~~~~~~~~~~~~~~~ If Link Sharing
458          * at Host facing interfaces, then disallow last ContainerFlow removal
459          * ~~~~~~~~~~~~~~~~~~~~ But the interface being host facing is a
460          * condition that can change at runtime and so the final effect will be
461          * unreliable. So now we will always allow the container flow removal,
462          * if this is a link host facing and is shared by many that will cause
463          * issues but that validation should be done not at the configuration
464          * but in the UI/northbound side.
465          */
466         ContainerData container = this.getContainerByName(containerName);
467         if (container == null) {
468             String error = String.format("Cannot validate flow specs for container %s: (Container does not exist)", containerName);
469             logger.warn(error);
470             return new Status(StatusCode.BADREQUEST, error);
471         }
472
473         if (delete) {
474             Set<NodeConnector> thisContainerPorts = container.getNodeConnectors();
475             // Go through all the installed containers
476             for (Map.Entry<String, ContainerData> entry : containerData.entrySet()) {
477                 if (containerName.equalsIgnoreCase(entry.getKey())) {
478                     continue;
479                 }
480                 // Derive the common ports
481                 Set<NodeConnector> commonPorts = entry.getValue().getNodeConnectors();
482                 commonPorts.retainAll(thisContainerPorts);
483                 if (commonPorts.isEmpty()) {
484                     continue;
485                 }
486
487                 // Check if this operation would remove the only flow spec
488                 // assigned to this container
489                 if (container.getFlowSpecCount() == 1) {
490                     if (!container.hasStaticVlanAssigned()) {
491                         // Ports are shared and static vlan is not present: this
492                         // is a failure
493                         // regardless the shared ports are host facing or
494                         // interswitch ports
495                         return new Status(StatusCode.BADREQUEST, "Container shares port with another container: "
496                                 + "The only one flow spec assigned to this container cannot be removed,"
497                                 + "because this container is not assigned any static vlan");
498                     }
499
500                     // Check on host facing port
501                     ITopologyManager topologyManager = (ITopologyManager) ServiceHelper.getInstance(
502                             ITopologyManager.class, GlobalConstants.DEFAULT.toString(), this);
503                     if (topologyManager == null) {
504                         return new Status(StatusCode.NOSERVICE,
505                                 "Cannot validate the request: Required service is not available");
506                     }
507                     for (NodeConnector nc : commonPorts) {
508                         /*
509                          * Shared link case : For internal port check if it has
510                          * a vlan configured. If vlan is configured, allow the
511                          * flowspec to be deleted If the port is host-facing, do
512                          * not allow the flowspec to be deleted
513                          */
514                         if (!topologyManager.isInternal(nc)) {
515                             return new Status(StatusCode.BADREQUEST, String.format(
516                                     "Port %s is shared and is host facing port: "
517                                             + "The only one flow spec assigned to this container cannot be removed", nc));
518                         }
519                     }
520                 }
521             }
522         } else {
523             // Adding a new flow spec: need to check if other containers with common
524             // ports do not have same flow spec
525             Set<NodeConnector> thisContainerPorts = container.getNodeConnectors();
526             List<ContainerFlow> proposed = new ArrayList<ContainerFlow>(container.getContainerFlowSpecs());
527             proposed.add(cFlow);
528             for (Map.Entry<String, ContainerData> entry : containerData.entrySet()) {
529                 if (containerName.equalsIgnoreCase(entry.getKey())) {
530                     continue;
531                 }
532                 ContainerData otherContainer = entry.getValue();
533                 Set<NodeConnector> commonPorts = otherContainer.getNodeConnectors();
534                 commonPorts.retainAll(thisContainerPorts);
535
536                 if (!commonPorts.isEmpty()) {
537                     Status status = checkCommonContainerFlow(otherContainer.getContainerFlowSpecs(), proposed);
538                     if (!status.isSuccess()) {
539                         return new Status(StatusCode.BADREQUEST, String.format(
540                                 "Container %s which shares ports with this container has overlapping flow spec: %s",
541                                 entry.getKey(), status.getDescription()));
542                     }
543                 }
544             }
545         }
546
547         return new Status(StatusCode.SUCCESS);
548     }
549
550     /**
551      * Checks if the passed list of node connectors can be safely applied to the
552      * specified existing container in terms of port sharing with other containers.
553      *
554      * @param containerName
555      *            the name of the existing container
556      * @param portList
557      *            the list of node connectors to be added to the container
558      * @return the status object representing the result of the check
559      */
560     private Status validatePortSharing(String containerName, List<NodeConnector> portList) {
561         ContainerData container = this.getContainerByName(containerName);
562         if (container == null) {
563             String error = String
564                     .format("Cannot validate port sharing for container %s: (container does not exist)", containerName);
565             logger.error(error);
566             return new Status(StatusCode.BADREQUEST, error);
567         }
568         return validatePortSharingInternal(portList, container.getContainerFlowSpecs());
569     }
570
571     /**
572      * Checks if the proposed container configuration is valid to be applied in
573      * terms of port sharing with other containers.
574      *
575      * @param containerConf
576      *            the container configuration object containing the list of node
577      *            connectors
578      * @return the status object representing the result of the check
579      */
580     private Status validatePortSharing(ContainerConfig containerConf) {
581         return validatePortSharingInternal(containerConf.getPortList(), containerConf.getContainerFlowSpecs());
582     }
583
584     /*
585      * If any port is shared with an existing container, need flowSpec to be
586      * configured. If no flowSpec for this or other container, or if containers have any
587      * overlapping flowspec in common, then let the caller know this
588      * configuration has to be rejected.
589      */
590     private Status validatePortSharingInternal(List<NodeConnector> portList, List<ContainerFlow> flowSpecList) {
591         for (NodeConnector port : portList) {
592             List<String> slist = nodeConnectorToContainers.get(port);
593             if (slist != null && !slist.isEmpty()) {
594                 for (String otherContainerName : slist) {
595                     String msg = null;
596                     ContainerData other = containerData.get(otherContainerName);
597                     if (flowSpecList.isEmpty()) {
598                         msg = String.format("Port %s is shared and flow spec is emtpy for this container", port);
599                     } else if (other.isFlowSpecEmpty()) {
600                         msg = String.format("Port %s is shared and flow spec is emtpy for the other container", port);
601                     } else if (!checkCommonContainerFlow(flowSpecList, other.getContainerFlowSpecs()).isSuccess()) {
602                         msg = String.format("Port %s is shared and other container has common flow spec", port);
603                     }
604                     if (msg != null) {
605                         logger.debug(msg);
606                         return new Status(StatusCode.BADREQUEST, msg);
607                     }
608                 }
609             }
610         }
611         return new Status(StatusCode.SUCCESS);
612     }
613
614     /**
615      * Utility function to check if two lists of container flows share any same
616      * or overlapping container flows.
617      *
618      * @param oneFlowList
619      *            One of the two lists of container flows to test
620      * @param twoFlowList
621      *            One of the two lists of container flows to test
622      * @return The status of the check. Either SUCCESS or CONFLICT. In case of
623      *         conflict, the Status will contain the description for the failed
624      *         check.
625      */
626     private Status checkCommonContainerFlow(List<ContainerFlow> oneFlowList, List<ContainerFlow> twoFlowList) {
627         for (ContainerFlow oneFlow : oneFlowList) {
628             for (ContainerFlow twoFlow : twoFlowList) {
629                 if (oneFlow.getMatch().intersetcs(twoFlow.getMatch())) {
630                     return new Status(StatusCode.CONFLICT, String.format("Flow Specs overlap: %s %s",
631                             oneFlow.getMatch(), twoFlow.getMatch()));
632                 }
633             }
634         }
635         return new Status(StatusCode.SUCCESS);
636     }
637
638     /**
639      * Return the ContainerData object for the passed container name. Given this is a
640      * backend database, the lower case version of the passed name is used while
641      * searching for the corresponding ContainerData object.
642      *
643      * @param name
644      *            The container name in any case
645      * @return The corresponding ContainerData object
646      */
647     private ContainerData getContainerByName(String name) {
648         return containerData.get(name.toLowerCase(Locale.ENGLISH));
649     }
650
651     /**
652      * Add a ContainerData object for the given container name.
653      *
654      * @param name
655      *            The container name in any case
656      * @param sData
657      *            The container data object
658      */
659     private void putContainerDataByName(String name, ContainerData sData) {
660         containerData.put(name.toLowerCase(Locale.ENGLISH), sData);
661     }
662
663     /**
664      * Removes the ContainerData object for the given container name.
665      *
666      * @param name
667      *            The container name in any case
668      */
669     private void removeContainerDataByName(String name) {
670         containerData.remove(name.toLowerCase(Locale.ENGLISH));
671     }
672
673     @Override
674     public List<ContainerConfig> getContainerConfigList() {
675         return new ArrayList<ContainerConfig>(containerConfigs.values());
676     }
677
678     @Override
679     public ContainerConfig getContainerConfig(String containerName) {
680         ContainerConfig target = containerConfigs.get(containerName);
681         return (target == null) ? null : new ContainerConfig(target);
682     }
683
684     @Override
685     public List<String> getContainerNameList() {
686         /*
687          * Return container names as they were configured by user (case sensitive)
688          * along with the default container
689          */
690         List<String> containerNameList = new ArrayList<String>();
691         containerNameList.add(GlobalConstants.DEFAULT.toString());
692         containerNameList.addAll(containerConfigs.keySet());
693         return containerNameList;
694     }
695
696     @Override
697     public Map<String, List<ContainerFlowConfig>> getContainerFlows() {
698         Map<String, List<ContainerFlowConfig>> flowSpecConfig = new HashMap<String, List<ContainerFlowConfig>>();
699         for (Map.Entry<String, ContainerConfig> entry : containerConfigs.entrySet()) {
700             List<ContainerFlowConfig> set = entry.getValue().getContainerFlowConfigs();
701             flowSpecConfig.put(entry.getKey(), set);
702         }
703         return flowSpecConfig;
704     }
705
706     private void loadConfigurations() {
707         /*
708          * Read containers, container flows and finally containers' entries from file
709          * and program the database accordingly
710          */
711         if (containerConfigs.isEmpty()) {
712             loadContainerConfig();
713         }
714     }
715
716     private Status saveContainerConfig() {
717         return saveContainerConfigLocal();
718     }
719
720     public Status saveContainerConfigLocal() {
721         ObjectWriter objWriter = new ObjectWriter();
722
723         Status status = objWriter.write(new ConcurrentHashMap<String, ContainerConfig>(containerConfigs), containersFileName);
724         if (!status.isSuccess()) {
725             return new Status(StatusCode.INTERNALERROR, "Failed to save container configurations: "
726                     + status.getDescription());
727         }
728         return new Status(StatusCode.SUCCESS);
729     }
730
731     private void removeComponentsStartUpfiles(String containerName) {
732         String startupLocation = String.format("./%s", GlobalConstants.STARTUPHOME.toString());
733         String containerPrint = String.format("_%s.", containerName.toLowerCase(Locale.ENGLISH));
734
735         File directory = new File(startupLocation);
736         String[] fileList = directory.list();
737
738         logger.trace("Deleteing startup configuration files for container {}", containerName);
739         if (fileList != null) {
740             for (String fileName : fileList) {
741                 if (fileName.contains(containerPrint)) {
742                     String fullPath = String.format("%s/%s", startupLocation, fileName);
743                     File file = new File(fullPath);
744                     boolean done = file.delete();
745                     logger.trace("{} {}", (done ? "Deleted: " : "Failed to delete: "), fileName);
746                 }
747             }
748         }
749     }
750
751     /**
752      * Create and initialize default all resource group and create association
753      * with default well known users and profiles, if not already learnt from
754      * another cluster node
755      */
756     private void createDefaultAuthorizationGroups() {
757         allResourcesGroupName = ContainerManager.allContainersGroup;
758
759         // Add the default container to the all containers group if needed
760         String defaultContainer = GlobalConstants.DEFAULT.toString();
761         Set<String> allContainers = (resourceGroups.containsKey(allResourcesGroupName)) ? resourceGroups
762                 .get(allResourcesGroupName) : new HashSet<String>();
763         if (!allContainers.contains(defaultContainer)) {
764             // Add Default container
765             allContainers.add(defaultContainer);
766             // Update cluster
767             resourceGroups.put(allResourcesGroupName, allContainers);
768         }
769
770         // Add the controller well known roles, if not known already
771         if (!roles.containsKey(UserLevel.SYSTEMADMIN.toString())) {
772             roles.put(UserLevel.SYSTEMADMIN.toString(), AppRoleLevel.APPADMIN);
773         }
774         if (!roles.containsKey(UserLevel.NETWORKADMIN.toString())) {
775             roles.put(UserLevel.NETWORKADMIN.toString(), AppRoleLevel.APPADMIN);
776         }
777         if (!roles.containsKey(UserLevel.NETWORKOPERATOR.toString())) {
778             roles.put(UserLevel.NETWORKOPERATOR.toString(), AppRoleLevel.APPOPERATOR);
779         }
780
781         /*
782          * Create and add the all containers user groups and associate them to the
783          * default well known user roles, if not present already
784          */
785         if (!groupsAuthorizations.containsKey(UserLevel.NETWORKADMIN.toString())) {
786             Set<ResourceGroup> writeProfile = new HashSet<ResourceGroup>(1);
787             Set<ResourceGroup> readProfile = new HashSet<ResourceGroup>(1);
788             writeProfile.add(new ResourceGroup(allResourcesGroupName, Privilege.WRITE));
789             readProfile.add(new ResourceGroup(allResourcesGroupName, Privilege.READ));
790             groupsAuthorizations.put(UserLevel.SYSTEMADMIN.toString(), writeProfile);
791             groupsAuthorizations.put(UserLevel.NETWORKADMIN.toString(), writeProfile);
792             groupsAuthorizations.put(UserLevel.NETWORKOPERATOR.toString(), readProfile);
793         }
794     }
795
796     /**
797      * Until manual configuration is not available, automatically maintain the
798      * well known resource groups
799      *
800      * @param containerName
801      * @param delete
802      */
803     private void updateResourceGroups(String containerName, boolean delete) {
804         // Container Roles and Container Resource Group
805         String groupName = "Container-" + containerName;
806         String containerAdminRole = "Container-" + containerName + "-Admin";
807         String containerOperatorRole = "Container-" + containerName + "-Operator";
808         Set<String> allContainerSet = resourceGroups.get(allResourcesGroupName);
809         if (delete) {
810             resourceGroups.remove(groupName);
811             groupsAuthorizations.remove(containerAdminRole);
812             groupsAuthorizations.remove(containerOperatorRole);
813             roles.remove(containerAdminRole);
814             roles.remove(containerOperatorRole);
815             // Update the all container group
816             allContainerSet.remove(containerName);
817         } else {
818             Set<String> resources = new HashSet<String>(1);
819             resources.add(containerName);
820             resourceGroups.put(groupName, resources);
821             Set<ResourceGroup> adminGroups = new HashSet<ResourceGroup>(1);
822             Set<ResourceGroup> operatorGroups = new HashSet<ResourceGroup>(1);
823             adminGroups.add(new ResourceGroup(groupName, Privilege.WRITE));
824             operatorGroups.add(new ResourceGroup(groupName, Privilege.READ));
825             groupsAuthorizations.put(containerAdminRole, adminGroups);
826             groupsAuthorizations.put(containerOperatorRole, operatorGroups);
827             roles.put(containerAdminRole, AppRoleLevel.APPADMIN);
828             roles.put(containerOperatorRole, AppRoleLevel.APPOPERATOR);
829             // Update the all containers resource group
830             allContainerSet.add(containerName);
831         }
832         // Update resource groups in cluster
833         resourceGroups.put(allResourcesGroupName, allContainerSet);
834     }
835
836     /**
837      * Notify ContainerAware listeners of the creation/deletion of the container
838      *
839      * @param containerName
840      * @param delete
841      *            true is container was removed, false otherwise
842      */
843     private void notifyContainerAwareListeners(String containerName, boolean delete) {
844         // Back-end World: container name forced to lower case
845         String name = containerName.toLowerCase(Locale.ENGLISH);
846
847         synchronized (this.iContainerAware) {
848             for (IContainerAware i : this.iContainerAware) {
849                 if (delete) {
850                     i.containerDestroy(name);
851                 } else {
852                     i.containerCreate(name);
853                 }
854             }
855         }
856     }
857
858     /**
859      * Notify the ContainerListener listeners in case the container mode has changed
860      * following a container configuration operation Note: this call must happen
861      * after the configuration db has been updated
862      *
863      * @param lastActionDelete
864      *            true if the last container configuration operation was a container
865      *            delete operation
866      */
867     private void notifyContainerModeChange(boolean lastActionDelete) {
868         if (lastActionDelete == false && containerConfigs.size() == 1) {
869             logger.info("First container Creation. Inform listeners");
870             synchronized (this.iContainerListener) {
871                 for (IContainerListener i : this.iContainerListener) {
872                     i.containerModeUpdated(UpdateType.ADDED);
873                 }
874             }
875         } else if (lastActionDelete == true && containerConfigs.isEmpty()) {
876             logger.info("Last container Deletion. Inform listeners");
877             synchronized (this.iContainerListener) {
878                 for (IContainerListener i : this.iContainerListener) {
879                     i.containerModeUpdated(UpdateType.REMOVED);
880                 }
881             }
882         }
883     }
884
885     private Status addRemoveContainerEntries(String containerName, List<String> nodeConnectorsString, boolean delete) {
886         // Construct action message
887         String action = String.format("Node conenctor(s) %s container %s: %s", delete ? "removal from" : "addition to",
888                 containerName, nodeConnectorsString);
889
890         // Validity Check
891         if (nodeConnectorsString == null || nodeConnectorsString.isEmpty()) {
892             return new Status(StatusCode.BADREQUEST, "Node connector list is null or empty");
893         }
894
895         // Presence check
896         ContainerConfig entryConf = containerConfigs.get(containerName);
897         if (entryConf == null) {
898             String msg = String.format("Container not found: %s", containerName);
899             String error = String.format("Failed to apply %s: (%s)", action, msg);
900             logger.warn(error);
901             return new Status(StatusCode.NOTFOUND, msg);
902         }
903
904         // Validation check
905         Status status = ContainerConfig.validateNodeConnectors(nodeConnectorsString);
906         if (!status.isSuccess()) {
907             String error = String.format("Failed to apply %s: (%s)", action, status.getDescription());
908             logger.warn(error);
909             return status;
910         }
911
912         List<NodeConnector> nodeConnectors = ContainerConfig.nodeConnectorsFromString(nodeConnectorsString);
913
914         // Port sharing check
915         if (!delete) {
916             /*
917              * Check if the ports being added to this container already belong to
918              * other containers. If so check whether the the appropriate flow specs
919              * are configured on this container
920              */
921             status = validatePortSharing(containerName, nodeConnectors);
922             if (!status.isSuccess()) {
923                 String error = String.format("Failed to apply %s: (%s)", action, status.getDescription());
924                 logger.warn(error);
925                 return status;
926             }
927         }
928
929         // Update Database
930         status = updateContainerEntryDatabase(containerName, nodeConnectors, delete);
931         if (!status.isSuccess()) {
932             String error = String.format("Failed to apply %s: (%s)", action, status.getDescription());
933             logger.warn(error);
934             return status;
935         }
936
937         // Update Configuration
938         status = (delete) ? entryConf.removeNodeConnectors(nodeConnectorsString) : entryConf
939                 .addNodeConnectors(nodeConnectorsString);
940         if (!status.isSuccess()) {
941             String error = String.format("Failed to modify config for %s: (%s)", action, status.getDescription());
942             logger.warn(error);
943             // Revert backend changes
944             Status statusRevert = updateContainerEntryDatabase(containerName, nodeConnectors, !delete);
945             if (!statusRevert.isSuccess()) {
946                 // Unlikely
947                 logger.error("Failed to revert changes in database (CRITICAL)");
948             }
949             return status;
950         }
951
952         // Update cluster Configuration cache
953         containerConfigs.put(containerName, entryConf);
954
955         // Notify
956         UpdateType update = (delete) ? UpdateType.REMOVED : UpdateType.ADDED;
957         notifyContainerEntryChangeInternal(containerName, nodeConnectors, update);
958         // Trigger cluster notification
959         containerChangeEvents.put(containerName, new NodeConnectorsChangeEvent(nodeConnectors, update));
960
961         return status;
962     }
963
964     private void notifyContainerChangeInternal(ContainerConfig conf, UpdateType update) {
965         String containerName = conf.getContainerName();
966         logger.trace("Notifying listeners on {} for container {}", update, containerName);
967         // Back-end World: container name forced to lower case
968         String container = containerName.toLowerCase(Locale.ENGLISH);
969         boolean delete = (update == UpdateType.REMOVED);
970         // Check if a container mode change notification is needed
971         notifyContainerModeChange(delete);
972         // Notify listeners
973         notifyContainerAwareListeners(container, delete);
974     }
975
976     private void notifyContainerEntryChangeInternal(String containerName, List<NodeConnector> ncList, UpdateType update) {
977         logger.trace("Notifying listeners on {} for ports {} in container {}", update, ncList, containerName);
978         // Back-end World: container name forced to lower case
979         String container = containerName.toLowerCase(Locale.ENGLISH);
980         for (NodeConnector nodeConnector : ncList) {
981             // Now signal that the port has been added/removed
982             synchronized (this.iContainerListener) {
983                 for (IContainerListener i : this.iContainerListener) {
984                     i.nodeConnectorUpdated(container, nodeConnector, update);
985                 }
986             }
987         }
988     }
989
990     private void notifyCFlowChangeInternal(String containerName, List<ContainerFlowConfig> confList, UpdateType update) {
991         logger.trace("Notifying listeners on {} for flow specs {} in container {}", update, confList, containerName);
992         // Back-end World: container name forced to lower case
993         String container = containerName.toLowerCase(Locale.ENGLISH);
994         synchronized (this.iContainerListener) {
995             for (ContainerFlowConfig conf : confList) {
996                 for (Match match : conf.getMatches()) {
997                     ContainerFlow cFlow = new ContainerFlow(match);
998                     for (IContainerListener i : this.iContainerListener) {
999                         i.containerFlowUpdated(container, cFlow, cFlow, update);
1000                     }
1001                 }
1002             }
1003         }
1004     }
1005
1006     private Status addRemoveContainerFlow(String containerName, List<ContainerFlowConfig> cFlowConfList, boolean delete) {
1007         // Construct action message
1008         String action = String.format("Flow spec(s) %s container %s: %s", delete ? "removal from" : "addition to",
1009                 containerName, cFlowConfList);
1010
1011         // Presence check
1012         ContainerConfig containerConfig = this.containerConfigs.get(containerName);
1013         if (containerConfig == null) {
1014             String msg = String.format("Container not found: %s", containerName);
1015             String error = String.format("Failed to apply %s: (%s)", action, msg);
1016             logger.warn(error);
1017             return new Status(StatusCode.NOTFOUND, "Container not present");
1018         }
1019
1020         // Validity check, check for overlaps on current container configuration
1021         Status status = containerConfig.validateContainerFlowModify(cFlowConfList, delete);
1022         if (!status.isSuccess()) {
1023             String msg = status.getDescription();
1024             String error = String.format("Failed to apply %s: (%s)", action, msg);
1025             logger.warn(error);
1026             return new Status(StatusCode.BADREQUEST, msg);
1027         }
1028
1029         // Validate the operation in terms to the port sharing with other containers
1030         for (ContainerFlowConfig conf : cFlowConfList) {
1031             for (Match match : conf.getMatches()) {
1032                 ContainerFlow cFlow = new ContainerFlow(match);
1033                 status = validateContainerFlowAddRemoval(containerName, cFlow, delete);
1034                 if (!status.isSuccess()) {
1035                     String msg = "Validation failed: " + status.getDescription();
1036                     String error = String.format("Failed to apply %s: (%s)", action, msg);
1037                     logger.warn(error);
1038                     return new Status(StatusCode.BADREQUEST, msg);
1039                 }
1040             }
1041         }
1042
1043         // Update Database
1044         status = updateContainerFlow(containerName, cFlowConfList, delete);
1045         if (!status.isSuccess()) {
1046             String error = String.format("Failed to apply %s: (%s)", action, status.getDescription());
1047             logger.error(error);
1048             return status;
1049         }
1050
1051         // Update Configuration
1052         status = (delete) ? containerConfig.removeContainerFlows(cFlowConfList) : containerConfig
1053                 .addContainerFlows(cFlowConfList);
1054         if (!status.isSuccess()) {
1055             String error = String.format("Failed to modify config for %s: (%s)", action, status.getDescription());
1056             logger.error(error);
1057             // Revert backend changes
1058             Status statusRevert = updateContainerFlow(containerName, cFlowConfList, !delete);
1059             if (!statusRevert.isSuccess()) {
1060                 // Unlikely
1061                 logger.error("Failed to revert changes in database (CRITICAL)");
1062             }
1063             return status;
1064         }
1065         // Update cluster cache
1066         this.containerConfigs.put(containerName, containerConfig);
1067
1068         // Notify listeners
1069         UpdateType update = (delete) ? UpdateType.REMOVED : UpdateType.ADDED;
1070         notifyCFlowChangeInternal(containerName, cFlowConfList, update);
1071         // Trigger cluster notification
1072         containerChangeEvents.put(containerName, new ContainerFlowChangeEvent(cFlowConfList, update));
1073
1074         return status;
1075     }
1076
1077     private Status addRemoveContainer(ContainerConfig containerConf, boolean delete) {
1078         // Construct action message
1079         String action = String.format("Container %s", delete ? "removal" : "creation");
1080
1081         // Valid configuration check
1082         Status status = null;
1083         String error = (containerConfigs == null) ? String.format("Invalid %s configuration: (null config object)", action)
1084                 : (!(status = containerConf.validate()).isSuccess()) ? String.format("Invalid %s configuration: (%s)",
1085                         action, status.getDescription()) : null;
1086         if (error != null) {
1087             logger.warn(error);
1088             return new Status(StatusCode.BADREQUEST, error);
1089         }
1090
1091         // Configuration presence check
1092         String containerName = containerConf.getContainerName();
1093         if (delete) {
1094             if (!containerConfigs.containsKey(containerName)) {
1095                 String msg = String.format("%s Failed: (Container does not exist: %s)", action, containerName);
1096                 logger.warn(msg);
1097                 return new Status(StatusCode.NOTFOUND, msg);
1098             }
1099         } else {
1100             if (containerConfigs.containsKey(containerName)) {
1101                 String msg = String.format("%s Failed: (Container already exist: %s)", action, containerName);
1102                 logger.warn(msg);
1103                 return new Status(StatusCode.CONFLICT, msg);
1104             }
1105         }
1106
1107         /*
1108          * The proposed container configuration could be a complex one containing
1109          * both ports and flow spec. If so, check if it has shared ports with
1110          * other existing containers. If that is the case verify flow spec isolation
1111          * is in place. No need to check on flow spec validation first. This
1112          * would take care of both
1113          */
1114         if (!delete) {
1115             status = validatePortSharing(containerConf);
1116             if (!status.isSuccess()) {
1117                 error = String.format("%s Failed: (%s)", action, status.getDescription());
1118                 logger.error(error);
1119                 return status;
1120             }
1121         }
1122
1123         // Update Database
1124         status = updateContainerDatabase(containerConf, delete);
1125
1126         // Abort and exit here if back-end database update failed
1127         if (!status.isSuccess()) {
1128             return status;
1129         }
1130
1131         /*
1132          * This is a quick fix until configuration service becomes the
1133          * centralized configuration management place. Here container manager will
1134          * remove the startup files for all the bundles that are present in the
1135          * container being deleted. Do the cleanup here in Container manger as do not
1136          * want to put this temporary code in Configuration manager yet which is
1137          * ODL.
1138          */
1139         if (delete) {
1140             // TODO: remove when Config Mgr takes over
1141             removeComponentsStartUpfiles(containerName);
1142         }
1143
1144         /*
1145          * Update Configuration: This will trigger the notifications on cache
1146          * update callback locally and on the other cluster nodes
1147          */
1148         if (delete) {
1149             this.containerConfigs.remove(containerName);
1150         } else {
1151             this.containerConfigs.put(containerName, containerConf);
1152         }
1153
1154         // Automatically create and populate user and resource groups
1155         updateResourceGroups(containerName, delete);
1156
1157         // Notify listeners
1158         UpdateType update = (delete) ? UpdateType.REMOVED : UpdateType.ADDED;
1159         notifyContainerChangeInternal(containerConf, update);
1160
1161         // Trigger cluster notification
1162         containerChangeEvents.put(containerName, new ContainerChangeEvent(containerConf, update));
1163
1164         if (update == UpdateType.ADDED) {
1165             if (containerConf.hasFlowSpecs()) {
1166                 List<ContainerFlowConfig> specList = containerConf.getContainerFlowConfigs();
1167                 // Notify flow spec addition
1168                 notifyCFlowChangeInternal(containerName, specList, update);
1169
1170                 // Trigger cluster notification
1171                 containerChangeEvents.put(containerName, new ContainerFlowChangeEvent(specList, update));
1172             }
1173
1174             if (containerConf.hasNodeConnectors()) {
1175                 List<NodeConnector> ncList = containerConf.getPortList();
1176                 // Notify port(s) addition
1177                 notifyContainerEntryChangeInternal(containerName, ncList, update);
1178                 // Trigger cluster notification
1179                 containerChangeEvents.put(containerName, new NodeConnectorsChangeEvent(ncList, update));
1180             }
1181         }
1182
1183         return status;
1184     }
1185
1186     @Override
1187     public Status addContainer(ContainerConfig containerConf) {
1188         return addRemoveContainer(containerConf, false);
1189     }
1190
1191     @Override
1192     public Status removeContainer(ContainerConfig containerConf) {
1193         return addRemoveContainer(containerConf, true);
1194     }
1195
1196     @Override
1197     public Status removeContainer(String containerName) {
1198         // Construct action message
1199         String action = String.format("Container removal: %s", containerName);
1200
1201         ContainerConfig containerConf = containerConfigs.get(containerName);
1202         if (containerConf == null) {
1203             String msg = String.format("Container not found");
1204             String error = String.format("Failed to apply %s: (%s)", action, msg);
1205             logger.warn(error);
1206             return new Status(StatusCode.NOTFOUND, msg);
1207         }
1208         return addRemoveContainer(containerConf, true);
1209     }
1210
1211     @Override
1212     public Status addContainerEntry(String containerName, List<String> nodeConnectors) {
1213         return addRemoveContainerEntries(containerName, nodeConnectors, false);
1214     }
1215
1216     @Override
1217     public Status removeContainerEntry(String containerName, List<String> nodeConnectors) {
1218         return addRemoveContainerEntries(containerName, nodeConnectors, true);
1219     }
1220
1221     @Override
1222     public Status addContainerFlows(String containerName, List<ContainerFlowConfig> fSpecConf) {
1223         return addRemoveContainerFlow(containerName, fSpecConf, false);
1224     }
1225
1226     @Override
1227     public Status removeContainerFlows(String containerName, List<ContainerFlowConfig> fSpecConf) {
1228         return addRemoveContainerFlow(containerName, fSpecConf, true);
1229     }
1230
1231     @Override
1232     public Status removeContainerFlows(String containerName, Set<String> names) {
1233         // Construct action message
1234         String action = String.format("Flow spec(s) removal from container %s: %s", containerName, names);
1235
1236         // Presence check
1237         ContainerConfig sc = containerConfigs.get(containerName);
1238         if (sc == null) {
1239             String msg = String.format("Container not found: %s", containerName);
1240             String error = String.format("Failed to apply %s: (%s)", action, msg);
1241             logger.warn(error);
1242             return new Status(StatusCode.NOTFOUND, msg);
1243         }
1244         List<ContainerFlowConfig> list = sc.getContainerFlowConfigs(names);
1245         if (list.isEmpty() || list.size() != names.size()) {
1246             String msg = String.format("Cannot find all the specified flow specs");
1247             String error = String.format("Failed to apply %s: (%s)", action, msg);
1248             logger.warn(error);
1249             return new Status(StatusCode.BADREQUEST, msg);
1250         }
1251         return addRemoveContainerFlow(containerName, list, true);
1252     }
1253
1254     @Override
1255     public List<ContainerFlowConfig> getContainerFlows(String containerName) {
1256         ContainerConfig sc = containerConfigs.get(containerName);
1257         return (sc == null) ? new ArrayList<ContainerFlowConfig>(0) : sc.getContainerFlowConfigs();
1258     }
1259
1260     @Override
1261     public List<String> getContainerFlowNameList(String containerName) {
1262         ContainerConfig sc = containerConfigs.get(containerName);
1263         return (sc == null) ? new ArrayList<String>(0) : sc.getContainerFlowConfigsNames();
1264     }
1265
1266     @Override
1267     public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
1268         // Perform the class deserialization locally, from inside the package
1269         // where the class is defined
1270         return ois.readObject();
1271     }
1272
1273     @SuppressWarnings("unchecked")
1274     private void loadContainerConfig() {
1275         ObjectReader objReader = new ObjectReader();
1276         ConcurrentMap<String, ContainerConfig> configMap = (ConcurrentMap<String, ContainerConfig>) objReader.read(this,
1277                 containersFileName);
1278
1279         if (configMap == null) {
1280             return;
1281         }
1282
1283         for (Map.Entry<String, ContainerConfig> configEntry : configMap.entrySet()) {
1284             addContainer(configEntry.getValue());
1285         }
1286     }
1287
1288     public void _psc(CommandInterpreter ci) {
1289         for (Map.Entry<String, ContainerConfig> entry : containerConfigs.entrySet()) {
1290             ContainerConfig sc = entry.getValue();
1291             ci.println(String.format("%s: %s", sc.getContainerName(), sc.toString()));
1292         }
1293         ci.println("Total number of containers: " + containerConfigs.entrySet().size());
1294     }
1295
1296     public void _pfc(CommandInterpreter ci) {
1297         for (Map.Entry<String, ContainerConfig> entry : containerConfigs.entrySet()) {
1298             ContainerConfig sc = entry.getValue();
1299             ci.println(String.format("%s: %s", sc.getContainerName(), sc.getContainerFlowConfigs()));
1300         }
1301     }
1302
1303     public void _psd(CommandInterpreter ci) {
1304         for (String containerName : containerData.keySet()) {
1305             ContainerData sd = containerData.get(containerName);
1306             for (Node sid : sd.getSwPorts().keySet()) {
1307                 Set<NodeConnector> s = sd.getSwPorts().get(sid);
1308                 ci.println("\t" + sid + " : " + s);
1309             }
1310
1311             for (ContainerFlow s : sd.getContainerFlowSpecs()) {
1312                 ci.println("\t" + s.toString());
1313             }
1314         }
1315     }
1316
1317     public void _psp(CommandInterpreter ci) {
1318         for (NodeConnector sp : nodeConnectorToContainers.keySet()) {
1319             ci.println(nodeConnectorToContainers.get(sp));
1320         }
1321     }
1322
1323     public void _psm(CommandInterpreter ci) {
1324         for (Node sp : nodeToContainers.keySet()) {
1325             ci.println(nodeToContainers.get(sp));
1326         }
1327     }
1328
1329     public void _addContainer(CommandInterpreter ci) {
1330         String containerName = ci.nextArgument();
1331         if (containerName == null) {
1332             ci.print("Container Name not specified");
1333             return;
1334         }
1335         String staticVlan = ci.nextArgument();
1336         if (staticVlan == null) {
1337             ci.print("Static Vlan not specified");
1338             return;
1339         }
1340         ContainerConfig containerConfig = new ContainerConfig(containerName, staticVlan, null, null);
1341         ci.println(this.addRemoveContainer(containerConfig, false));
1342     }
1343
1344     public void _createContainer(CommandInterpreter ci) {
1345         String containerName = ci.nextArgument();
1346         if (containerName == null) {
1347             ci.print("Container Name not specified");
1348             return;
1349         }
1350         String staticVlan = ci.nextArgument();
1351         if (staticVlan == null) {
1352             ci.print("Static Vlan not specified");
1353             return;
1354         }
1355         List<String> ports = new ArrayList<String>();
1356         for (long l = 1L; l < 10L; l++) {
1357             ports.add(NodeConnectorCreator.createOFNodeConnector((short) 1, NodeCreator.createOFNode(l)).toString());
1358         }
1359         List<ContainerFlowConfig> cFlowList = new ArrayList<ContainerFlowConfig>();
1360         cFlowList.add(this.createSampleContainerFlowConfig("tcp", true));
1361         ContainerConfig containerConfig = new ContainerConfig(containerName, staticVlan, ports, cFlowList);
1362         ci.println(this.addRemoveContainer(containerConfig, false));
1363     }
1364
1365     public void _removeContainer(CommandInterpreter ci) {
1366         String containerName = ci.nextArgument();
1367         if (containerName == null) {
1368             ci.print("Container Name not specified");
1369             return;
1370         }
1371         ContainerConfig containerConfig = new ContainerConfig(containerName, "", null, null);
1372         ci.println(this.addRemoveContainer(containerConfig, true));
1373     }
1374
1375     public void _addContainerEntry(CommandInterpreter ci) {
1376         String containerName = ci.nextArgument();
1377         if (containerName == null) {
1378             ci.print("Container Name not specified");
1379             return;
1380         }
1381         String nodeId = ci.nextArgument();
1382         if (nodeId == null) {
1383             ci.print("Node Id not specified");
1384             return;
1385         }
1386         String portId = ci.nextArgument();
1387         if (portId == null) {
1388             ci.print("Port not specified");
1389             return;
1390         }
1391         Node node = NodeCreator.createOFNode(Long.valueOf(nodeId));
1392         Short port = Short.valueOf(portId);
1393         NodeConnector nc = NodeConnectorCreator.createOFNodeConnector(port, node);
1394         List<String> portList = new ArrayList<String>(1);
1395         portList.add(nc.toString());
1396         ci.println(this.addRemoveContainerEntries(containerName, portList, false));
1397     }
1398
1399     public void _removeContainerEntry(CommandInterpreter ci) {
1400         String containerName = ci.nextArgument();
1401         if (containerName == null) {
1402             ci.print("Container Name not specified");
1403             return;
1404         }
1405         String nodeId = ci.nextArgument();
1406         if (nodeId == null) {
1407             ci.print("Node Id not specified");
1408             return;
1409         }
1410         String portId = ci.nextArgument();
1411         if (portId == null) {
1412             ci.print("Port not specified");
1413             return;
1414         }
1415         Node node = NodeCreator.createOFNode(Long.valueOf(nodeId));
1416         Short port = Short.valueOf(portId);
1417         NodeConnector nc = NodeConnectorCreator.createOFNodeConnector(port, node);
1418         List<String> portList = new ArrayList<String>(1);
1419         portList.add(nc.toString());
1420         ci.println(this.addRemoveContainerEntries(containerName, portList, true));
1421     }
1422
1423     private ContainerFlowConfig createSampleContainerFlowConfig(String cflowName, boolean boolUnidirectional) {
1424         ContainerFlowConfig cfg = new ContainerFlowConfig(cflowName, "9.9.1.0/24", "19.9.1.2", "TCP", "1234", "25");
1425         return cfg;
1426     }
1427
1428     public void _addContainerFlow(CommandInterpreter ci) {
1429         String containerName = ci.nextArgument();
1430         if (containerName == null) {
1431             ci.print("Container Name not specified");
1432             return;
1433         }
1434         String cflowName = ci.nextArgument();
1435         if (cflowName == null) {
1436             ci.print("cflowName not specified");
1437             return;
1438         }
1439         String unidirectional = ci.nextArgument();
1440         boolean boolUnidirectional = Boolean.parseBoolean(unidirectional);
1441         List<ContainerFlowConfig> list = new ArrayList<ContainerFlowConfig>();
1442         list.add(createSampleContainerFlowConfig(cflowName, boolUnidirectional));
1443         ci.println(this.addRemoveContainerFlow(containerName, list, false));
1444     }
1445
1446     public void _removeContainerFlow(CommandInterpreter ci) {
1447         String containerName = ci.nextArgument();
1448         if (containerName == null) {
1449             ci.print("Container Name not specified");
1450             return;
1451         }
1452         String cflowName = ci.nextArgument();
1453         if (cflowName == null) {
1454             ci.print("cflowName not specified");
1455             return;
1456         }
1457         Set<String> set = new HashSet<String>(1);
1458         set.add(cflowName);
1459         ci.println(this.removeContainerFlows(containerName, set));
1460     }
1461
1462     @Override
1463     public String getHelp() {
1464         StringBuffer help = new StringBuffer();
1465         help.append("---ContainerManager Testing---\n");
1466         help.append("\tpsc        - Print ContainerConfigs\n");
1467         help.append("\tpfc        - Print FlowSpecConfigs\n");
1468         help.append("\tpsd        - Print ContainerData\n");
1469         help.append("\tpsp        - Print nodeConnectorToContainers\n");
1470         help.append("\tpsm        - Print nodeToContainers\n");
1471         help.append("\t addContainer <containerName> <staticVlan> \n");
1472         help.append("\t removeContainer <containerName> \n");
1473         help.append("\t addContainerEntry <containerName> <nodeId> <port> \n");
1474         help.append("\t removeContainerEntry <containerName> <nodeId> <port> \n");
1475         help.append("\t addContainerFlow <containerName> <cflowName> <unidirectional true/false>\n");
1476         help.append("\t removeContainerFlow <containerName> <cflowName> \n");
1477         return help.toString();
1478     }
1479
1480     @Override
1481     public boolean doesContainerExist(String containerName) {
1482         // Test for default container
1483         if (GlobalConstants.DEFAULT.toString().equalsIgnoreCase(containerName)) {
1484             return true;
1485         }
1486         // Test for non-default one
1487         return (getContainerByName(containerName) != null);
1488     }
1489
1490     @Override
1491     public ContainerData getContainerData(String containerName) {
1492         return (getContainerByName(containerName));
1493     }
1494
1495     @Override
1496     public Status saveConfiguration() {
1497         return saveContainerConfig();
1498     }
1499
1500     public void _containermgrGetRoles(CommandInterpreter ci) {
1501         ci.println("Configured roles for Container Mgr:");
1502         List<String> list = this.getRoles();
1503         for (String role : list) {
1504             ci.println(role + "\t" + roles.get(role));
1505         }
1506     }
1507
1508     public void _containermgrGetAuthorizedGroups(CommandInterpreter ci) {
1509         String roleName = ci.nextArgument();
1510         if (roleName == null || roleName.trim().isEmpty()) {
1511             ci.println("Invalid argument");
1512             ci.println("mmGetAuthorizedGroups <role_name>");
1513             return;
1514         }
1515         ci.println("Resource Groups associated to role " + roleName + ":");
1516         List<ResourceGroup> list = this.getAuthorizedGroups(roleName);
1517         for (ResourceGroup group : list) {
1518             ci.println(group.toString());
1519         }
1520     }
1521
1522     public void _containermgrGetAuthorizedResources(CommandInterpreter ci) {
1523         String roleName = ci.nextArgument();
1524         if (roleName == null || roleName.trim().isEmpty()) {
1525             ci.println("Invalid argument");
1526             ci.println("mmGetAuthorizedResources <role_name>");
1527             return;
1528         }
1529         ci.println("Resource associated to role " + roleName + ":");
1530         List<Resource> list = this.getAuthorizedResources(roleName);
1531         for (Resource resource : list) {
1532             ci.println(resource.toString());
1533         }
1534     }
1535
1536     public void _containermgrGetResourcesForGroup(CommandInterpreter ci) {
1537         String groupName = ci.nextArgument();
1538         if (groupName == null || groupName.trim().isEmpty()) {
1539             ci.println("Invalid argument");
1540             ci.println("containermgrResourcesForGroup <group_name>");
1541             return;
1542         }
1543         ci.println("Group " + groupName + " contains the following resources:");
1544         List<Object> resources = this.getResources(groupName);
1545         for (Object resource : resources) {
1546             ci.println(resource.toString());
1547         }
1548     }
1549
1550     public void _containermgrGetUserLevel(CommandInterpreter ci) {
1551         String userName = ci.nextArgument();
1552         if (userName == null || userName.trim().isEmpty()) {
1553             ci.println("Invalid argument");
1554             ci.println("containermgrGetUserLevel <user_name>");
1555             return;
1556         }
1557         ci.println("User " + userName + " has level: " + this.getUserLevel(userName));
1558     }
1559
1560     public void _containermgrGetUserResources(CommandInterpreter ci) {
1561         String userName = ci.nextArgument();
1562         if (userName == null || userName.trim().isEmpty()) {
1563             ci.println("Invalid argument");
1564             ci.println("containermgrGetUserResources <user_name>");
1565             return;
1566         }
1567         ci.println("User " + userName + " owns the following resources: ");
1568         Set<Resource> resources = this.getAllResourcesforUser(userName);
1569         for (Resource resource : resources) {
1570             ci.println(resource.toString());
1571         }
1572     }
1573
1574     /*
1575      * For scalability testing where as of now controller gui is unresponsive
1576      * providing here an osgi hook to trigger the save config so that DT do not
1577      * have to reaply the scalable configuration each time they restart the
1578      * controller
1579      */
1580     // TODO: remove when no longer needed
1581     public void _saveConfig(CommandInterpreter ci) {
1582         Status status = new Status(StatusCode.NOSERVICE, "Configuration service not reachable");
1583
1584         IConfigurationService configService = (IConfigurationService) ServiceHelper.getGlobalInstance(
1585                 IConfigurationService.class, this);
1586         if (configService != null) {
1587             status = configService.saveConfigurations();
1588         }
1589         ci.println(status.toString());
1590     }
1591
1592     @Override
1593     public List<String> getContainerNames() {
1594         return getContainerNameList();
1595     }
1596
1597     @Override
1598     public boolean hasNonDefaultContainer() {
1599         return !containerConfigs.keySet().isEmpty();
1600     }
1601 }