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 / NeutronFirewallInterface.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.INeutronFirewallCRUD;
20 import org.opendaylight.controller.networkconfig.neutron.NeutronFirewall;
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 NeutronFirewallInterface implements INeutronFirewallCRUD, IConfigurationContainerAware, IObjectReader {
40     private static final Logger logger = LoggerFactory.getLogger(NeutronFirewallInterface.class);
41     private static final String FILE_NAME = "neutron.firewall.conf";
42     private String containerName = null;
43
44     private IClusterContainerServices clusterContainerService = null;
45     private IConfigurationContainerService configurationService;
46     private ConcurrentMap<String, NeutronFirewall> firewallDB;
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");
77         try {
78             // neutron caches
79             this.clusterContainerService.createCache("neutronFirewalls",
80                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
81         } catch (CacheConfigException cce) {
82             logger.error("Cache couldn't be created for Neutron Firewall -  check cache mode");
83         } catch (CacheExistException cce) {
84             logger.error("Cache for Neutron Firewall already exists, destroy and recreate");
85         }
86         logger.debug("Cache successfully created for Neutron Firewall");
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");
97         firewallDB = (ConcurrentMap<String, NeutronFirewall>) clusterContainerService
98                 .getCache("neutronFirewalls");
99         if (firewallDB == null) {
100             logger.error("Cache couldn't be retrieved for Neutron Firewall");
101         }
102         logger.debug("Cache was successfully retrieved for Neutron Firewall");
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("neutronFirewalls");
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     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     void destroy() {
142         destroyCache();
143     }
144
145     /**
146      * Function called by dependency manager after "init ()" is called and after
147      * the services provided by the class are registered in the service registry
148      */
149     void start() {
150     }
151
152     /**
153      * Function called by the dependency manager before the services exported by
154      * the component are unregistered, this will be followed by a "destroy ()"
155      * calls
156      */
157     void stop() {
158     }
159
160     // this method uses reflection to update an object from it's delta.
161
162     private boolean overwrite(Object target, Object delta) {
163         Method[] methods = target.getClass().getMethods();
164
165         for (Method toMethod : methods) {
166             if (toMethod.getDeclaringClass().equals(target.getClass())
167                     && toMethod.getName().startsWith("set")) {
168
169                 String toName = toMethod.getName();
170                 String fromName = toName.replace("set", "get");
171
172                 try {
173                     Method fromMethod = delta.getClass().getMethod(fromName);
174                     Object value = fromMethod.invoke(delta, (Object[]) null);
175                     if (value != null) {
176                         toMethod.invoke(target, value);
177                     }
178                 } catch (Exception e) {
179                     e.printStackTrace();
180                     return false;
181                 }
182             }
183         }
184         return true;
185     }
186
187     @Override
188     public boolean neutronFirewallExists(String uuid) {
189         return firewallDB.containsKey(uuid);
190     }
191
192     @Override
193     public NeutronFirewall getNeutronFirewall(String uuid) {
194         if (!neutronFirewallExists(uuid)) {
195             logger.debug("No Firewall Have Been Defined");
196             return null;
197         }
198         return firewallDB.get(uuid);
199     }
200
201     @Override
202     public List<NeutronFirewall> getAllNeutronFirewalls() {
203         Set<NeutronFirewall> allFirewalls = new HashSet<NeutronFirewall>();
204         for (Entry<String, NeutronFirewall> entry : firewallDB.entrySet()) {
205             NeutronFirewall firewall = entry.getValue();
206             allFirewalls.add(firewall);
207         }
208         logger.debug("Exiting getFirewalls, Found {} OpenStackFirewall", allFirewalls.size());
209         List<NeutronFirewall> ans = new ArrayList<NeutronFirewall>();
210         ans.addAll(allFirewalls);
211         return ans;
212     }
213
214     @Override
215     public boolean addNeutronFirewall(NeutronFirewall input) {
216         if (neutronFirewallExists(input.getFirewallUUID())) {
217             return false;
218         }
219         firewallDB.putIfAbsent(input.getFirewallUUID(), input);
220         return true;
221     }
222
223     @Override
224     public boolean removeNeutronFirewall(String uuid) {
225         if (!neutronFirewallExists(uuid)) {
226             return false;
227         }
228         firewallDB.remove(uuid);
229         return true;
230     }
231
232     @Override
233     public boolean updateNeutronFirewall(String uuid, NeutronFirewall delta) {
234         if (!neutronFirewallExists(uuid)) {
235             return false;
236         }
237         NeutronFirewall target = firewallDB.get(uuid);
238         return overwrite(target, delta);
239     }
240
241     @Override
242     public boolean neutronFirewallInUse(String firewallUUID) {
243         return !neutronFirewallExists(firewallUUID);
244     }
245
246     private void loadConfiguration() {
247         for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, FILE_NAME)) {
248             NeutronFirewall nn = (NeutronFirewall) conf;
249             firewallDB.put(nn.getFirewallUUID(), nn);
250         }
251     }
252
253     @Override
254     public Status saveConfiguration() {
255         return configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(firewallDB.values()),
256                 FILE_NAME);
257     }
258
259     @Override
260     public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
261         return ois.readObject();
262     }
263
264 }