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