sal-remoterpc-connector: sync ch.qos.logback:logback-classic version
[controller.git] / opendaylight / networkconfiguration / neutron / implementation / src / main / java / org / opendaylight / controller / networkconfig / neutron / implementation / NeutronSubnetInterface.java
1 /*
2  * Copyright IBM Corporation, 2013.  All rights reserved.
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 java.io.FileNotFoundException;
12 import java.io.IOException;
13 import java.io.ObjectInputStream;
14 import java.lang.reflect.Method;
15 import java.util.ArrayList;
16 import java.util.Dictionary;
17 import java.util.EnumSet;
18 import java.util.HashSet;
19 import java.util.List;
20 import java.util.Set;
21 import java.util.Map.Entry;
22 import java.util.concurrent.ConcurrentHashMap;
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.IConfigurationContainerAware;
31 import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkCRUD;
32 import org.opendaylight.controller.networkconfig.neutron.INeutronSubnetCRUD;
33 import org.opendaylight.controller.networkconfig.neutron.NeutronCRUDInterfaces;
34 import org.opendaylight.controller.networkconfig.neutron.NeutronNetwork;
35 import org.opendaylight.controller.networkconfig.neutron.NeutronSubnet;
36 import org.opendaylight.controller.sal.utils.GlobalConstants;
37 import org.opendaylight.controller.sal.utils.IObjectReader;
38 import org.opendaylight.controller.sal.utils.ObjectReader;
39 import org.opendaylight.controller.sal.utils.ObjectWriter;
40 import org.opendaylight.controller.sal.utils.Status;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 public class NeutronSubnetInterface implements INeutronSubnetCRUD, IConfigurationContainerAware,
45                                                IObjectReader {
46     private static final Logger logger = LoggerFactory.getLogger(NeutronSubnetInterface.class);
47     private static String ROOT = GlobalConstants.STARTUPHOME.toString();
48     private static final String FILENAME ="neutron.subnet";
49     private static String fileName;
50
51     private String containerName = null;
52
53     private IClusterContainerServices clusterContainerService = null;
54     private ConcurrentMap<String, NeutronSubnet> subnetDB;
55
56     // methods needed for creating caches
57
58     void setClusterContainerService(IClusterContainerServices s) {
59         logger.debug("Cluster Service set");
60         this.clusterContainerService = s;
61     }
62
63     void unsetClusterContainerService(IClusterContainerServices s) {
64         if (this.clusterContainerService == s) {
65             logger.debug("Cluster Service removed!");
66             this.clusterContainerService = null;
67         }
68     }
69
70     @SuppressWarnings("deprecation")
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 Subnets");
77         try {
78             // neutron caches
79             this.clusterContainerService.createCache("neutronSubnets",
80                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
81         } catch (CacheConfigException cce) {
82             logger.error("Cache couldn't be created for Neutron Subnets -  check cache mode");
83         } catch (CacheExistException cce) {
84             logger.error("Cache for Neutron Subnets already exists, destroy and recreate");
85         }
86         logger.debug("Cache successfully created for Neutron Subnets");
87     }
88
89     @SuppressWarnings({ "unchecked", "deprecation" })
90     private void retrieveCache() {
91         if (this.clusterContainerService == null) {
92             logger.error("un-initialized clusterContainerService, can't retrieve cache");
93             return;
94         }
95
96         logger.debug("Retrieving cache for Neutron Subnets");
97         subnetDB = (ConcurrentMap<String, NeutronSubnet>) this.clusterContainerService
98         .getCache("neutronSubnets");
99         if (subnetDB == null) {
100             logger.error("Cache couldn't be retrieved for Neutron Subnets");
101         }
102         logger.debug("Cache was successfully retrieved for Neutron Subnets");
103     }
104
105     @SuppressWarnings("deprecation")
106     private void destroyCache() {
107         if (this.clusterContainerService == null) {
108             logger.error("un-initialized clusterMger, can't destroy cache");
109             return;
110         }
111         logger.debug("Destroying Cache for HostTracker");
112         this.clusterContainerService.destroyCache("neutronSubnets");
113     }
114
115     private void startUp() {
116         allocateCache();
117         retrieveCache();
118         if (subnetDB.isEmpty()) {
119             loadConfiguration();
120         }
121
122     }
123
124     /**
125      * Function called by the dependency manager when all the required
126      * dependencies are satisfied
127      *
128      */
129     void init(Component c) {
130         Dictionary<?, ?> props = c.getServiceProperties();
131         if (props != null) {
132             this.containerName = (String) props.get("containerName");
133             logger.debug("Running containerName: {}", this.containerName);
134         } else {
135             // In the Global instance case the containerName is empty
136             this.containerName = "";
137         }
138         fileName = ROOT + FILENAME + "_" + containerName + ".conf";
139         startUp();
140     }
141
142     /**
143      * Function called by the dependency manager when at least one dependency
144      * become unsatisfied or when the component is shutting down because for
145      * example bundle is being stopped.
146      *
147      */
148     void destroy() {
149         destroyCache();
150     }
151
152     /**
153      * Function called by dependency manager after "init ()" is called and after
154      * the services provided by the class are registered in the service registry
155      *
156      */
157     void start() {
158     }
159
160     /**
161      * Function called by the dependency manager before the services exported by
162      * the component are unregistered, this will be followed by a "destroy ()"
163      * calls
164      *
165      */
166     void stop() {
167     }
168
169     // this method uses reflection to update an object from it's delta.
170
171     private boolean overwrite(Object target, Object delta) {
172         Method[] methods = target.getClass().getMethods();
173
174         for(Method toMethod: methods){
175             if(toMethod.getDeclaringClass().equals(target.getClass())
176                     && toMethod.getName().startsWith("set")){
177
178                 String toName = toMethod.getName();
179                 String fromName = toName.replace("set", "get");
180
181                 try {
182                     Method fromMethod = delta.getClass().getMethod(fromName);
183                     Object value = fromMethod.invoke(delta, (Object[])null);
184                     if(value != null){
185                         toMethod.invoke(target, value);
186                     }
187                 } catch (Exception e) {
188                     e.printStackTrace();
189                     return false;
190                 }
191             }
192         }
193         return true;
194     }
195
196
197     // IfNBSubnetCRUD methods
198
199     @Override
200     public boolean subnetExists(String uuid) {
201         return subnetDB.containsKey(uuid);
202     }
203
204     @Override
205     public NeutronSubnet getSubnet(String uuid) {
206         if (!subnetExists(uuid))
207             return null;
208         return subnetDB.get(uuid);
209     }
210
211     @Override
212     public List<NeutronSubnet> getAllSubnets() {
213         Set<NeutronSubnet> allSubnets = new HashSet<NeutronSubnet>();
214         for (Entry<String, NeutronSubnet> entry : subnetDB.entrySet()) {
215             NeutronSubnet subnet = entry.getValue();
216             allSubnets.add(subnet);
217         }
218         logger.debug("Exiting getAllSubnets, Found {} OpenStackSubnets", allSubnets.size());
219         List<NeutronSubnet> ans = new ArrayList<NeutronSubnet>();
220         ans.addAll(allSubnets);
221         return ans;
222     }
223
224     @Override
225     public boolean addSubnet(NeutronSubnet input) {
226         String id = input.getID();
227         if (subnetExists(id))
228             return false;
229         subnetDB.putIfAbsent(id, input);
230         INeutronNetworkCRUD networkIf = NeutronCRUDInterfaces.getINeutronNetworkCRUD(this);
231
232         NeutronNetwork targetNet = networkIf.getNetwork(input.getNetworkUUID());
233         targetNet.addSubnet(id);
234         return true;
235     }
236
237     @Override
238     public boolean removeSubnet(String uuid) {
239         if (!subnetExists(uuid))
240             return false;
241         NeutronSubnet target = subnetDB.get(uuid);
242         INeutronNetworkCRUD networkIf = NeutronCRUDInterfaces.getINeutronNetworkCRUD(this);
243
244         NeutronNetwork targetNet = networkIf.getNetwork(target.getNetworkUUID());
245         targetNet.removeSubnet(uuid);
246         subnetDB.remove(uuid);
247         return true;
248     }
249
250     @Override
251     public boolean updateSubnet(String uuid, NeutronSubnet delta) {
252         if (!subnetExists(uuid))
253             return false;
254         NeutronSubnet target = subnetDB.get(uuid);
255         return overwrite(target, delta);
256     }
257
258     @Override
259     public boolean subnetInUse(String subnetUUID) {
260         if (!subnetExists(subnetUUID))
261             return true;
262         NeutronSubnet target = subnetDB.get(subnetUUID);
263         return (target.getPortsInSubnet().size() > 0);
264     }
265
266     @SuppressWarnings("unchecked")
267     private void loadConfiguration() {
268         ObjectReader objReader = new ObjectReader();
269         ConcurrentMap<String, NeutronSubnet> confList = (ConcurrentMap<String, NeutronSubnet>)
270                                                             objReader.read(this, fileName);
271
272         if (confList == null) {
273             return;
274         }
275
276         for (String key : confList.keySet()) {
277             subnetDB.put(key, confList.get(key));
278         }
279     }
280
281     @Override
282     public Status saveConfiguration() {
283         ObjectWriter objWriter = new ObjectWriter();
284         return objWriter.write(new ConcurrentHashMap<String, NeutronSubnet>(subnetDB), fileName);
285     }
286
287     @Override
288     public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
289         return ois.readObject();
290     }
291
292 }