Merge "Bug 1029: Remove dead code: sal-schema-repository-api"
[controller.git] / opendaylight / networkconfiguration / neutron / implementation / src / main / java / org / opendaylight / controller / networkconfig / neutron / implementation / NeutronSecurityRuleInterface.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
25 import org.apache.felix.dm.Component;
26 import org.opendaylight.controller.clustering.services.CacheConfigException;
27 import org.opendaylight.controller.clustering.services.CacheExistException;
28 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
29 import org.opendaylight.controller.clustering.services.IClusterServices;
30 import org.opendaylight.controller.configuration.ConfigurationObject;
31 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
32 import org.opendaylight.controller.configuration.IConfigurationContainerService;
33 import org.opendaylight.controller.networkconfig.neutron.INeutronSecurityRuleCRUD;
34 import org.opendaylight.controller.networkconfig.neutron.NeutronSecurityRule;
35 import org.opendaylight.controller.sal.utils.IObjectReader;
36 import org.opendaylight.controller.sal.utils.Status;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40
41 public class NeutronSecurityRuleInterface implements INeutronSecurityRuleCRUD, IConfigurationContainerAware, IObjectReader {
42     private static final Logger logger = LoggerFactory.getLogger(NeutronSecurityRuleInterface.class);
43     private static final String FILE_NAME = "neutron.securityrule.conf";
44     private String containerName = null;
45
46     private IClusterContainerServices clusterContainerService = null;
47     private IConfigurationContainerService configurationService;
48     private ConcurrentMap<String, NeutronSecurityRule> securityRuleDB;
49
50     // methods needed for creating caches
51     void setClusterContainerService(IClusterContainerServices s) {
52         logger.debug("Cluster Service set");
53         clusterContainerService = s;
54     }
55
56     void unsetClusterContainerService(IClusterContainerServices s) {
57         if (clusterContainerService == s) {
58             logger.debug("Cluster Service removed!");
59             clusterContainerService = null;
60         }
61     }
62
63     public void setConfigurationContainerService(IConfigurationContainerService service) {
64         logger.trace("Configuration service set: {}", service);
65         configurationService = service;
66     }
67
68     public void unsetConfigurationContainerService(IConfigurationContainerService service) {
69         logger.trace("Configuration service removed: {}", service);
70         configurationService = null;
71     }
72
73     private void allocateCache() {
74         if (this.clusterContainerService == null) {
75             logger.error("un-initialized clusterContainerService, can't create cache");
76             return;
77         }
78         logger.debug("Creating Cache for Neutron Security Rules");
79         try {
80             // neutron caches
81             this.clusterContainerService.createCache("neutronSecurityRules",
82                 EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
83         } catch (CacheConfigException cce) {
84             logger.error("Cache couldn't be created for Neutron Security Rules -  check cache mode");
85         } catch (CacheExistException cce) {
86             logger.error("Cache for Neutron Security Rules already exists, destroy and recreate");
87         }
88         logger.debug("Cache successfully created for Neutron Security Rules");
89     }
90
91     @SuppressWarnings({"unchecked"})
92     private void retrieveCache() {
93         if (clusterContainerService == null) {
94             logger.error("un-initialized clusterContainerService, can't retrieve cache");
95             return;
96         }
97
98         logger.debug("Retrieving cache for Neutron Security Rules");
99         securityRuleDB = (ConcurrentMap<String, NeutronSecurityRule>) clusterContainerService
100             .getCache("neutronSecurityRules");
101         if (securityRuleDB == null) {
102             logger.error("Cache couldn't be retrieved for Neutron Security Rules");
103         }
104         logger.debug("Cache was successfully retrieved for Neutron Security Rules");
105     }
106
107     private void destroyCache() {
108         if (clusterContainerService == null) {
109             logger.error("un-initialized clusterMger, can't destroy cache");
110             return;
111         }
112         logger.debug("Destroying Cache for Neutron Security Rules");
113         clusterContainerService.destroyCache("neutronSecurityRules");
114     }
115
116     private void startUp() {
117         allocateCache();
118         retrieveCache();
119         loadConfiguration();
120     }
121
122     /**
123      * Function called by the dependency manager when all the required
124      * dependencies are satisfied
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     void destroy() {
144         destroyCache();
145     }
146
147     /**
148      * Function called by dependency manager after "init ()" is called and after
149      * the services provided by the class are registered in the service registry
150      */
151     void start() {
152     }
153
154     /**
155      * Function called by the dependency manager before the services exported by
156      * the component are unregistered, this will be followed by a "destroy ()"
157      * calls
158      */
159     void stop() {
160     }
161
162     // this method uses reflection to update an object from it's delta.
163     private boolean overwrite(Object target, Object delta) {
164         Method[] methods = target.getClass().getMethods();
165
166         for (Method toMethod : methods) {
167             if (toMethod.getDeclaringClass().equals(target.getClass())
168                 && toMethod.getName().startsWith("set")) {
169
170                 String toName = toMethod.getName();
171                 String fromName = toName.replace("set", "get");
172
173                 try {
174                     Method fromMethod = delta.getClass().getMethod(fromName);
175                     Object value = fromMethod.invoke(delta, (Object[]) null);
176                     if (value != null) {
177                         toMethod.invoke(target, value);
178                     }
179                 } catch (Exception e) {
180                     e.printStackTrace();
181                     return false;
182                 }
183             }
184         }
185         return true;
186     }
187
188     @Override
189     public boolean neutronSecurityRuleExists(String uuid) {
190         return securityRuleDB.containsKey(uuid);
191     }
192
193     @Override
194     public NeutronSecurityRule getNeutronSecurityRule(String uuid) {
195         if (!neutronSecurityRuleExists(uuid)) {
196             logger.debug("No Security Rules Have Been Defined");
197             return null;
198         }
199         return securityRuleDB.get(uuid);
200     }
201
202     @Override
203     public List<NeutronSecurityRule> getAllNeutronSecurityRules() {
204         Set<NeutronSecurityRule> allSecurityRules = new HashSet<NeutronSecurityRule>();
205         for (Entry<String, NeutronSecurityRule> entry : securityRuleDB.entrySet()) {
206             NeutronSecurityRule securityRule = entry.getValue();
207             allSecurityRules.add(securityRule);
208         }
209         logger.debug("Exiting getSecurityRule, Found {} OpenStackSecurityRule", allSecurityRules.size());
210         List<NeutronSecurityRule> ans = new ArrayList<NeutronSecurityRule>();
211         ans.addAll(allSecurityRules);
212         return ans;
213     }
214
215     @Override
216     public boolean addNeutronSecurityRule(NeutronSecurityRule input) {
217         if (neutronSecurityRuleExists(input.getSecurityRuleUUID())) {
218             return false;
219         }
220         securityRuleDB.putIfAbsent(input.getSecurityRuleUUID(), input);
221         return true;
222     }
223
224     @Override
225     public boolean removeNeutronSecurityRule(String uuid) {
226         if (!neutronSecurityRuleExists(uuid)) {
227             return false;
228         }
229         securityRuleDB.remove(uuid);
230         return true;
231     }
232
233     @Override
234     public boolean updateNeutronSecurityRule(String uuid, NeutronSecurityRule delta) {
235         if (!neutronSecurityRuleExists(uuid)) {
236             return false;
237         }
238         NeutronSecurityRule target = securityRuleDB.get(uuid);
239         return overwrite(target, delta);
240     }
241
242     @Override
243     public boolean neutronSecurityRuleInUse(String securityRuleUUID) {
244         return !neutronSecurityRuleExists(securityRuleUUID);
245     }
246
247     private void loadConfiguration() {
248         for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, FILE_NAME)) {
249             NeutronSecurityRule nn = (NeutronSecurityRule) conf;
250             securityRuleDB.put(nn.getSecurityRuleUUID(), nn);
251         }
252     }
253
254     @Override
255     public Status saveConfiguration() {
256         return configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(securityRuleDB.values()),
257             FILE_NAME);
258     }
259
260     @Override
261     public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
262         return ois.readObject();
263     }
264
265 }