Neutron API v2.0 bindings and APIs for security groups/rules.
[controller.git] / opendaylight / networkconfiguration / neutron / implementation / src / main / java / org / opendaylight / controller / networkconfig / neutron / implementation / NeutronSecurityGroupInterface.java
1 /*
2  * Copyright (C) 2014 Red Hat, Inc.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  *
8  */
9
10 package org.opendaylight.controller.networkconfig.neutron.implementation;
11
12 import java.io.FileNotFoundException;
13 import java.io.IOException;
14 import java.io.ObjectInputStream;
15 import java.lang.reflect.Method;
16 import java.util.ArrayList;
17 import java.util.Dictionary;
18 import java.util.EnumSet;
19 import java.util.HashSet;
20 import java.util.Map.Entry;
21 import java.util.List;
22 import java.util.Set;
23 import java.util.concurrent.ConcurrentMap;
24 import org.apache.felix.dm.Component;
25 import org.opendaylight.controller.clustering.services.CacheConfigException;
26 import org.opendaylight.controller.clustering.services.CacheExistException;
27 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
28 import org.opendaylight.controller.clustering.services.IClusterServices;
29 import org.opendaylight.controller.configuration.ConfigurationObject;
30 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
31 import org.opendaylight.controller.configuration.IConfigurationContainerService;
32 import org.opendaylight.controller.networkconfig.neutron.INeutronSecurityGroupCRUD;
33 import org.opendaylight.controller.networkconfig.neutron.NeutronSecurityGroup;
34 import org.opendaylight.controller.sal.utils.IObjectReader;
35 import org.opendaylight.controller.sal.utils.Status;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39
40 public class NeutronSecurityGroupInterface implements INeutronSecurityGroupCRUD, IConfigurationContainerAware, IObjectReader {
41     private static final Logger logger = LoggerFactory.getLogger(NeutronSecurityGroupInterface.class);
42     private static final String FILE_NAME ="neutron.securitygroup.conf";
43     private String containerName = null;
44
45     private IClusterContainerServices clusterContainerService = null;
46     private IConfigurationContainerService configurationService;
47     private ConcurrentMap<String, NeutronSecurityGroup> securityGroupDB;
48
49     // methods needed for creating caches
50     void setClusterContainerService(IClusterContainerServices s) {
51         logger.debug("Cluster Service set");
52         clusterContainerService = s;
53     }
54
55     void unsetClusterContainerService(IClusterContainerServices s) {
56         if (clusterContainerService == s) {
57             logger.debug("Cluster Service removed!");
58             clusterContainerService = null;
59         }
60     }
61
62     public void setConfigurationContainerService(IConfigurationContainerService service) {
63         logger.trace("Configuration service set: {}", service);
64         configurationService = service;
65     }
66
67     public void unsetConfigurationContainerService(IConfigurationContainerService service) {
68         logger.trace("Configuration service removed: {}", service);
69         configurationService = null;
70     }
71
72     private void allocateCache() {
73         if (this.clusterContainerService == null) {
74             logger.error("un-initialized clusterContainerService, can't create cache");
75             return;
76         }
77         logger.debug("Creating Cache for Neutron Security Groups");
78         try {
79             // neutron caches
80             this.clusterContainerService.createCache("neutronSecurityGroups",
81                 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
82         } catch (CacheConfigException cce) {
83             logger.error("Cache couldn't be created for Neutron Security Groups -  check cache mode");
84         } catch (CacheExistException cce) {
85             logger.error("Cache for Neutron Security Groups already exists, destroy and recreate");
86         }
87         logger.debug("Cache successfully created for Neutron Security Groups");
88     }
89
90     @SuppressWarnings({ "unchecked" })
91     private void retrieveCache() {
92         if (clusterContainerService == null) {
93             logger.error("un-initialized clusterContainerService, can't retrieve cache");
94             return;
95         }
96
97         logger.debug("Retrieving cache for Neutron Security Groups");
98         securityGroupDB = (ConcurrentMap<String, NeutronSecurityGroup>) clusterContainerService
99             .getCache("neutronSecurityGroups");
100         if (securityGroupDB == null) {
101             logger.error("Cache couldn't be retrieved for Neutron Security Groups");
102         }
103         logger.debug("Cache was successfully retrieved for Neutron Security Groups");
104     }
105
106     private void destroyCache() {
107         if (clusterContainerService == null) {
108             logger.error("un-initialized clusterMger, can't destroy cache");
109             return;
110         }
111         logger.debug("Destroying Cache for Neutron Security Groups");
112         clusterContainerService.destroyCache("neutronSecurityGroups");
113     }
114
115     private void startUp() {
116         allocateCache();
117         retrieveCache();
118         loadConfiguration();
119     }
120
121     /**
122      * Function called by the dependency manager when all the required
123      * dependencies are satisfied
124      *
125      */
126     void init(Component c) {
127         Dictionary<?, ?> props = c.getServiceProperties();
128         if (props != null) {
129             this.containerName = (String) props.get("containerName");
130             logger.debug("Running containerName: {}", this.containerName);
131         } else {
132             // In the Global instance case the containerName is empty
133             this.containerName = "";
134         }
135         startUp();
136     }
137
138     /**
139      * Function called by the dependency manager when at least one dependency
140      * become unsatisfied or when the component is shutting down because for
141      * example bundle is being stopped.
142      *
143      */
144     void destroy() {
145         destroyCache();
146     }
147
148     /**
149      * Function called by dependency manager after "init ()" is called and after
150      * the services provided by the class are registered in the service registry
151      *
152      */
153     void start() {
154     }
155
156     /**
157      * Function called by the dependency manager before the services exported by
158      * the component are unregistered, this will be followed by a "destroy ()"
159      * calls
160      *
161      */
162     void stop() {
163     }
164
165     // this method uses reflection to update an object from it's delta.
166
167     private boolean overwrite(Object target, Object delta) {
168         Method[] methods = target.getClass().getMethods();
169
170         for(Method toMethod: methods){
171             if(toMethod.getDeclaringClass().equals(target.getClass())
172                 && toMethod.getName().startsWith("set")){
173
174                 String toName = toMethod.getName();
175                 String fromName = toName.replace("set", "get");
176
177                 try {
178                     Method fromMethod = delta.getClass().getMethod(fromName);
179                     Object value = fromMethod.invoke(delta, (Object[])null);
180                     if(value != null){
181                         toMethod.invoke(target, value);
182                     }
183                 } catch (Exception e) {
184                     e.printStackTrace();
185                     return false;
186                 }
187             }
188         }
189         return true;
190     }
191
192     @Override
193     public boolean neutronSecurityGroupExists(String uuid) {
194         return securityGroupDB.containsKey(uuid);
195     }
196
197     @Override
198     public NeutronSecurityGroup getNeutronSecurityGroup(String uuid) {
199         if (!neutronSecurityGroupExists(uuid)) {
200             logger.debug("No Security Groups Have Been Defined");
201             return null;
202         }
203         return securityGroupDB.get(uuid);
204     }
205
206     @Override
207     public List<NeutronSecurityGroup> getAllNeutronSecurityGroups() {
208         Set<NeutronSecurityGroup> allSecurityGroups = new HashSet<NeutronSecurityGroup>();
209         for (Entry<String, NeutronSecurityGroup> entry : securityGroupDB.entrySet()) {
210             NeutronSecurityGroup securityGroup = entry.getValue();
211             allSecurityGroups.add(securityGroup);
212         }
213         logger.debug("Exiting getSecurityGroups, Found {} OpenStackSecurityGroup", allSecurityGroups.size());
214         List<NeutronSecurityGroup> ans = new ArrayList<NeutronSecurityGroup>();
215         ans.addAll(allSecurityGroups);
216         return ans;
217     }
218
219     @Override
220     public boolean addNeutronSecurityGroup(NeutronSecurityGroup input) {
221         if (neutronSecurityGroupExists(input.getSecurityGroupUUID())) {
222             return false;
223         }
224         securityGroupDB.putIfAbsent(input.getSecurityGroupUUID(), input);
225         return true;
226     }
227
228     @Override
229     public boolean removeNeutronSecurityGroup(String uuid) {
230         if (!neutronSecurityGroupExists(uuid)) {
231             return false;
232         }
233         securityGroupDB.remove(uuid);
234         return true;
235     }
236
237     @Override
238     public boolean updateNeutronSecurityGroup(String uuid, NeutronSecurityGroup delta) {
239         if (!neutronSecurityGroupExists(uuid)) {
240             return false;
241         }
242         NeutronSecurityGroup target = securityGroupDB.get(uuid);
243         return overwrite(target, delta);
244     }
245
246     @Override
247     public boolean neutronSecurityGroupInUse(String securityGroupUUID) {
248         return !neutronSecurityGroupExists(securityGroupUUID);
249     }
250
251     private void loadConfiguration() {
252         for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, FILE_NAME)) {
253             NeutronSecurityGroup nn = (NeutronSecurityGroup) conf;
254             securityGroupDB.put(nn.getSecurityGroupUUID(), nn);
255         }
256     }
257
258     @Override
259     public Status saveConfiguration() {
260         return configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(securityGroupDB.values()),
261             FILE_NAME);
262     }
263
264     @Override
265     public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
266         return ois.readObject();
267     }
268
269 }