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