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