Fix typo in messages in ContainerManager
[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.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;
67
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;
75
76 public class ContainerManager extends Authorization<String> implements IContainerManager, IObjectReader,
77         CommandProvider, ICacheUpdateAware<String, Object>, IContainerInternal, IContainerAuthorization,
78         IConfigurationAware {
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;
84     /*
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
88      */
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>());
99
100     void setIContainerListener(IContainerListener s) {
101         if (this.iContainerListener != null) {
102             this.iContainerListener.add(s);
103             /*
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.
109              */
110             if (!this.containerData.isEmpty()) {
111                 s.containerModeUpdated(UpdateType.ADDED);
112             }
113             for (ConcurrentMap.Entry<NodeConnector, CopyOnWriteArrayList<String>> entry : nodeConnectorToContainers
114                     .entrySet()) {
115                 NodeConnector port = entry.getKey();
116                 for (String container : entry.getValue()) {
117                     s.nodeConnectorUpdated(container, port, UpdateType.ADDED);
118                 }
119             }
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);
123                 }
124             }
125         }
126     }
127
128     void unsetIContainerListener(IContainerListener s) {
129         if (this.iContainerListener != null) {
130             this.iContainerListener.remove(s);
131         }
132     }
133
134     void setIContainerLocalListener(IContainerLocalListener s) {
135         if (this.iContainerLocalListener != null) {
136             this.iContainerLocalListener.add(s);
137         }
138     }
139
140     void unsetIContainerLocalListener(IContainerLocalListener s) {
141         if (this.iContainerLocalListener != null) {
142             this.iContainerLocalListener.remove(s);
143         }
144     }
145
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));
152             }
153         }
154     }
155
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
160         // component itself
161     }
162
163     public void setClusterServices(IClusterGlobalServices i) {
164         this.clusterServices = i;
165         logger.debug("IClusterServices set");
166     }
167
168     public void unsetClusterServices(IClusterGlobalServices i) {
169         if (this.clusterServices == i) {
170             this.clusterServices = null;
171             logger.debug("IClusterServices Unset");
172         }
173     }
174
175     private void allocateCaches() {
176         logger.debug("Container Manager allocating caches");
177
178         if (clusterServices == null) {
179             logger.warn("un-initialized Cluster Services, can't allocate caches");
180             return;
181         }
182         try {
183             clusterServices.createCache("containermgr.containerConfigs", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
184
185             clusterServices.createCache("containermgr.event.containerChange",
186                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
187
188             clusterServices.createCache("containermgr.containerData", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
189
190             clusterServices.createCache("containermgr.nodeConnectorToContainers",
191                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
192
193             clusterServices.createCache("containermgr.nodeToContainers", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
194
195             clusterServices.createCache("containermgr.containerGroups", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
196
197             clusterServices.createCache("containermgr.containerAuthorizations",
198                     EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
199
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");
205         }
206     }
207
208     @SuppressWarnings({ "unchecked" })
209     private void retrieveCaches() {
210         logger.debug("Container Manager retrieving caches");
211
212         if (clusterServices == null) {
213             logger.warn("un-initialized Cluster Services, can't retrieve caches");
214             return;
215         }
216
217         containerConfigs = (ConcurrentMap<String, ContainerConfig>) clusterServices.getCache("containermgr.containerConfigs");
218
219         containerChangeEvents = (ConcurrentMap<String, Object>) clusterServices.getCache("containermgr.event.containerChange");
220
221         containerData = (ConcurrentMap<String, ContainerData>) clusterServices.getCache("containermgr.containerData");
222
223         nodeConnectorToContainers = (ConcurrentMap<NodeConnector, CopyOnWriteArrayList<String>>) clusterServices
224                 .getCache("containermgr.nodeConnectorToContainers");
225
226         nodeToContainers = (ConcurrentMap<Node, Set<String>>) clusterServices.getCache("containermgr.nodeToContainers");
227
228         resourceGroups = (ConcurrentMap<String, Set<String>>) clusterServices.getCache("containermgr.containerGroups");
229
230         groupsAuthorizations = (ConcurrentMap<String, Set<ResourceGroup>>) clusterServices
231                 .getCache("containermgr.containerAuthorizations");
232
233         roles = (ConcurrentMap<String, AppRoleLevel>) clusterServices.getCache("containermgr.roles");
234
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);
239             }
240         }
241     }
242
243     @Override
244     public void entryCreated(String containerName, String cacheName, boolean originLocal) {
245
246     }
247
248     @Override
249     public void entryUpdated(String key, Object value, String cacheName, boolean originLocal) {
250         /*
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.
258          */
259         if (!originLocal) {
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);
270             }
271         }
272     }
273
274     @Override
275     public void entryDeleted(String containerName, String cacheName, boolean originLocal) {
276     }
277
278     public ContainerManager() {
279     }
280
281     public void init() {
282
283     }
284
285     public void start() {
286         // Get caches from cluster manager
287         allocateCaches();
288         retrieveCaches();
289
290         // Allocates default groups and association to default roles
291         createDefaultAuthorizationGroups();
292
293         // Read startup configuration and create local database
294         loadConfigurations();
295     }
296
297     public void destroy() {
298         // Clear local states
299         this.iContainerAware.clear();
300         this.iContainerListener.clear();
301         this.iContainerLocalListener.clear();
302     }
303
304     /**
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.
308      */
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");
313         }
314
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);
319                 if (delete) {
320                     logger.trace("Removing Flow Spec {} from Container {}", conf.getName(), containerName);
321                     container.deleteFlowSpec(cFlow);
322                 } else {
323                     logger.trace("Adding Flow Spec {} to Container {}", conf.getName(), containerName);
324                     container.addFlowSpec(cFlow);
325
326                 }
327                 // Update Database
328                 putContainerDataByName(containerName, container);
329             }
330         }
331         return new Status(StatusCode.SUCCESS);
332     }
333
334     /**
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
339      */
340     private Status updateContainerDatabase(ContainerConfig containerConf, boolean delete) {
341         /*
342          * Back-end world here, container names are all stored in lower case
343          */
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");
348         }
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");
352         }
353         if (delete) {
354             logger.debug("Removing container {}", containerName);
355             removeNodeToContainersMapping(container);
356             removeNodeConnectorToContainersMapping(container);
357             removeContainerDataByName(containerName);
358         } else {
359             logger.debug("Adding container {}", containerName);
360             container = new ContainerData(containerConf);
361             putContainerDataByName(containerName, container);
362
363             // If flow specs are specified, add them
364             if (containerConf.hasFlowSpecs()) {
365                 updateContainerFlow(containerName, containerConf.getContainerFlowConfigs(), delete);
366             }
367
368             // If ports are specified, add them
369             if (!containerConf.getPortList().isEmpty()) {
370                 updateContainerEntryDatabase(containerName, containerConf.getPortList(), delete);
371             }
372         }
373         return new Status(StatusCode.SUCCESS);
374     }
375
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);
389                     } else {
390                         nodeConnectorToContainers.put(nc, slist);
391                     }
392                     break;
393                 }
394             }
395         }
396     }
397
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);
405                     value.remove(sdata);
406                     nodeToContainers.put(node, value);
407                     break;
408                 }
409             }
410         }
411     }
412
413     /**
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
417      */
418     private Status updateContainerEntryDatabase(String containerName, List<NodeConnector> nodeConnectors, boolean delete) {
419         ContainerData container = getContainerByName(containerName);
420         // Presence check
421         if (container == null) {
422             return new Status(StatusCode.NOTFOUND, "Container Not Found");
423         }
424
425         // Check changes in the portlist
426         for (NodeConnector port : nodeConnectors) {
427             Node node = port.getNode();
428             if (delete) {
429                 container.removePortFromSwitch(port);
430                 putContainerDataByName(containerName, container);
431
432                 /* remove <sp> - container mapping */
433                 if (nodeConnectorToContainers.containsKey(port)) {
434                     nodeConnectorToContainers.remove(port);
435                 }
436                 /*
437                  * If no more ports in the switch, remove switch from container
438                  * Generate switchRemoved Event
439                  */
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);
445                     if (slist != null) {
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);
452                         }
453                     }
454                 }
455             } else {
456                 if (container.isSwitchInContainer(node) == false) {
457                     Set<String> value = nodeToContainers.get(node);
458                     // Add node->containers mapping
459                     if (value == null) {
460                         value = new HashSet<String>();
461                         logger.debug("Creating new Container Set for switch {}", node);
462                     }
463                     value.add(container.getContainerName());
464                     nodeToContainers.put(node, value);
465                 }
466                 container.addPortToSwitch(port);
467                 putContainerDataByName(containerName, container);
468
469                 // added nc->containers mapping
470                 CopyOnWriteArrayList<String> slist = nodeConnectorToContainers.get(port);
471                 if (slist == null) {
472                     slist = new CopyOnWriteArrayList<String>();
473                 }
474                 slist.add(container.getContainerName());
475                 nodeConnectorToContainers.put(port, slist);
476             }
477         }
478         return new Status(StatusCode.SUCCESS);
479     }
480
481     private Status validateContainerFlowAddRemoval(String containerName, ContainerFlow cFlow, boolean delete) {
482         /*
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.
491          */
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);
495             logger.warn(error);
496             return new Status(StatusCode.BADREQUEST, error);
497         }
498
499         if (delete) {
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())) {
504                     continue;
505                 }
506                 // Derive the common ports
507                 Set<NodeConnector> commonPorts = entry.getValue().getNodeConnectors();
508                 commonPorts.retainAll(thisContainerPorts);
509                 if (commonPorts.isEmpty()) {
510                     continue;
511                 }
512
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
518                         // is a failure
519                         // regardless the shared ports are host facing or
520                         // interswitch ports
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");
524                     }
525
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");
532                     }
533                     for (NodeConnector nc : commonPorts) {
534                         /*
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
539                          */
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));
544                         }
545                     }
546                 }
547             }
548         } else {
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());
553             proposed.add(cFlow);
554             for (Map.Entry<String, ContainerData> entry : containerData.entrySet()) {
555                 if (containerName.equalsIgnoreCase(entry.getKey())) {
556                     continue;
557                 }
558                 ContainerData otherContainer = entry.getValue();
559                 Set<NodeConnector> commonPorts = otherContainer.getNodeConnectors();
560                 commonPorts.retainAll(thisContainerPorts);
561
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()));
568                     }
569                 }
570             }
571         }
572
573         return new Status(StatusCode.SUCCESS);
574     }
575
576     /**
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.
579      *
580      * @param containerName
581      *            the name of the existing container
582      * @param portList
583      *            the list of node connectors to be added to the container
584      * @return the status object representing the result of the check
585      */
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);
591             logger.error(error);
592             return new Status(StatusCode.BADREQUEST, error);
593         }
594         return validatePortSharingInternal(portList, container.getContainerFlowSpecs());
595     }
596
597     /**
598      * Checks if the proposed container configuration is valid to be applied in
599      * terms of port sharing with other containers.
600      *
601      * @param containerConf
602      *            the container configuration object containing the list of node
603      *            connectors
604      * @return the status object representing the result of the check
605      */
606     private Status validatePortSharing(ContainerConfig containerConf) {
607         return validatePortSharingInternal(containerConf.getPortList(), containerConf.getContainerFlowSpecs());
608     }
609
610     /*
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.
615      */
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) {
621                     String msg = null;
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);
629                     }
630                     if (msg != null) {
631                         logger.debug(msg);
632                         return new Status(StatusCode.BADREQUEST, msg);
633                     }
634                 }
635             }
636         }
637         return new Status(StatusCode.SUCCESS);
638     }
639
640     /**
641      * Utility function to check if two lists of container flows share any same
642      * or overlapping container flows.
643      *
644      * @param oneFlowList
645      *            One of the two lists of container flows to test
646      * @param twoFlowList
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
650      *         check.
651      */
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()));
658                 }
659             }
660         }
661         return new Status(StatusCode.SUCCESS);
662     }
663
664     /**
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.
668      *
669      * @param name
670      *            The container name in any case
671      * @return The corresponding ContainerData object
672      */
673     private ContainerData getContainerByName(String name) {
674         return containerData.get(name.toLowerCase(Locale.ENGLISH));
675     }
676
677     /**
678      * Add a ContainerData object for the given container name.
679      *
680      * @param name
681      *            The container name in any case
682      * @param sData
683      *            The container data object
684      */
685     private void putContainerDataByName(String name, ContainerData sData) {
686         containerData.put(name.toLowerCase(Locale.ENGLISH), sData);
687     }
688
689     /**
690      * Removes the ContainerData object for the given container name.
691      *
692      * @param name
693      *            The container name in any case
694      */
695     private void removeContainerDataByName(String name) {
696         containerData.remove(name.toLowerCase(Locale.ENGLISH));
697     }
698
699     @Override
700     public List<ContainerConfig> getContainerConfigList() {
701         return new ArrayList<ContainerConfig>(containerConfigs.values());
702     }
703
704     @Override
705     public ContainerConfig getContainerConfig(String containerName) {
706         ContainerConfig target = containerConfigs.get(containerName);
707         return (target == null) ? null : new ContainerConfig(target);
708     }
709
710     @Override
711     public List<String> getContainerNameList() {
712         /*
713          * Return container names as they were configured by user (case sensitive)
714          * along with the default container
715          */
716         List<String> containerNameList = new ArrayList<String>();
717         containerNameList.add(GlobalConstants.DEFAULT.toString());
718         containerNameList.addAll(containerConfigs.keySet());
719         return containerNameList;
720     }
721
722     @Override
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);
728         }
729         return flowSpecConfig;
730     }
731
732     private void loadConfigurations() {
733         /*
734          * Read containers, container flows and finally containers' entries from file
735          * and program the database accordingly
736          */
737         if (containerConfigs.isEmpty()) {
738             loadContainerConfig();
739         }
740     }
741
742     private Status saveContainerConfig() {
743         return saveContainerConfigLocal();
744     }
745
746     public Status saveContainerConfigLocal() {
747         ObjectWriter objWriter = new ObjectWriter();
748
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());
753         }
754         return new Status(StatusCode.SUCCESS);
755     }
756
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));
760
761         File directory = new File(startupLocation);
762         String[] fileList = directory.list();
763
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);
772                 }
773             }
774         }
775     }
776
777     /**
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
781      */
782     private void createDefaultAuthorizationGroups() {
783         allResourcesGroupName = ContainerManager.allContainersGroup;
784
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);
792             // Update cluster
793             resourceGroups.put(allResourcesGroupName, allContainers);
794         }
795
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);
799         }
800         if (!roles.containsKey(UserLevel.NETWORKADMIN.toString())) {
801             roles.put(UserLevel.NETWORKADMIN.toString(), AppRoleLevel.APPADMIN);
802         }
803         if (!roles.containsKey(UserLevel.NETWORKOPERATOR.toString())) {
804             roles.put(UserLevel.NETWORKOPERATOR.toString(), AppRoleLevel.APPOPERATOR);
805         }
806
807         /*
808          * Create and add the all containers user groups and associate them to the
809          * default well known user roles, if not present already
810          */
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);
819         }
820     }
821
822     /**
823      * Until manual configuration is not available, automatically maintain the
824      * well known resource groups
825      *
826      * @param containerName
827      * @param delete
828      */
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);
836         if (delete) {
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);
844         } else {
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);
858         }
859         // Update resource groups in cluster
860         resourceGroups.put(allResourcesGroupName, allContainerSet);
861     }
862
863     /**
864      * Notify ContainerAware listeners of the creation/deletion of the container
865      *
866      * @param containerName
867      * @param delete
868      *            true is container was removed, false otherwise
869      */
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);
873
874         synchronized (this.iContainerAware) {
875             for (IContainerAware i : this.iContainerAware) {
876                 if (delete) {
877                     i.containerDestroy(name);
878                 } else {
879                     i.containerCreate(name);
880                 }
881             }
882         }
883     }
884
885     /**
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
889      *
890      * @param lastActionDelete
891      *            true if the last container configuration operation was a
892      *            container delete operation
893      * @param notifyLocal
894      *            if true, the notification is also sent to the
895      *            IContainerLocalListener classes besides the IContainerListener
896      *            classes
897      */
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);
904                 }
905             }
906             if (notifyLocal) {
907                 synchronized (this.iContainerLocalListener) {
908                     for (IContainerLocalListener i : this.iContainerLocalListener) {
909                         i.containerModeUpdated(UpdateType.ADDED);
910                     }
911                 }
912             }
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);
918                 }
919             }
920             if (notifyLocal) {
921                 synchronized (this.iContainerLocalListener) {
922                     for (IContainerLocalListener i : this.iContainerLocalListener) {
923                         i.containerModeUpdated(UpdateType.REMOVED);
924                     }
925                 }
926             }
927         }
928     }
929
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);
934
935         // Validity Check
936         if (nodeConnectorsString == null || nodeConnectorsString.isEmpty()) {
937             return new Status(StatusCode.BADREQUEST, "Node connector list is null or empty");
938         }
939
940         // Presence check
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);
945             logger.warn(error);
946             return new Status(StatusCode.NOTFOUND, msg);
947         }
948
949         // Validation check
950         Status status = ContainerConfig.validateNodeConnectors(nodeConnectorsString);
951         if (!status.isSuccess()) {
952             String error = String.format("Failed to apply %s: (%s)", action, status.getDescription());
953             logger.warn(error);
954             return status;
955         }
956
957         List<NodeConnector> nodeConnectors = ContainerConfig.nodeConnectorsFromString(nodeConnectorsString);
958
959         // Port sharing check
960         if (!delete) {
961             /*
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
965              */
966             status = validatePortSharing(containerName, nodeConnectors);
967             if (!status.isSuccess()) {
968                 String error = String.format("Failed to apply %s: (%s)", action, status.getDescription());
969                 logger.warn(error);
970                 return status;
971             }
972         }
973
974         // Update Database
975         status = updateContainerEntryDatabase(containerName, nodeConnectors, delete);
976         if (!status.isSuccess()) {
977             String error = String.format("Failed to apply %s: (%s)", action, status.getDescription());
978             logger.warn(error);
979             return status;
980         }
981
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());
987             logger.warn(error);
988             // Revert backend changes
989             Status statusRevert = updateContainerEntryDatabase(containerName, nodeConnectors, !delete);
990             if (!statusRevert.isSuccess()) {
991                 // Unlikely
992                 logger.error("Failed to revert changes in database (CRITICAL)");
993             }
994             return status;
995         }
996
997         // Update cluster Configuration cache
998         containerConfigs.put(containerName, entryConf);
999
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));
1005
1006         return status;
1007     }
1008
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);
1017         // Notify listeners
1018         notifyContainerAwareListeners(container, delete);
1019     }
1020
1021     private void notifyContainerEntryChangeInternal(String containerName, List<NodeConnector> ncList, UpdateType update, boolean notifyLocal) {
1022         logger.trace("Notifying listeners on {} for ports {} in container {}", update, ncList, containerName);
1023         // Back-end World: container name forced to lower case
1024         String container = containerName.toLowerCase(Locale.ENGLISH);
1025         for (NodeConnector nodeConnector : ncList) {
1026             // Now signal that the port has been added/removed
1027             synchronized (this.iContainerListener) {
1028                 for (IContainerListener i : this.iContainerListener) {
1029                     i.nodeConnectorUpdated(container, nodeConnector, update);
1030                 }
1031             }
1032             // Check if the Functional Modules need to be notified as well
1033             if (notifyLocal) {
1034                 synchronized (this.iContainerLocalListener) {
1035                     for (IContainerLocalListener i : this.iContainerLocalListener) {
1036                         i.nodeConnectorUpdated(container, nodeConnector, update);
1037                     }
1038                 }
1039             }
1040         }
1041     }
1042
1043     private void notifyCFlowChangeInternal(String containerName, List<ContainerFlowConfig> confList, UpdateType update,
1044             boolean notifyLocal) {
1045         logger.trace("Notifying listeners on {} for flow specs {} in container {}", update, confList, containerName);
1046         // Back-end World: container name forced to lower case
1047         String container = containerName.toLowerCase(Locale.ENGLISH);
1048
1049         for (ContainerFlowConfig conf : confList) {
1050             for (Match match : conf.getMatches()) {
1051                 ContainerFlow cFlow = new ContainerFlow(match);
1052                 synchronized (this.iContainerListener) {
1053                     for (IContainerListener i : this.iContainerListener) {
1054                         i.containerFlowUpdated(container, cFlow, cFlow, update);
1055                     }
1056                 }
1057                 // Check if the Functional Modules need to be notified as well
1058                 if (notifyLocal) {
1059                     synchronized (this.iContainerLocalListener) {
1060                         for (IContainerLocalListener i : this.iContainerLocalListener) {
1061                             i.containerFlowUpdated(container, cFlow, cFlow, update);
1062                         }
1063                     }
1064                 }
1065             }
1066         }
1067     }
1068
1069     private Status addRemoveContainerFlow(String containerName, List<ContainerFlowConfig> cFlowConfList, boolean delete) {
1070         // Construct action message
1071         String action = String.format("Flow spec(s) %s container %s: %s", delete ? "removal from" : "addition to",
1072                 containerName, cFlowConfList);
1073
1074         // Presence check
1075         ContainerConfig containerConfig = this.containerConfigs.get(containerName);
1076         if (containerConfig == null) {
1077             String msg = String.format("Container not found: %s", containerName);
1078             String error = String.format("Failed to apply %s: (%s)", action, msg);
1079             logger.warn(error);
1080             return new Status(StatusCode.NOTFOUND, "Container not present");
1081         }
1082
1083         // Validity check, check for overlaps on current container configuration
1084         Status status = containerConfig.validateContainerFlowModify(cFlowConfList, delete);
1085         if (!status.isSuccess()) {
1086             String msg = status.getDescription();
1087             String error = String.format("Failed to apply %s: (%s)", action, msg);
1088             logger.warn(error);
1089             return new Status(StatusCode.BADREQUEST, msg);
1090         }
1091
1092         // Validate the operation in terms to the port sharing with other containers
1093         for (ContainerFlowConfig conf : cFlowConfList) {
1094             for (Match match : conf.getMatches()) {
1095                 ContainerFlow cFlow = new ContainerFlow(match);
1096                 status = validateContainerFlowAddRemoval(containerName, cFlow, delete);
1097                 if (!status.isSuccess()) {
1098                     String msg = "Validation failed: " + status.getDescription();
1099                     String error = String.format("Failed to apply %s: (%s)", action, msg);
1100                     logger.warn(error);
1101                     return new Status(StatusCode.BADREQUEST, msg);
1102                 }
1103             }
1104         }
1105
1106         // Update Database
1107         status = updateContainerFlow(containerName, cFlowConfList, delete);
1108         if (!status.isSuccess()) {
1109             String error = String.format("Failed to apply %s: (%s)", action, status.getDescription());
1110             logger.error(error);
1111             return status;
1112         }
1113
1114         // Update Configuration
1115         status = (delete) ? containerConfig.removeContainerFlows(cFlowConfList) : containerConfig
1116                 .addContainerFlows(cFlowConfList);
1117         if (!status.isSuccess()) {
1118             String error = String.format("Failed to modify config for %s: (%s)", action, status.getDescription());
1119             logger.error(error);
1120             // Revert backend changes
1121             Status statusRevert = updateContainerFlow(containerName, cFlowConfList, !delete);
1122             if (!statusRevert.isSuccess()) {
1123                 // Unlikely
1124                 logger.error("Failed to revert changes in database (CRITICAL)");
1125             }
1126             return status;
1127         }
1128         // Update cluster cache
1129         this.containerConfigs.put(containerName, containerConfig);
1130
1131         // Notify global and local listeners
1132         UpdateType update = (delete) ? UpdateType.REMOVED : UpdateType.ADDED;
1133         notifyCFlowChangeInternal(containerName, cFlowConfList, update, true);
1134         // Trigger cluster notification
1135         containerChangeEvents.put(containerName, new ContainerFlowChangeEvent(cFlowConfList, update));
1136
1137         return status;
1138     }
1139
1140     private Status addRemoveContainer(ContainerConfig containerConf, boolean delete) {
1141         // Construct action message
1142         String action = String.format("Container %s", delete ? "removal" : "creation");
1143
1144         // Valid configuration check
1145         Status status = null;
1146         String error = (containerConfigs == null) ? String.format("Invalid %s configuration: (null config object)", action)
1147                 : (!(status = containerConf.validate()).isSuccess()) ? String.format("Invalid %s configuration: (%s)",
1148                         action, status.getDescription()) : null;
1149         if (error != null) {
1150             logger.warn(error);
1151             return new Status(StatusCode.BADREQUEST, error);
1152         }
1153
1154         // Configuration presence check
1155         String containerName = containerConf.getContainerName();
1156         if (delete) {
1157             if (!containerConfigs.containsKey(containerName)) {
1158                 String msg = String.format("%s Failed: (Container does not exist: %s)", action, containerName);
1159                 logger.warn(msg);
1160                 return new Status(StatusCode.NOTFOUND, msg);
1161             }
1162         } else {
1163             if (containerConfigs.containsKey(containerName)) {
1164                 String msg = String.format("%s Failed: (Container already exist: %s)", action, containerName);
1165                 logger.warn(msg);
1166                 return new Status(StatusCode.CONFLICT, msg);
1167             }
1168         }
1169
1170         /*
1171          * The proposed container configuration could be a complex one containing
1172          * both ports and flow spec. If so, check if it has shared ports with
1173          * other existing containers. If that is the case verify flow spec isolation
1174          * is in place. No need to check on flow spec validation first. This
1175          * would take care of both
1176          */
1177         if (!delete) {
1178             status = validatePortSharing(containerConf);
1179             if (!status.isSuccess()) {
1180                 error = String.format("%s Failed: (%s)", action, status.getDescription());
1181                 logger.error(error);
1182                 return status;
1183             }
1184         }
1185
1186         // Update Database
1187         status = updateContainerDatabase(containerConf, delete);
1188
1189         // Abort and exit here if back-end database update failed
1190         if (!status.isSuccess()) {
1191             return status;
1192         }
1193
1194         /*
1195          * This is a quick fix until configuration service becomes the
1196          * centralized configuration management place. Here container manager will
1197          * remove the startup files for all the bundles that are present in the
1198          * container being deleted. Do the cleanup here in Container manger as do not
1199          * want to put this temporary code in Configuration manager yet which is
1200          * ODL.
1201          */
1202         if (delete) {
1203             // TODO: remove when Config Mgr takes over
1204             removeComponentsStartUpfiles(containerName);
1205         }
1206
1207         /*
1208          * Update Configuration: This will trigger the notifications on cache
1209          * update callback locally and on the other cluster nodes
1210          */
1211         if (delete) {
1212             this.containerConfigs.remove(containerName);
1213         } else {
1214             this.containerConfigs.put(containerName, containerConf);
1215         }
1216
1217         // Automatically create and populate user and resource groups
1218         updateResourceGroups(containerConf, delete);
1219
1220         // Notify global and local listeners
1221         UpdateType update = (delete) ? UpdateType.REMOVED : UpdateType.ADDED;
1222         notifyContainerChangeInternal(containerConf, update, true);
1223
1224         // Trigger cluster notification
1225         containerChangeEvents.put(containerName, new ContainerChangeEvent(containerConf, update));
1226
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);
1232
1233                 // Trigger cluster notification
1234                 containerChangeEvents.put(containerName, new ContainerFlowChangeEvent(specList, update));
1235             }
1236
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));
1243             }
1244         }
1245
1246         if (delete) {
1247             clusterServices.removeContainerCaches(containerName);
1248         }
1249         return status;
1250     }
1251
1252     @Override
1253     public Status addContainer(ContainerConfig containerConf) {
1254         return addRemoveContainer(containerConf, false);
1255     }
1256
1257     @Override
1258     public Status removeContainer(ContainerConfig containerConf) {
1259         return addRemoveContainer(containerConf, true);
1260     }
1261
1262     @Override
1263     public Status removeContainer(String containerName) {
1264         // Construct action message
1265         String action = String.format("Container removal: %s", containerName);
1266
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);
1271             logger.warn(error);
1272             return new Status(StatusCode.NOTFOUND, msg);
1273         }
1274         return addRemoveContainer(containerConf, true);
1275     }
1276
1277     @Override
1278     public Status addContainerEntry(String containerName, List<String> nodeConnectors) {
1279         return addRemoveContainerEntries(containerName, nodeConnectors, false);
1280     }
1281
1282     @Override
1283     public Status removeContainerEntry(String containerName, List<String> nodeConnectors) {
1284         return addRemoveContainerEntries(containerName, nodeConnectors, true);
1285     }
1286
1287     @Override
1288     public Status addContainerFlows(String containerName, List<ContainerFlowConfig> fSpecConf) {
1289         return addRemoveContainerFlow(containerName, fSpecConf, false);
1290     }
1291
1292     @Override
1293     public Status removeContainerFlows(String containerName, List<ContainerFlowConfig> fSpecConf) {
1294         return addRemoveContainerFlow(containerName, fSpecConf, true);
1295     }
1296
1297     @Override
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);
1301
1302         // Presence check
1303         ContainerConfig sc = containerConfigs.get(containerName);
1304         if (sc == null) {
1305             String msg = String.format("Container not found: %s", containerName);
1306             String error = String.format("Failed to apply %s: (%s)", action, msg);
1307             logger.warn(error);
1308             return new Status(StatusCode.NOTFOUND, msg);
1309         }
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);
1314             logger.warn(error);
1315             return new Status(StatusCode.BADREQUEST, msg);
1316         }
1317         return addRemoveContainerFlow(containerName, list, true);
1318     }
1319
1320     @Override
1321     public List<ContainerFlowConfig> getContainerFlows(String containerName) {
1322         ContainerConfig sc = containerConfigs.get(containerName);
1323         return (sc == null) ? new ArrayList<ContainerFlowConfig>(0) : sc.getContainerFlowConfigs();
1324     }
1325
1326     @Override
1327     public List<String> getContainerFlowNameList(String containerName) {
1328         ContainerConfig sc = containerConfigs.get(containerName);
1329         return (sc == null) ? new ArrayList<String>(0) : sc.getContainerFlowConfigsNames();
1330     }
1331
1332     @Override
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();
1337     }
1338
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);
1344
1345         if (configMap == null) {
1346             return;
1347         }
1348
1349         for (Map.Entry<String, ContainerConfig> configEntry : configMap.entrySet()) {
1350             addContainer(configEntry.getValue());
1351         }
1352     }
1353
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()));
1358         }
1359         ci.println("Total number of containers: " + containerConfigs.entrySet().size());
1360     }
1361
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()));
1366         }
1367     }
1368
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);
1375             }
1376
1377             for (ContainerFlow s : sd.getContainerFlowSpecs()) {
1378                 ci.println("\t" + s.toString());
1379             }
1380         }
1381     }
1382
1383     public void _psp(CommandInterpreter ci) {
1384         for (NodeConnector sp : nodeConnectorToContainers.keySet()) {
1385             ci.println(nodeConnectorToContainers.get(sp));
1386         }
1387     }
1388
1389     public void _psm(CommandInterpreter ci) {
1390         for (Node sp : nodeToContainers.keySet()) {
1391             ci.println(nodeToContainers.get(sp));
1392         }
1393     }
1394
1395     public void _addContainer(CommandInterpreter ci) {
1396         String containerName = ci.nextArgument();
1397         if (containerName == null) {
1398             ci.print("Container Name not specified");
1399             return;
1400         }
1401         String staticVlan = ci.nextArgument();
1402         ContainerConfig containerConfig = new ContainerConfig(containerName, staticVlan, null, null);
1403         ci.println(this.addRemoveContainer(containerConfig, false));
1404     }
1405
1406     public void _createContainer(CommandInterpreter ci) {
1407         String containerName = ci.nextArgument();
1408         if (containerName == null) {
1409             ci.print("Container Name not specified");
1410             return;
1411         }
1412         String staticVlan = ci.nextArgument();
1413         if (staticVlan == null) {
1414             ci.print("Static Vlan not specified");
1415             return;
1416         }
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());
1420         }
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));
1425     }
1426
1427     public void _removeContainer(CommandInterpreter ci) {
1428         String containerName = ci.nextArgument();
1429         if (containerName == null) {
1430             ci.print("Container Name not specified");
1431             return;
1432         }
1433         ContainerConfig containerConfig = new ContainerConfig(containerName, "", null, null);
1434         ci.println(this.addRemoveContainer(containerConfig, true));
1435     }
1436
1437     public void _addContainerEntry(CommandInterpreter ci) {
1438         String containerName = ci.nextArgument();
1439         if (containerName == null) {
1440             ci.print("Container Name not specified");
1441             return;
1442         }
1443         String nodeId = ci.nextArgument();
1444         if (nodeId == null) {
1445             ci.print("Node Id not specified");
1446             return;
1447         }
1448         String portId = ci.nextArgument();
1449         if (portId == null) {
1450             ci.print("Port not specified");
1451             return;
1452         }
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));
1459     }
1460
1461     public void _removeContainerEntry(CommandInterpreter ci) {
1462         String containerName = ci.nextArgument();
1463         if (containerName == null) {
1464             ci.print("Container Name not specified");
1465             return;
1466         }
1467         String nodeId = ci.nextArgument();
1468         if (nodeId == null) {
1469             ci.print("Node Id not specified");
1470             return;
1471         }
1472         String portId = ci.nextArgument();
1473         if (portId == null) {
1474             ci.print("Port not specified");
1475             return;
1476         }
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));
1483     }
1484
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");
1487         return cfg;
1488     }
1489
1490     public void _addContainerFlow(CommandInterpreter ci) {
1491         String containerName = ci.nextArgument();
1492         if (containerName == null) {
1493             ci.print("Container Name not specified");
1494             return;
1495         }
1496         String cflowName = ci.nextArgument();
1497         if (cflowName == null) {
1498             ci.print("cflowName not specified");
1499             return;
1500         }
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));
1506     }
1507
1508     public void _removeContainerFlow(CommandInterpreter ci) {
1509         String containerName = ci.nextArgument();
1510         if (containerName == null) {
1511             ci.print("Container Name not specified");
1512             return;
1513         }
1514         String cflowName = ci.nextArgument();
1515         if (cflowName == null) {
1516             ci.print("cflowName not specified");
1517             return;
1518         }
1519         Set<String> set = new HashSet<String>(1);
1520         set.add(cflowName);
1521         ci.println(this.removeContainerFlows(containerName, set));
1522     }
1523
1524     @Override
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();
1540     }
1541
1542     @Override
1543     public boolean doesContainerExist(String containerName) {
1544         // Test for default container
1545         if (GlobalConstants.DEFAULT.toString().equalsIgnoreCase(containerName)) {
1546             return true;
1547         }
1548         // Test for non-default one
1549         return (getContainerByName(containerName) != null);
1550     }
1551
1552     @Override
1553     public ContainerData getContainerData(String containerName) {
1554         return (getContainerByName(containerName));
1555     }
1556
1557     @Override
1558     public Status saveConfiguration() {
1559         return saveContainerConfig();
1560     }
1561
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));
1567         }
1568     }
1569
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>");
1575             return;
1576         }
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());
1581         }
1582     }
1583
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>");
1589             return;
1590         }
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());
1595         }
1596     }
1597
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>");
1603             return;
1604         }
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());
1609         }
1610     }
1611
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>");
1617             return;
1618         }
1619         ci.println("User " + userName + " has level: " + this.getUserLevel(userName));
1620     }
1621
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>");
1627             return;
1628         }
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());
1633         }
1634     }
1635
1636     /*
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
1640      * controller
1641      */
1642     // TODO: remove when no longer needed
1643     public void _saveConfig(CommandInterpreter ci) {
1644         Status status = new Status(StatusCode.NOSERVICE, "Configuration service not reachable");
1645
1646         IConfigurationService configService = (IConfigurationService) ServiceHelper.getGlobalInstance(
1647                 IConfigurationService.class, this);
1648         if (configService != null) {
1649             status = configService.saveConfigurations();
1650         }
1651         ci.println(status.toString());
1652     }
1653
1654     @Override
1655     public List<String> getContainerNames() {
1656         return getContainerNameList();
1657     }
1658
1659     @Override
1660     public boolean hasNonDefaultContainer() {
1661         return !containerConfigs.keySet().isEmpty();
1662     }
1663
1664     @Override
1665     public boolean inContainerMode() {
1666         return this.containerConfigs.size() > 0;
1667     }
1668 }