3 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
10 package org.opendaylight.controller.containermanager.internal;
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;
25 import java.util.Map.Entry;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.ConcurrentMap;
29 import java.util.concurrent.CopyOnWriteArrayList;
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.IContainerLocalListener;
51 import org.opendaylight.controller.sal.core.Node;
52 import org.opendaylight.controller.sal.core.NodeConnector;
53 import org.opendaylight.controller.sal.core.UpdateType;
54 import org.opendaylight.controller.sal.match.Match;
55 import org.opendaylight.controller.sal.utils.GlobalConstants;
56 import org.opendaylight.controller.sal.utils.IObjectReader;
57 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
58 import org.opendaylight.controller.sal.utils.NodeCreator;
59 import org.opendaylight.controller.sal.utils.ObjectReader;
60 import org.opendaylight.controller.sal.utils.ObjectWriter;
61 import org.opendaylight.controller.sal.utils.ServiceHelper;
62 import org.opendaylight.controller.sal.utils.Status;
63 import org.opendaylight.controller.sal.utils.StatusCode;
64 import org.opendaylight.controller.topologymanager.ITopologyManager;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
68 import org.opendaylight.controller.appauth.authorization.Authorization;
69 import org.opendaylight.controller.containermanager.ContainerFlowChangeEvent;
70 import org.opendaylight.controller.containermanager.ContainerFlowConfig;
71 import org.opendaylight.controller.containermanager.NodeConnectorsChangeEvent;
72 import org.opendaylight.controller.containermanager.ContainerChangeEvent;
73 import org.opendaylight.controller.containermanager.ContainerConfig;
74 import org.opendaylight.controller.containermanager.ContainerData;
76 public class ContainerManager extends Authorization<String> implements IContainerManager, IObjectReader,
77 CommandProvider, ICacheUpdateAware<String, Object>, IContainerInternal, IContainerAuthorization,
79 private static final Logger logger = LoggerFactory.getLogger(ContainerManager.class);
80 private static String ROOT = GlobalConstants.STARTUPHOME.toString();
81 private static String containersFileName = ROOT + "containers.conf";
82 private static final String allContainersGroup = "allContainers";
83 private IClusterGlobalServices clusterServices;
85 * Collection containing the configuration objects. This is configuration
86 * world: container names (also the map key) are maintained as they were
87 * configured by user, same case
89 private ConcurrentMap<String, ContainerConfig> containerConfigs;
90 private ConcurrentMap<String, ContainerData> containerData;
91 private ConcurrentMap<NodeConnector, CopyOnWriteArrayList<String>> nodeConnectorToContainers;
92 private ConcurrentMap<Node, Set<String>> nodeToContainers;
93 private ConcurrentMap<String, Object> containerChangeEvents;
94 private final Set<IContainerAware> iContainerAware = Collections.synchronizedSet(new HashSet<IContainerAware>());
95 private final Set<IContainerListener> iContainerListener = Collections
96 .synchronizedSet(new HashSet<IContainerListener>());
97 private final Set<IContainerLocalListener> iContainerLocalListener = Collections
98 .synchronizedSet(new HashSet<IContainerLocalListener>());
100 void setIContainerListener(IContainerListener s) {
101 if (this.iContainerListener != null) {
102 this.iContainerListener.add(s);
104 * At boot with startup, containers are created before listeners have
105 * joined. Replaying here the first container creation notification for
106 * the joining listener when containers are already present. Also
107 * replaying all the node connectors and container flows additions
108 * to the existing containers.
110 if (!this.containerData.isEmpty()) {
111 s.containerModeUpdated(UpdateType.ADDED);
113 for (ConcurrentMap.Entry<NodeConnector, CopyOnWriteArrayList<String>> entry : nodeConnectorToContainers
115 NodeConnector port = entry.getKey();
116 for (String container : entry.getValue()) {
117 s.nodeConnectorUpdated(container, port, UpdateType.ADDED);
120 for (Map.Entry<String, ContainerData> container : containerData.entrySet()) {
121 for (ContainerFlow cFlow : container.getValue().getContainerFlowSpecs()) {
122 s.containerFlowUpdated(container.getKey(), cFlow, cFlow, UpdateType.ADDED);
128 void unsetIContainerListener(IContainerListener s) {
129 if (this.iContainerListener != null) {
130 this.iContainerListener.remove(s);
134 void setIContainerLocalListener(IContainerLocalListener s) {
135 if (this.iContainerLocalListener != null) {
136 this.iContainerLocalListener.add(s);
140 void unsetIContainerLocalListener(IContainerLocalListener s) {
141 if (this.iContainerLocalListener != null) {
142 this.iContainerLocalListener.remove(s);
146 public void setIContainerAware(IContainerAware iContainerAware) {
147 if (!this.iContainerAware.contains(iContainerAware)) {
148 this.iContainerAware.add(iContainerAware);
149 // Now call the container creation for all the known containers so far
150 for (String container : getContainerNameList()) {
151 iContainerAware.containerCreate(container.toLowerCase(Locale.ENGLISH));
156 public void unsetIContainerAware(IContainerAware iContainerAware) {
157 this.iContainerAware.remove(iContainerAware);
158 // There is no need to do cleanup of the component when
159 // unregister because it will be taken care by the Container
163 public void setClusterServices(IClusterGlobalServices i) {
164 this.clusterServices = i;
165 logger.debug("IClusterServices set");
168 public void unsetClusterServices(IClusterGlobalServices i) {
169 if (this.clusterServices == i) {
170 this.clusterServices = null;
171 logger.debug("IClusterServices Unset");
175 private void allocateCaches() {
176 logger.debug("Container Manager allocating caches");
178 if (clusterServices == null) {
179 logger.warn("un-initialized Cluster Services, can't allocate caches");
183 clusterServices.createCache("containermgr.containerConfigs", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
185 clusterServices.createCache("containermgr.event.containerChange",
186 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
188 clusterServices.createCache("containermgr.containerData", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
190 clusterServices.createCache("containermgr.nodeConnectorToContainers",
191 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
193 clusterServices.createCache("containermgr.nodeToContainers", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
195 clusterServices.createCache("containermgr.containerGroups", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
197 clusterServices.createCache("containermgr.containerAuthorizations",
198 EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
200 clusterServices.createCache("containermgr.roles", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
201 } catch (CacheConfigException cce) {
202 logger.error("Cache configuration invalid - check cache mode");
203 } catch (CacheExistException ce) {
204 logger.error("Cache already exits - destroy and recreate if needed");
208 @SuppressWarnings({ "unchecked" })
209 private void retrieveCaches() {
210 logger.debug("Container Manager retrieving caches");
212 if (clusterServices == null) {
213 logger.warn("un-initialized Cluster Services, can't retrieve caches");
217 containerConfigs = (ConcurrentMap<String, ContainerConfig>) clusterServices.getCache("containermgr.containerConfigs");
219 containerChangeEvents = (ConcurrentMap<String, Object>) clusterServices.getCache("containermgr.event.containerChange");
221 containerData = (ConcurrentMap<String, ContainerData>) clusterServices.getCache("containermgr.containerData");
223 nodeConnectorToContainers = (ConcurrentMap<NodeConnector, CopyOnWriteArrayList<String>>) clusterServices
224 .getCache("containermgr.nodeConnectorToContainers");
226 nodeToContainers = (ConcurrentMap<Node, Set<String>>) clusterServices.getCache("containermgr.nodeToContainers");
228 resourceGroups = (ConcurrentMap<String, Set<String>>) clusterServices.getCache("containermgr.containerGroups");
230 groupsAuthorizations = (ConcurrentMap<String, Set<ResourceGroup>>) clusterServices
231 .getCache("containermgr.containerAuthorizations");
233 roles = (ConcurrentMap<String, AppRoleLevel>) clusterServices.getCache("containermgr.roles");
235 if (inContainerMode()) {
236 for (Map.Entry<String, ContainerConfig> entry : containerConfigs.entrySet()) {
237 // Notify global and local listeners about the mode change
238 notifyContainerChangeInternal(entry.getValue(), UpdateType.ADDED, true);
244 public void entryCreated(String containerName, String cacheName, boolean originLocal) {
249 public void entryUpdated(String key, Object value, String cacheName, boolean originLocal) {
251 * This is were container manager replays a configuration event that was
252 * notified by its peer from a cluster node where the configuration
253 * happened. Only the global listeners, the cluster unaware classes,
254 * (mainly the shim classes in the sdn protocol plugins) need to receive
255 * these notifications on this cluster node. The cluster aware classes,
256 * like the functional modules which reacts on these events, must _not_
257 * be notified to avoid parallel computation in the cluster.
260 if (value instanceof NodeConnectorsChangeEvent) {
261 NodeConnectorsChangeEvent event = (NodeConnectorsChangeEvent) value;
262 List<NodeConnector> ncList = event.getNodeConnectors();
263 notifyContainerEntryChangeInternal(key, ncList, event.getUpdateType(), false);
264 } else if (value instanceof ContainerFlowChangeEvent) {
265 ContainerFlowChangeEvent event = (ContainerFlowChangeEvent) value;
266 notifyCFlowChangeInternal(key, event.getConfigList(), event.getUpdateType(), false);
267 } else if (value instanceof ContainerChangeEvent) {
268 ContainerChangeEvent event = (ContainerChangeEvent) value;
269 notifyContainerChangeInternal(event.getConfig(), event.getUpdateType(), false);
275 public void entryDeleted(String containerName, String cacheName, boolean originLocal) {
278 public ContainerManager() {
285 public void start() {
286 // Get caches from cluster manager
290 // Allocates default groups and association to default roles
291 createDefaultAuthorizationGroups();
293 // Read startup configuration and create local database
294 loadConfigurations();
297 public void destroy() {
298 // Clear local states
299 this.iContainerAware.clear();
300 this.iContainerListener.clear();
301 this.iContainerLocalListener.clear();
305 * Adds/Remove the list of flow specs to/from the specified container. This
306 * function is supposed to be called after all the validation checks have
307 * already been run on the proposed configuration.
309 private Status updateContainerFlow(String containerName, List<ContainerFlowConfig> confList, boolean delete) {
310 ContainerData container = getContainerByName(containerName);
311 if (container == null) {
312 return new Status(StatusCode.GONE, "Container not present");
315 for (ContainerFlowConfig conf : confList) {
316 // Validation was fine. Modify the database now.
317 for (Match match : conf.getMatches()) {
318 ContainerFlow cFlow = new ContainerFlow(match);
320 logger.trace("Removing Flow Spec {} from Container {}", conf.getName(), containerName);
321 container.deleteFlowSpec(cFlow);
323 logger.trace("Adding Flow Spec {} to Container {}", conf.getName(), containerName);
324 container.addFlowSpec(cFlow);
328 putContainerDataByName(containerName, container);
331 return new Status(StatusCode.SUCCESS);
335 * Adds/Remove this container to/from the Container database, no updates are going
336 * to be generated here other that the destroying and creation of the container.
337 * This function is supposed to be called after all the validation checks
338 * have already been run on the configuration object
340 private Status updateContainerDatabase(ContainerConfig containerConf, boolean delete) {
342 * Back-end world here, container names are all stored in lower case
344 String containerName = containerConf.getContainerName();
345 ContainerData container = getContainerByName(containerName);
346 if (delete && container == null) {
347 return new Status(StatusCode.NOTFOUND, "Container is not present");
349 if (!delete && container != null) {
350 // A container with the same (lower case) name already exists
351 return new Status(StatusCode.CONFLICT, "A container with the same name already exists");
354 logger.debug("Removing container {}", containerName);
355 removeNodeToContainersMapping(container);
356 removeNodeConnectorToContainersMapping(container);
357 removeContainerDataByName(containerName);
359 logger.debug("Adding container {}", containerName);
360 container = new ContainerData(containerConf);
361 putContainerDataByName(containerName, container);
363 // If flow specs are specified, add them
364 if (containerConf.hasFlowSpecs()) {
365 updateContainerFlow(containerName, containerConf.getContainerFlowConfigs(), delete);
368 // If ports are specified, add them
369 if (!containerConf.getPortList().isEmpty()) {
370 updateContainerEntryDatabase(containerName, containerConf.getPortList(), delete);
373 return new Status(StatusCode.SUCCESS);
376 private void removeNodeConnectorToContainersMapping(ContainerData container) {
377 Iterator<Entry<NodeConnector, CopyOnWriteArrayList<String>>> it = nodeConnectorToContainers.entrySet().iterator();
378 String containerName = container.getContainerName();
379 for (; it.hasNext();) {
380 Entry<NodeConnector, CopyOnWriteArrayList<String>> entry = it.next();
381 final NodeConnector nc = entry.getKey();
382 final CopyOnWriteArrayList<String> slist = entry.getValue();
383 for (final String sdata : slist) {
384 if (sdata.equalsIgnoreCase(containerName)) {
385 logger.debug("Removing NodeConnector->Containers mapping, nodeConnector: {}", nc);
386 slist.remove(containerName);
387 if (slist.isEmpty()) {
388 nodeConnectorToContainers.remove(nc);
390 nodeConnectorToContainers.put(nc, slist);
398 private void removeNodeToContainersMapping(ContainerData container) {
399 for (Entry<Node, Set<String>> entry : nodeToContainers.entrySet()) {
400 Node node = entry.getKey();
401 for (String sdata : entry.getValue()) {
402 if (sdata.equals(container.getContainerName())) {
403 logger.debug("Removing Node->Containers mapping, node {} container {}", node, sdata);
404 Set<String> value = nodeToContainers.get(node);
406 nodeToContainers.put(node, value);
414 * Adds/Remove container data to/from the container. This function is supposed to be
415 * called after all the validation checks have already been run on the
416 * configuration object
418 private Status updateContainerEntryDatabase(String containerName, List<NodeConnector> nodeConnectors, boolean delete) {
419 ContainerData container = getContainerByName(containerName);
421 if (container == null) {
422 return new Status(StatusCode.NOTFOUND, "Container Not Found");
425 // Check changes in the portlist
426 for (NodeConnector port : nodeConnectors) {
427 Node node = port.getNode();
429 container.removePortFromSwitch(port);
430 putContainerDataByName(containerName, container);
432 /* remove <sp> - container mapping */
433 if (nodeConnectorToContainers.containsKey(port)) {
434 nodeConnectorToContainers.remove(port);
437 * If no more ports in the switch, remove switch from container
438 * Generate switchRemoved Event
440 if (container.portListEmpty(node)) {
441 logger.debug("Port List empty for switch {}", node);
442 putContainerDataByName(containerName, container);
443 // remove node->containers mapping
444 Set<String> slist = nodeToContainers.get(node);
446 logger.debug("Removing container from switch-container list. node{}, container{}", node, containerName);
447 slist.remove(container.getContainerName());
448 nodeToContainers.put(node, slist);
449 if (slist.isEmpty()) {
450 logger.debug("Container list empty for switch {}. removing switch-container mapping", node);
451 nodeToContainers.remove(node);
456 if (container.isSwitchInContainer(node) == false) {
457 Set<String> value = nodeToContainers.get(node);
458 // Add node->containers mapping
460 value = new HashSet<String>();
461 logger.debug("Creating new Container Set for switch {}", node);
463 value.add(container.getContainerName());
464 nodeToContainers.put(node, value);
466 container.addPortToSwitch(port);
467 putContainerDataByName(containerName, container);
469 // added nc->containers mapping
470 CopyOnWriteArrayList<String> slist = nodeConnectorToContainers.get(port);
472 slist = new CopyOnWriteArrayList<String>();
474 slist.add(container.getContainerName());
475 nodeConnectorToContainers.put(port, slist);
478 return new Status(StatusCode.SUCCESS);
481 private Status validateContainerFlowAddRemoval(String containerName, ContainerFlow cFlow, boolean delete) {
483 * It used to be the comment below: ~~~~~~~~~~~~~~~~~~~~ If Link Sharing
484 * at Host facing interfaces, then disallow last ContainerFlow removal
485 * ~~~~~~~~~~~~~~~~~~~~ But the interface being host facing is a
486 * condition that can change at runtime and so the final effect will be
487 * unreliable. So now we will always allow the container flow removal,
488 * if this is a link host facing and is shared by many that will cause
489 * issues but that validation should be done not at the configuration
490 * but in the UI/northbound side.
492 ContainerData container = this.getContainerByName(containerName);
493 if (container == null) {
494 String error = String.format("Cannot validate flow specs for container %s: (Container does not exist)", containerName);
496 return new Status(StatusCode.BADREQUEST, error);
500 Set<NodeConnector> thisContainerPorts = container.getNodeConnectors();
501 // Go through all the installed containers
502 for (Map.Entry<String, ContainerData> entry : containerData.entrySet()) {
503 if (containerName.equalsIgnoreCase(entry.getKey())) {
506 // Derive the common ports
507 Set<NodeConnector> commonPorts = entry.getValue().getNodeConnectors();
508 commonPorts.retainAll(thisContainerPorts);
509 if (commonPorts.isEmpty()) {
513 // Check if this operation would remove the only flow spec
514 // assigned to this container
515 if (container.getFlowSpecCount() == 1) {
516 if (!container.hasStaticVlanAssigned()) {
517 // Ports are shared and static vlan is not present: this
519 // regardless the shared ports are host facing or
521 return new Status(StatusCode.BADREQUEST, "Container shares port with another container: "
522 + "The only one flow spec assigned to this container cannot be removed,"
523 + "because this container is not assigned any static vlan");
526 // Check on host facing port
527 ITopologyManager topologyManager = (ITopologyManager) ServiceHelper.getInstance(
528 ITopologyManager.class, GlobalConstants.DEFAULT.toString(), this);
529 if (topologyManager == null) {
530 return new Status(StatusCode.NOSERVICE,
531 "Cannot validate the request: Required service is not available");
533 for (NodeConnector nc : commonPorts) {
535 * Shared link case : For internal port check if it has
536 * a vlan configured. If vlan is configured, allow the
537 * flowspec to be deleted If the port is host-facing, do
538 * not allow the flowspec to be deleted
540 if (!topologyManager.isInternal(nc)) {
541 return new Status(StatusCode.BADREQUEST, String.format(
542 "Port %s is shared and is host facing port: "
543 + "The only one flow spec assigned to this container cannot be removed", nc));
549 // Adding a new flow spec: need to check if other containers with common
550 // ports do not have same flow spec
551 Set<NodeConnector> thisContainerPorts = container.getNodeConnectors();
552 List<ContainerFlow> proposed = new ArrayList<ContainerFlow>(container.getContainerFlowSpecs());
554 for (Map.Entry<String, ContainerData> entry : containerData.entrySet()) {
555 if (containerName.equalsIgnoreCase(entry.getKey())) {
558 ContainerData otherContainer = entry.getValue();
559 Set<NodeConnector> commonPorts = otherContainer.getNodeConnectors();
560 commonPorts.retainAll(thisContainerPorts);
562 if (!commonPorts.isEmpty()) {
563 Status status = checkCommonContainerFlow(otherContainer.getContainerFlowSpecs(), proposed);
564 if (!status.isSuccess()) {
565 return new Status(StatusCode.BADREQUEST, String.format(
566 "Container %s which shares ports with this container has overlapping flow spec: %s",
567 entry.getKey(), status.getDescription()));
573 return new Status(StatusCode.SUCCESS);
577 * Checks if the passed list of node connectors can be safely applied to the
578 * specified existing container in terms of port sharing with other containers.
580 * @param containerName
581 * the name of the existing container
583 * the list of node connectors to be added to the container
584 * @return the status object representing the result of the check
586 private Status validatePortSharing(String containerName, List<NodeConnector> portList) {
587 ContainerData container = this.getContainerByName(containerName);
588 if (container == null) {
589 String error = String
590 .format("Cannot validate port sharing for container %s: (container does not exist)", containerName);
592 return new Status(StatusCode.BADREQUEST, error);
594 return validatePortSharingInternal(portList, container.getContainerFlowSpecs());
598 * Checks if the proposed container configuration is valid to be applied in
599 * terms of port sharing with other containers.
601 * @param containerConf
602 * the container configuration object containing the list of node
604 * @return the status object representing the result of the check
606 private Status validatePortSharing(ContainerConfig containerConf) {
607 return validatePortSharingInternal(containerConf.getPortList(), containerConf.getContainerFlowSpecs());
611 * If any port is shared with an existing container, need flowSpec to be
612 * configured. If no flowSpec for this or other container, or if containers have any
613 * overlapping flowspec in common, then let the caller know this
614 * configuration has to be rejected.
616 private Status validatePortSharingInternal(List<NodeConnector> portList, List<ContainerFlow> flowSpecList) {
617 for (NodeConnector port : portList) {
618 List<String> slist = nodeConnectorToContainers.get(port);
619 if (slist != null && !slist.isEmpty()) {
620 for (String otherContainerName : slist) {
622 ContainerData other = containerData.get(otherContainerName);
623 if (flowSpecList.isEmpty()) {
624 msg = String.format("Port %s is shared and flow spec is empty for this container", port);
625 } else if (other.isFlowSpecEmpty()) {
626 msg = String.format("Port %s is shared and flow spec is empty for the other container", port);
627 } else if (!checkCommonContainerFlow(flowSpecList, other.getContainerFlowSpecs()).isSuccess()) {
628 msg = String.format("Port %s is shared and other container has common flow spec", port);
632 return new Status(StatusCode.BADREQUEST, msg);
637 return new Status(StatusCode.SUCCESS);
641 * Utility function to check if two lists of container flows share any same
642 * or overlapping container flows.
645 * One of the two lists of container flows to test
647 * One of the two lists of container flows to test
648 * @return The status of the check. Either SUCCESS or CONFLICT. In case of
649 * conflict, the Status will contain the description for the failed
652 private Status checkCommonContainerFlow(List<ContainerFlow> oneFlowList, List<ContainerFlow> twoFlowList) {
653 for (ContainerFlow oneFlow : oneFlowList) {
654 for (ContainerFlow twoFlow : twoFlowList) {
655 if (oneFlow.getMatch().intersetcs(twoFlow.getMatch())) {
656 return new Status(StatusCode.CONFLICT, String.format("Flow Specs overlap: %s %s",
657 oneFlow.getMatch(), twoFlow.getMatch()));
661 return new Status(StatusCode.SUCCESS);
665 * Return the ContainerData object for the passed container name. Given this is a
666 * backend database, the lower case version of the passed name is used while
667 * searching for the corresponding ContainerData object.
670 * The container name in any case
671 * @return The corresponding ContainerData object
673 private ContainerData getContainerByName(String name) {
674 return containerData.get(name.toLowerCase(Locale.ENGLISH));
678 * Add a ContainerData object for the given container name.
681 * The container name in any case
683 * The container data object
685 private void putContainerDataByName(String name, ContainerData sData) {
686 containerData.put(name.toLowerCase(Locale.ENGLISH), sData);
690 * Removes the ContainerData object for the given container name.
693 * The container name in any case
695 private void removeContainerDataByName(String name) {
696 containerData.remove(name.toLowerCase(Locale.ENGLISH));
700 public List<ContainerConfig> getContainerConfigList() {
701 return new ArrayList<ContainerConfig>(containerConfigs.values());
705 public ContainerConfig getContainerConfig(String containerName) {
706 ContainerConfig target = containerConfigs.get(containerName);
707 return (target == null) ? null : new ContainerConfig(target);
711 public List<String> getContainerNameList() {
713 * Return container names as they were configured by user (case sensitive)
714 * along with the default container
716 List<String> containerNameList = new ArrayList<String>();
717 containerNameList.add(GlobalConstants.DEFAULT.toString());
718 containerNameList.addAll(containerConfigs.keySet());
719 return containerNameList;
723 public Map<String, List<ContainerFlowConfig>> getContainerFlows() {
724 Map<String, List<ContainerFlowConfig>> flowSpecConfig = new HashMap<String, List<ContainerFlowConfig>>();
725 for (Map.Entry<String, ContainerConfig> entry : containerConfigs.entrySet()) {
726 List<ContainerFlowConfig> set = entry.getValue().getContainerFlowConfigs();
727 flowSpecConfig.put(entry.getKey(), set);
729 return flowSpecConfig;
732 private void loadConfigurations() {
734 * Read containers, container flows and finally containers' entries from file
735 * and program the database accordingly
737 if (containerConfigs.isEmpty()) {
738 loadContainerConfig();
742 private Status saveContainerConfig() {
743 return saveContainerConfigLocal();
746 public Status saveContainerConfigLocal() {
747 ObjectWriter objWriter = new ObjectWriter();
749 Status status = objWriter.write(new ConcurrentHashMap<String, ContainerConfig>(containerConfigs), containersFileName);
750 if (!status.isSuccess()) {
751 return new Status(StatusCode.INTERNALERROR, "Failed to save container configurations: "
752 + status.getDescription());
754 return new Status(StatusCode.SUCCESS);
757 private void removeComponentsStartUpfiles(String containerName) {
758 String startupLocation = String.format("./%s", GlobalConstants.STARTUPHOME.toString());
759 String containerPrint = String.format("_%s.", containerName.toLowerCase(Locale.ENGLISH));
761 File directory = new File(startupLocation);
762 String[] fileList = directory.list();
764 logger.trace("Deleting startup configuration files for container {}", containerName);
765 if (fileList != null) {
766 for (String fileName : fileList) {
767 if (fileName.contains(containerPrint)) {
768 String fullPath = String.format("%s/%s", startupLocation, fileName);
769 File file = new File(fullPath);
770 boolean done = file.delete();
771 logger.trace("{} {}", (done ? "Deleted: " : "Failed to delete: "), fileName);
778 * Create and initialize default all resource group and create association
779 * with default well known users and profiles, if not already learnt from
780 * another cluster node
782 private void createDefaultAuthorizationGroups() {
783 allResourcesGroupName = ContainerManager.allContainersGroup;
785 // Add the default container to the all containers group if needed
786 String defaultContainer = GlobalConstants.DEFAULT.toString();
787 Set<String> allContainers = (resourceGroups.containsKey(allResourcesGroupName)) ? resourceGroups
788 .get(allResourcesGroupName) : new HashSet<String>();
789 if (!allContainers.contains(defaultContainer)) {
790 // Add Default container
791 allContainers.add(defaultContainer);
793 resourceGroups.put(allResourcesGroupName, allContainers);
796 // Add the controller well known roles, if not known already
797 if (!roles.containsKey(UserLevel.SYSTEMADMIN.toString())) {
798 roles.put(UserLevel.SYSTEMADMIN.toString(), AppRoleLevel.APPADMIN);
800 if (!roles.containsKey(UserLevel.NETWORKADMIN.toString())) {
801 roles.put(UserLevel.NETWORKADMIN.toString(), AppRoleLevel.APPADMIN);
803 if (!roles.containsKey(UserLevel.NETWORKOPERATOR.toString())) {
804 roles.put(UserLevel.NETWORKOPERATOR.toString(), AppRoleLevel.APPOPERATOR);
808 * Create and add the all containers user groups and associate them to the
809 * default well known user roles, if not present already
811 if (!groupsAuthorizations.containsKey(UserLevel.NETWORKADMIN.toString())) {
812 Set<ResourceGroup> writeProfile = new HashSet<ResourceGroup>(1);
813 Set<ResourceGroup> readProfile = new HashSet<ResourceGroup>(1);
814 writeProfile.add(new ResourceGroup(allResourcesGroupName, Privilege.WRITE));
815 readProfile.add(new ResourceGroup(allResourcesGroupName, Privilege.READ));
816 groupsAuthorizations.put(UserLevel.SYSTEMADMIN.toString(), writeProfile);
817 groupsAuthorizations.put(UserLevel.NETWORKADMIN.toString(), writeProfile);
818 groupsAuthorizations.put(UserLevel.NETWORKOPERATOR.toString(), readProfile);
823 * Until manual configuration is not available, automatically maintain the
824 * well known resource groups
826 * @param containerName
829 private void updateResourceGroups(ContainerConfig containerConf, boolean delete) {
830 // Container Roles and Container Resource Group
831 String containerName = containerConf.getContainer();
832 String groupName = containerConf.getContainerGroupName();
833 String containerAdminRole = containerConf.getContainerAdminRole();
834 String containerOperatorRole = containerConf.getContainerOperatorRole();
835 Set<String> allContainerSet = resourceGroups.get(allResourcesGroupName);
837 resourceGroups.remove(groupName);
838 groupsAuthorizations.remove(containerAdminRole);
839 groupsAuthorizations.remove(containerOperatorRole);
840 roles.remove(containerAdminRole);
841 roles.remove(containerOperatorRole);
842 // Update the all container group
843 allContainerSet.remove(containerName);
845 Set<String> resources = new HashSet<String>(1);
846 resources.add(containerName);
847 resourceGroups.put(groupName, resources);
848 Set<ResourceGroup> adminGroups = new HashSet<ResourceGroup>(1);
849 Set<ResourceGroup> operatorGroups = new HashSet<ResourceGroup>(1);
850 adminGroups.add(new ResourceGroup(groupName, Privilege.WRITE));
851 operatorGroups.add(new ResourceGroup(groupName, Privilege.READ));
852 groupsAuthorizations.put(containerAdminRole, adminGroups);
853 groupsAuthorizations.put(containerOperatorRole, operatorGroups);
854 roles.put(containerAdminRole, AppRoleLevel.APPADMIN);
855 roles.put(containerOperatorRole, AppRoleLevel.APPOPERATOR);
856 // Update the all containers resource group
857 allContainerSet.add(containerName);
859 // Update resource groups in cluster
860 resourceGroups.put(allResourcesGroupName, allContainerSet);
864 * Notify ContainerAware listeners of the creation/deletion of the container
866 * @param containerName
868 * true is container was removed, false otherwise
870 private void notifyContainerAwareListeners(String containerName, boolean delete) {
871 // Back-end World: container name forced to lower case
872 String name = containerName.toLowerCase(Locale.ENGLISH);
874 synchronized (this.iContainerAware) {
875 for (IContainerAware i : this.iContainerAware) {
877 i.containerDestroy(name);
879 i.containerCreate(name);
886 * Notify the ContainerListener listeners in case the container mode has
887 * changed following a container configuration operation Note: this call
888 * must happen after the configuration db has been updated
890 * @param lastActionDelete
891 * true if the last container configuration operation was a
892 * container delete operation
894 * if true, the notification is also sent to the
895 * IContainerLocalListener classes besides the IContainerListener
898 private void notifyContainerModeChange(boolean lastActionDelete, boolean notifyLocal) {
899 if (lastActionDelete == false && containerConfigs.size() == 1) {
900 logger.info("First container Creation. Inform listeners");
901 synchronized (this.iContainerListener) {
902 for (IContainerListener i : this.iContainerListener) {
903 i.containerModeUpdated(UpdateType.ADDED);
907 synchronized (this.iContainerLocalListener) {
908 for (IContainerLocalListener i : this.iContainerLocalListener) {
909 i.containerModeUpdated(UpdateType.ADDED);
913 } else if (lastActionDelete == true && containerConfigs.isEmpty()) {
914 logger.info("Last container Deletion. Inform listeners");
915 synchronized (this.iContainerListener) {
916 for (IContainerListener i : this.iContainerListener) {
917 i.containerModeUpdated(UpdateType.REMOVED);
921 synchronized (this.iContainerLocalListener) {
922 for (IContainerLocalListener i : this.iContainerLocalListener) {
923 i.containerModeUpdated(UpdateType.REMOVED);
930 private Status addRemoveContainerEntries(String containerName, List<String> nodeConnectorsString, boolean delete) {
931 // Construct action message
932 String action = String.format("Node connector(s) %s container %s: %s", delete ? "removal from" : "addition to",
933 containerName, nodeConnectorsString);
936 if (nodeConnectorsString == null || nodeConnectorsString.isEmpty()) {
937 return new Status(StatusCode.BADREQUEST, "Node connector list is null or empty");
941 ContainerConfig entryConf = containerConfigs.get(containerName);
942 if (entryConf == null) {
943 String msg = String.format("Container not found: %s", containerName);
944 String error = String.format("Failed to apply %s: (%s)", action, msg);
946 return new Status(StatusCode.NOTFOUND, msg);
950 Status status = ContainerConfig.validateNodeConnectors(nodeConnectorsString);
951 if (!status.isSuccess()) {
952 String error = String.format("Failed to apply %s: (%s)", action, status.getDescription());
957 List<NodeConnector> nodeConnectors = ContainerConfig.nodeConnectorsFromString(nodeConnectorsString);
959 // Port sharing check
962 * Check if the ports being added to this container already belong to
963 * other containers. If so check whether the the appropriate flow specs
964 * are configured on this container
966 status = validatePortSharing(containerName, nodeConnectors);
967 if (!status.isSuccess()) {
968 String error = String.format("Failed to apply %s: (%s)", action, status.getDescription());
975 status = updateContainerEntryDatabase(containerName, nodeConnectors, delete);
976 if (!status.isSuccess()) {
977 String error = String.format("Failed to apply %s: (%s)", action, status.getDescription());
982 // Update Configuration
983 status = (delete) ? entryConf.removeNodeConnectors(nodeConnectorsString) : entryConf
984 .addNodeConnectors(nodeConnectorsString);
985 if (!status.isSuccess()) {
986 String error = String.format("Failed to modify config for %s: (%s)", action, status.getDescription());
988 // Revert backend changes
989 Status statusRevert = updateContainerEntryDatabase(containerName, nodeConnectors, !delete);
990 if (!statusRevert.isSuccess()) {
992 logger.error("Failed to revert changes in database (CRITICAL)");
997 // Update cluster Configuration cache
998 containerConfigs.put(containerName, entryConf);
1000 // Notify global and local listeners
1001 UpdateType update = (delete) ? UpdateType.REMOVED : UpdateType.ADDED;
1002 notifyContainerEntryChangeInternal(containerName, nodeConnectors, update, true);
1003 // Trigger cluster notification
1004 containerChangeEvents.put(containerName, new NodeConnectorsChangeEvent(nodeConnectors, update));
1009 private void notifyContainerChangeInternal(ContainerConfig conf, UpdateType update, boolean notifyLocal) {
1010 String containerName = conf.getContainerName();
1011 logger.trace("Notifying listeners on {} for container {}", update, containerName);
1012 // Back-end World: container name forced to lower case
1013 String container = containerName.toLowerCase(Locale.ENGLISH);
1014 boolean delete = (update == UpdateType.REMOVED);
1015 // Check if a container mode change notification is needed
1016 notifyContainerModeChange(delete, notifyLocal);
1018 notifyContainerAwareListeners(container, delete);
1021 * This is a quick fix until configuration service becomes the
1022 * centralized configuration management place. Here container manager
1023 * will remove the startup files for all the bundles that are present in
1024 * the container being deleted. Do the cleanup here in Container manger
1025 * as do not want to put this temporary code in Configuration manager
1029 // TODO: remove when Config Mgr takes over
1030 removeComponentsStartUpfiles(containerName);
1034 private void notifyContainerEntryChangeInternal(String containerName, List<NodeConnector> ncList, UpdateType update, boolean notifyLocal) {
1035 logger.trace("Notifying listeners on {} for ports {} in container {}", update, ncList, containerName);
1036 // Back-end World: container name forced to lower case
1037 String container = containerName.toLowerCase(Locale.ENGLISH);
1038 for (NodeConnector nodeConnector : ncList) {
1039 // Now signal that the port has been added/removed
1040 synchronized (this.iContainerListener) {
1041 for (IContainerListener i : this.iContainerListener) {
1042 i.nodeConnectorUpdated(container, nodeConnector, update);
1045 // Check if the Functional Modules need to be notified as well
1047 synchronized (this.iContainerLocalListener) {
1048 for (IContainerLocalListener i : this.iContainerLocalListener) {
1049 i.nodeConnectorUpdated(container, nodeConnector, update);
1056 private void notifyCFlowChangeInternal(String containerName, List<ContainerFlowConfig> confList, UpdateType update,
1057 boolean notifyLocal) {
1058 logger.trace("Notifying listeners on {} for flow specs {} in container {}", update, confList, containerName);
1059 // Back-end World: container name forced to lower case
1060 String container = containerName.toLowerCase(Locale.ENGLISH);
1062 for (ContainerFlowConfig conf : confList) {
1063 for (Match match : conf.getMatches()) {
1064 ContainerFlow cFlow = new ContainerFlow(match);
1065 synchronized (this.iContainerListener) {
1066 for (IContainerListener i : this.iContainerListener) {
1067 i.containerFlowUpdated(container, cFlow, cFlow, update);
1070 // Check if the Functional Modules need to be notified as well
1072 synchronized (this.iContainerLocalListener) {
1073 for (IContainerLocalListener i : this.iContainerLocalListener) {
1074 i.containerFlowUpdated(container, cFlow, cFlow, update);
1082 private Status addRemoveContainerFlow(String containerName, List<ContainerFlowConfig> cFlowConfList, boolean delete) {
1083 // Construct action message
1084 String action = String.format("Flow spec(s) %s container %s: %s", delete ? "removal from" : "addition to",
1085 containerName, cFlowConfList);
1088 ContainerConfig containerConfig = this.containerConfigs.get(containerName);
1089 if (containerConfig == null) {
1090 String msg = String.format("Container not found: %s", containerName);
1091 String error = String.format("Failed to apply %s: (%s)", action, msg);
1093 return new Status(StatusCode.NOTFOUND, "Container not present");
1096 // Validity check, check for overlaps on current container configuration
1097 Status status = containerConfig.validateContainerFlowModify(cFlowConfList, delete);
1098 if (!status.isSuccess()) {
1099 String msg = status.getDescription();
1100 String error = String.format("Failed to apply %s: (%s)", action, msg);
1102 return new Status(StatusCode.BADREQUEST, msg);
1105 // Validate the operation in terms to the port sharing with other containers
1106 for (ContainerFlowConfig conf : cFlowConfList) {
1107 for (Match match : conf.getMatches()) {
1108 ContainerFlow cFlow = new ContainerFlow(match);
1109 status = validateContainerFlowAddRemoval(containerName, cFlow, delete);
1110 if (!status.isSuccess()) {
1111 String msg = "Validation failed: " + status.getDescription();
1112 String error = String.format("Failed to apply %s: (%s)", action, msg);
1114 return new Status(StatusCode.BADREQUEST, msg);
1120 status = updateContainerFlow(containerName, cFlowConfList, delete);
1121 if (!status.isSuccess()) {
1122 String error = String.format("Failed to apply %s: (%s)", action, status.getDescription());
1123 logger.error(error);
1127 // Update Configuration
1128 status = (delete) ? containerConfig.removeContainerFlows(cFlowConfList) : containerConfig
1129 .addContainerFlows(cFlowConfList);
1130 if (!status.isSuccess()) {
1131 String error = String.format("Failed to modify config for %s: (%s)", action, status.getDescription());
1132 logger.error(error);
1133 // Revert backend changes
1134 Status statusRevert = updateContainerFlow(containerName, cFlowConfList, !delete);
1135 if (!statusRevert.isSuccess()) {
1137 logger.error("Failed to revert changes in database (CRITICAL)");
1141 // Update cluster cache
1142 this.containerConfigs.put(containerName, containerConfig);
1144 // Notify global and local listeners
1145 UpdateType update = (delete) ? UpdateType.REMOVED : UpdateType.ADDED;
1146 notifyCFlowChangeInternal(containerName, cFlowConfList, update, true);
1147 // Trigger cluster notification
1148 containerChangeEvents.put(containerName, new ContainerFlowChangeEvent(cFlowConfList, update));
1153 private Status addRemoveContainer(ContainerConfig containerConf, boolean delete) {
1154 // Construct action message
1155 String action = String.format("Container %s", delete ? "removal" : "creation");
1157 // Valid configuration check
1158 Status status = null;
1159 String error = (containerConfigs == null) ? String.format("Invalid %s configuration: (null config object)", action)
1160 : (!(status = containerConf.validate()).isSuccess()) ? String.format("Invalid %s configuration: (%s)",
1161 action, status.getDescription()) : null;
1162 if (error != null) {
1164 return new Status(StatusCode.BADREQUEST, error);
1167 // Configuration presence check
1168 String containerName = containerConf.getContainerName();
1170 if (!containerConfigs.containsKey(containerName)) {
1171 String msg = String.format("%s Failed: (Container does not exist: %s)", action, containerName);
1173 return new Status(StatusCode.NOTFOUND, msg);
1176 if (containerConfigs.containsKey(containerName)) {
1177 String msg = String.format("%s Failed: (Container already exist: %s)", action, containerName);
1179 return new Status(StatusCode.CONFLICT, msg);
1184 * The proposed container configuration could be a complex one containing
1185 * both ports and flow spec. If so, check if it has shared ports with
1186 * other existing containers. If that is the case verify flow spec isolation
1187 * is in place. No need to check on flow spec validation first. This
1188 * would take care of both
1191 status = validatePortSharing(containerConf);
1192 if (!status.isSuccess()) {
1193 error = String.format("%s Failed: (%s)", action, status.getDescription());
1194 logger.error(error);
1200 status = updateContainerDatabase(containerConf, delete);
1202 // Abort and exit here if back-end database update failed
1203 if (!status.isSuccess()) {
1208 * Update Configuration: This will trigger the notifications on cache
1209 * update callback locally and on the other cluster nodes
1212 this.containerConfigs.remove(containerName);
1214 this.containerConfigs.put(containerName, containerConf);
1217 // Automatically create and populate user and resource groups
1218 updateResourceGroups(containerConf, delete);
1220 // Notify global and local listeners
1221 UpdateType update = (delete) ? UpdateType.REMOVED : UpdateType.ADDED;
1222 notifyContainerChangeInternal(containerConf, update, true);
1224 // Trigger cluster notification
1225 containerChangeEvents.put(containerName, new ContainerChangeEvent(containerConf, update));
1227 if (update == UpdateType.ADDED) {
1228 if (containerConf.hasFlowSpecs()) {
1229 List<ContainerFlowConfig> specList = containerConf.getContainerFlowConfigs();
1230 // Notify global and local listeners about flow spec addition
1231 notifyCFlowChangeInternal(containerName, specList, update, true);
1233 // Trigger cluster notification
1234 containerChangeEvents.put(containerName, new ContainerFlowChangeEvent(specList, update));
1237 if (containerConf.hasNodeConnectors()) {
1238 List<NodeConnector> ncList = containerConf.getPortList();
1239 // Notify global and local listeners about port(s) addition
1240 notifyContainerEntryChangeInternal(containerName, ncList, update, true);
1241 // Trigger cluster notification
1242 containerChangeEvents.put(containerName, new NodeConnectorsChangeEvent(ncList, update));
1247 clusterServices.removeContainerCaches(containerName);
1253 public Status addContainer(ContainerConfig containerConf) {
1254 return addRemoveContainer(containerConf, false);
1258 public Status removeContainer(ContainerConfig containerConf) {
1259 return addRemoveContainer(containerConf, true);
1263 public Status removeContainer(String containerName) {
1264 // Construct action message
1265 String action = String.format("Container removal: %s", containerName);
1267 ContainerConfig containerConf = containerConfigs.get(containerName);
1268 if (containerConf == null) {
1269 String msg = String.format("Container not found");
1270 String error = String.format("Failed to apply %s: (%s)", action, msg);
1272 return new Status(StatusCode.NOTFOUND, msg);
1274 return addRemoveContainer(containerConf, true);
1278 public Status addContainerEntry(String containerName, List<String> nodeConnectors) {
1279 return addRemoveContainerEntries(containerName, nodeConnectors, false);
1283 public Status removeContainerEntry(String containerName, List<String> nodeConnectors) {
1284 return addRemoveContainerEntries(containerName, nodeConnectors, true);
1288 public Status addContainerFlows(String containerName, List<ContainerFlowConfig> fSpecConf) {
1289 return addRemoveContainerFlow(containerName, fSpecConf, false);
1293 public Status removeContainerFlows(String containerName, List<ContainerFlowConfig> fSpecConf) {
1294 return addRemoveContainerFlow(containerName, fSpecConf, true);
1298 public Status removeContainerFlows(String containerName, Set<String> names) {
1299 // Construct action message
1300 String action = String.format("Flow spec(s) removal from container %s: %s", containerName, names);
1303 ContainerConfig sc = containerConfigs.get(containerName);
1305 String msg = String.format("Container not found: %s", containerName);
1306 String error = String.format("Failed to apply %s: (%s)", action, msg);
1308 return new Status(StatusCode.NOTFOUND, msg);
1310 List<ContainerFlowConfig> list = sc.getContainerFlowConfigs(names);
1311 if (list.isEmpty() || list.size() != names.size()) {
1312 String msg = String.format("Cannot find all the specified flow specs");
1313 String error = String.format("Failed to apply %s: (%s)", action, msg);
1315 return new Status(StatusCode.BADREQUEST, msg);
1317 return addRemoveContainerFlow(containerName, list, true);
1321 public List<ContainerFlowConfig> getContainerFlows(String containerName) {
1322 ContainerConfig sc = containerConfigs.get(containerName);
1323 return (sc == null) ? new ArrayList<ContainerFlowConfig>(0) : sc.getContainerFlowConfigs();
1327 public List<String> getContainerFlowNameList(String containerName) {
1328 ContainerConfig sc = containerConfigs.get(containerName);
1329 return (sc == null) ? new ArrayList<String>(0) : sc.getContainerFlowConfigsNames();
1333 public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
1334 // Perform the class deserialization locally, from inside the package
1335 // where the class is defined
1336 return ois.readObject();
1339 @SuppressWarnings("unchecked")
1340 private void loadContainerConfig() {
1341 ObjectReader objReader = new ObjectReader();
1342 ConcurrentMap<String, ContainerConfig> configMap = (ConcurrentMap<String, ContainerConfig>) objReader.read(this,
1343 containersFileName);
1345 if (configMap == null) {
1349 for (Map.Entry<String, ContainerConfig> configEntry : configMap.entrySet()) {
1350 addContainer(configEntry.getValue());
1354 public void _psc(CommandInterpreter ci) {
1355 for (Map.Entry<String, ContainerConfig> entry : containerConfigs.entrySet()) {
1356 ContainerConfig sc = entry.getValue();
1357 ci.println(String.format("%s: %s", sc.getContainerName(), sc.toString()));
1359 ci.println("Total number of containers: " + containerConfigs.entrySet().size());
1362 public void _pfc(CommandInterpreter ci) {
1363 for (Map.Entry<String, ContainerConfig> entry : containerConfigs.entrySet()) {
1364 ContainerConfig sc = entry.getValue();
1365 ci.println(String.format("%s: %s", sc.getContainerName(), sc.getContainerFlowConfigs()));
1369 public void _psd(CommandInterpreter ci) {
1370 for (String containerName : containerData.keySet()) {
1371 ContainerData sd = containerData.get(containerName);
1372 for (Node sid : sd.getSwPorts().keySet()) {
1373 Set<NodeConnector> s = sd.getSwPorts().get(sid);
1374 ci.println("\t" + sid + " : " + s);
1377 for (ContainerFlow s : sd.getContainerFlowSpecs()) {
1378 ci.println("\t" + s.toString());
1383 public void _psp(CommandInterpreter ci) {
1384 for (NodeConnector sp : nodeConnectorToContainers.keySet()) {
1385 ci.println(nodeConnectorToContainers.get(sp));
1389 public void _psm(CommandInterpreter ci) {
1390 for (Node sp : nodeToContainers.keySet()) {
1391 ci.println(nodeToContainers.get(sp));
1395 public void _addContainer(CommandInterpreter ci) {
1396 String containerName = ci.nextArgument();
1397 if (containerName == null) {
1398 ci.print("Container Name not specified");
1401 String staticVlan = ci.nextArgument();
1402 ContainerConfig containerConfig = new ContainerConfig(containerName, staticVlan, null, null);
1403 ci.println(this.addRemoveContainer(containerConfig, false));
1406 public void _createContainer(CommandInterpreter ci) {
1407 String containerName = ci.nextArgument();
1408 if (containerName == null) {
1409 ci.print("Container Name not specified");
1412 String staticVlan = ci.nextArgument();
1413 if (staticVlan == null) {
1414 ci.print("Static Vlan not specified");
1417 List<String> ports = new ArrayList<String>();
1418 for (long l = 1L; l < 10L; l++) {
1419 ports.add(NodeConnectorCreator.createOFNodeConnector((short) 1, NodeCreator.createOFNode(l)).toString());
1421 List<ContainerFlowConfig> cFlowList = new ArrayList<ContainerFlowConfig>();
1422 cFlowList.add(this.createSampleContainerFlowConfig("tcp", true));
1423 ContainerConfig containerConfig = new ContainerConfig(containerName, staticVlan, ports, cFlowList);
1424 ci.println(this.addRemoveContainer(containerConfig, false));
1427 public void _removeContainer(CommandInterpreter ci) {
1428 String containerName = ci.nextArgument();
1429 if (containerName == null) {
1430 ci.print("Container Name not specified");
1433 ContainerConfig containerConfig = new ContainerConfig(containerName, "", null, null);
1434 ci.println(this.addRemoveContainer(containerConfig, true));
1437 public void _addContainerEntry(CommandInterpreter ci) {
1438 String containerName = ci.nextArgument();
1439 if (containerName == null) {
1440 ci.print("Container Name not specified");
1443 String nodeId = ci.nextArgument();
1444 if (nodeId == null) {
1445 ci.print("Node Id not specified");
1448 String portId = ci.nextArgument();
1449 if (portId == null) {
1450 ci.print("Port not specified");
1453 Node node = NodeCreator.createOFNode(Long.valueOf(nodeId));
1454 Short port = Short.valueOf(portId);
1455 NodeConnector nc = NodeConnectorCreator.createOFNodeConnector(port, node);
1456 List<String> portList = new ArrayList<String>(1);
1457 portList.add(nc.toString());
1458 ci.println(this.addRemoveContainerEntries(containerName, portList, false));
1461 public void _removeContainerEntry(CommandInterpreter ci) {
1462 String containerName = ci.nextArgument();
1463 if (containerName == null) {
1464 ci.print("Container Name not specified");
1467 String nodeId = ci.nextArgument();
1468 if (nodeId == null) {
1469 ci.print("Node Id not specified");
1472 String portId = ci.nextArgument();
1473 if (portId == null) {
1474 ci.print("Port not specified");
1477 Node node = NodeCreator.createOFNode(Long.valueOf(nodeId));
1478 Short port = Short.valueOf(portId);
1479 NodeConnector nc = NodeConnectorCreator.createOFNodeConnector(port, node);
1480 List<String> portList = new ArrayList<String>(1);
1481 portList.add(nc.toString());
1482 ci.println(this.addRemoveContainerEntries(containerName, portList, true));
1485 private ContainerFlowConfig createSampleContainerFlowConfig(String cflowName, boolean boolUnidirectional) {
1486 ContainerFlowConfig cfg = new ContainerFlowConfig(cflowName, "9.9.1.0/24", "19.9.1.2", "TCP", "1234", "25");
1490 public void _addContainerFlow(CommandInterpreter ci) {
1491 String containerName = ci.nextArgument();
1492 if (containerName == null) {
1493 ci.print("Container Name not specified");
1496 String cflowName = ci.nextArgument();
1497 if (cflowName == null) {
1498 ci.print("cflowName not specified");
1501 String unidirectional = ci.nextArgument();
1502 boolean boolUnidirectional = Boolean.parseBoolean(unidirectional);
1503 List<ContainerFlowConfig> list = new ArrayList<ContainerFlowConfig>();
1504 list.add(createSampleContainerFlowConfig(cflowName, boolUnidirectional));
1505 ci.println(this.addRemoveContainerFlow(containerName, list, false));
1508 public void _removeContainerFlow(CommandInterpreter ci) {
1509 String containerName = ci.nextArgument();
1510 if (containerName == null) {
1511 ci.print("Container Name not specified");
1514 String cflowName = ci.nextArgument();
1515 if (cflowName == null) {
1516 ci.print("cflowName not specified");
1519 Set<String> set = new HashSet<String>(1);
1521 ci.println(this.removeContainerFlows(containerName, set));
1525 public String getHelp() {
1526 StringBuffer help = new StringBuffer();
1527 help.append("---ContainerManager Testing---\n");
1528 help.append("\tpsc - Print ContainerConfigs\n");
1529 help.append("\tpfc - Print FlowSpecConfigs\n");
1530 help.append("\tpsd - Print ContainerData\n");
1531 help.append("\tpsp - Print nodeConnectorToContainers\n");
1532 help.append("\tpsm - Print nodeToContainers\n");
1533 help.append("\t addContainer <containerName> <staticVlan> \n");
1534 help.append("\t removeContainer <containerName> \n");
1535 help.append("\t addContainerEntry <containerName> <nodeId> <port> \n");
1536 help.append("\t removeContainerEntry <containerName> <nodeId> <port> \n");
1537 help.append("\t addContainerFlow <containerName> <cflowName> <unidirectional true/false>\n");
1538 help.append("\t removeContainerFlow <containerName> <cflowName> \n");
1539 return help.toString();
1543 public boolean doesContainerExist(String containerName) {
1544 // Test for default container
1545 if (GlobalConstants.DEFAULT.toString().equalsIgnoreCase(containerName)) {
1548 // Test for non-default one
1549 return (getContainerByName(containerName) != null);
1553 public ContainerData getContainerData(String containerName) {
1554 return (getContainerByName(containerName));
1558 public Status saveConfiguration() {
1559 return saveContainerConfig();
1562 public void _containermgrGetRoles(CommandInterpreter ci) {
1563 ci.println("Configured roles for Container Mgr:");
1564 List<String> list = this.getRoles();
1565 for (String role : list) {
1566 ci.println(role + "\t" + roles.get(role));
1570 public void _containermgrGetAuthorizedGroups(CommandInterpreter ci) {
1571 String roleName = ci.nextArgument();
1572 if (roleName == null || roleName.trim().isEmpty()) {
1573 ci.println("Invalid argument");
1574 ci.println("mmGetAuthorizedGroups <role_name>");
1577 ci.println("Resource Groups associated to role " + roleName + ":");
1578 List<ResourceGroup> list = this.getAuthorizedGroups(roleName);
1579 for (ResourceGroup group : list) {
1580 ci.println(group.toString());
1584 public void _containermgrGetAuthorizedResources(CommandInterpreter ci) {
1585 String roleName = ci.nextArgument();
1586 if (roleName == null || roleName.trim().isEmpty()) {
1587 ci.println("Invalid argument");
1588 ci.println("mmGetAuthorizedResources <role_name>");
1591 ci.println("Resource associated to role " + roleName + ":");
1592 List<Resource> list = this.getAuthorizedResources(roleName);
1593 for (Resource resource : list) {
1594 ci.println(resource.toString());
1598 public void _containermgrGetResourcesForGroup(CommandInterpreter ci) {
1599 String groupName = ci.nextArgument();
1600 if (groupName == null || groupName.trim().isEmpty()) {
1601 ci.println("Invalid argument");
1602 ci.println("containermgrResourcesForGroup <group_name>");
1605 ci.println("Group " + groupName + " contains the following resources:");
1606 List<Object> resources = this.getResources(groupName);
1607 for (Object resource : resources) {
1608 ci.println(resource.toString());
1612 public void _containermgrGetUserLevel(CommandInterpreter ci) {
1613 String userName = ci.nextArgument();
1614 if (userName == null || userName.trim().isEmpty()) {
1615 ci.println("Invalid argument");
1616 ci.println("containermgrGetUserLevel <user_name>");
1619 ci.println("User " + userName + " has level: " + this.getUserLevel(userName));
1622 public void _containermgrGetUserResources(CommandInterpreter ci) {
1623 String userName = ci.nextArgument();
1624 if (userName == null || userName.trim().isEmpty()) {
1625 ci.println("Invalid argument");
1626 ci.println("containermgrGetUserResources <user_name>");
1629 ci.println("User " + userName + " owns the following resources: ");
1630 Set<Resource> resources = this.getAllResourcesforUser(userName);
1631 for (Resource resource : resources) {
1632 ci.println(resource.toString());
1637 * For scalability testing where as of now controller gui is unresponsive
1638 * providing here an osgi hook to trigger the save config so that DT do not
1639 * have to reaply the scalable configuration each time they restart the
1642 // TODO: remove when no longer needed
1643 public void _saveConfig(CommandInterpreter ci) {
1644 Status status = new Status(StatusCode.NOSERVICE, "Configuration service not reachable");
1646 IConfigurationService configService = (IConfigurationService) ServiceHelper.getGlobalInstance(
1647 IConfigurationService.class, this);
1648 if (configService != null) {
1649 status = configService.saveConfigurations();
1651 ci.println(status.toString());
1655 public List<String> getContainerNames() {
1656 return getContainerNameList();
1660 public boolean hasNonDefaultContainer() {
1661 return !containerConfigs.keySet().isEmpty();
1665 public boolean inContainerMode() {
1666 return this.containerConfigs.size() > 0;