Merge "Fix for Bug 3"
[controller.git] / opendaylight / networkconfiguration / neutron / implementation / src / main / java / org / opendaylight / controller / networkconfig / neutron / implementation / NeutronFloatingIPInterface.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.INeutronFloatingIPCRUD;
32 import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkCRUD;
33 import org.opendaylight.controller.networkconfig.neutron.INeutronPortCRUD;
34 import org.opendaylight.controller.networkconfig.neutron.INeutronSubnetCRUD;
35 import org.opendaylight.controller.networkconfig.neutron.NeutronCRUDInterfaces;
36 import org.opendaylight.controller.networkconfig.neutron.NeutronFloatingIP;
37 import org.opendaylight.controller.networkconfig.neutron.NeutronPort;
38 import org.opendaylight.controller.networkconfig.neutron.NeutronSubnet;
39 import org.opendaylight.controller.sal.utils.GlobalConstants;
40 import org.opendaylight.controller.sal.utils.IObjectReader;
41 import org.opendaylight.controller.sal.utils.ObjectReader;
42 import org.opendaylight.controller.sal.utils.ObjectWriter;
43 import org.opendaylight.controller.sal.utils.Status;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 public class NeutronFloatingIPInterface implements INeutronFloatingIPCRUD, IConfigurationContainerAware,
48                                                    IObjectReader {
49     private static final Logger logger = LoggerFactory.getLogger(NeutronFloatingIPInterface.class);
50     private static String ROOT = GlobalConstants.STARTUPHOME.toString();
51     private static final String FILENAME ="neutron.floatingip";
52     private static String fileName;
53     private String containerName = null;
54
55     private IClusterContainerServices clusterContainerService = null;
56     private ConcurrentMap<String, NeutronFloatingIP> floatingIPDB;
57
58     // methods needed for creating caches
59
60     void setClusterContainerService(IClusterContainerServices s) {
61         logger.debug("Cluster Service set");
62         this.clusterContainerService = s;
63     }
64
65     void unsetClusterContainerService(IClusterContainerServices s) {
66         if (this.clusterContainerService == s) {
67             logger.debug("Cluster Service removed!");
68             this.clusterContainerService = null;
69         }
70     }
71
72     @SuppressWarnings("deprecation")
73     private void allocateCache() {
74         if (this.clusterContainerService == null) {
75             logger.error("un-initialized clusterContainerService, can't create cache");
76             return;
77         }
78         logger.debug("Creating Cache for Neutron FloatingIPs");
79         try {
80             // neutron caches
81             this.clusterContainerService.createCache("neutronFloatingIPs",
82                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
83         } catch (CacheConfigException cce) {
84             logger.error("Cache couldn't be created for Neutron -  check cache mode");
85         } catch (CacheExistException cce) {
86             logger.error("Cache for Neutron already exists, destroy and recreate");
87         }
88         logger.debug("Cache successfully created for NeutronFloatingIps");
89     }
90
91     @SuppressWarnings({ "unchecked", "deprecation" })
92     private void retrieveCache() {
93         if (this.clusterContainerService == null) {
94             logger.error("un-initialized clusterContainerService, can't retrieve cache");
95             return;
96         }
97
98         logger.debug("Retrieving cache for Neutron FloatingIPs");
99         floatingIPDB = (ConcurrentMap<String, NeutronFloatingIP>) this.clusterContainerService
100         .getCache("neutronFloatingIPs");
101         if (floatingIPDB == null) {
102             logger.error("Cache couldn't be retrieved for Neutron FloatingIPs");
103         }
104         logger.debug("Cache was successfully retrieved for Neutron FloatingIPs");
105     }
106
107     @SuppressWarnings("deprecation")
108     private void destroyCache() {
109         if (this.clusterContainerService == null) {
110             logger.error("un-initialized clusterMger, can't destroy cache");
111             return;
112         }
113         logger.debug("Destroying Cache for HostTracker");
114         this.clusterContainerService.destroyCache("neutronFloatingIPs");
115     }
116
117     private void startUp() {
118         allocateCache();
119         retrieveCache();
120         if (floatingIPDB.isEmpty()) {
121             loadConfiguration();
122         }
123     }
124
125     /**
126      * Function called by the dependency manager when all the required
127      * dependencies are satisfied
128      *
129      */
130     void init(Component c) {
131         Dictionary<?, ?> props = c.getServiceProperties();
132         if (props != null) {
133             this.containerName = (String) props.get("containerName");
134             logger.debug("Running containerName: {}", this.containerName);
135         } else {
136             // In the Global instance case the containerName is empty
137             this.containerName = "";
138         }
139         fileName = ROOT + FILENAME + "_" + containerName + ".conf";
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     // IfNBFloatingIPCRUD interface methods
198
199     @Override
200     public boolean floatingIPExists(String uuid) {
201         return floatingIPDB.containsKey(uuid);
202     }
203
204     @Override
205     public NeutronFloatingIP getFloatingIP(String uuid) {
206         if (!floatingIPExists(uuid))
207             return null;
208         return floatingIPDB.get(uuid);
209     }
210
211     @Override
212     public List<NeutronFloatingIP> getAllFloatingIPs() {
213         Set<NeutronFloatingIP> allIPs = new HashSet<NeutronFloatingIP>();
214         for (Entry<String, NeutronFloatingIP> entry : floatingIPDB.entrySet()) {
215             NeutronFloatingIP floatingip = entry.getValue();
216             allIPs.add(floatingip);
217         }
218         logger.debug("Exiting getAllFloatingIPs, Found {} FloatingIPs", allIPs.size());
219         List<NeutronFloatingIP> ans = new ArrayList<NeutronFloatingIP>();
220         ans.addAll(allIPs);
221         return ans;
222     }
223
224     @Override
225     public boolean addFloatingIP(NeutronFloatingIP input) {
226         INeutronNetworkCRUD networkCRUD = NeutronCRUDInterfaces.getINeutronNetworkCRUD(this);
227         INeutronSubnetCRUD subnetCRUD = NeutronCRUDInterfaces.getINeutronSubnetCRUD(this);
228         INeutronPortCRUD portCRUD = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
229
230         if (floatingIPExists(input.getID()))
231             return false;
232         //if floating_ip_address isn't there, allocate from the subnet pool
233         NeutronSubnet subnet = subnetCRUD.getSubnet(networkCRUD.getNetwork(input.getFloatingNetworkUUID()).getSubnets().get(0));
234         if (input.getFloatingIPAddress() == null)
235             input.setFloatingIPAddress(subnet.getLowAddr());
236         subnet.allocateIP(input.getFloatingIPAddress());
237
238         //if port_id is there, bind port to this floating ip
239         if (input.getPortUUID() != null) {
240             NeutronPort port = portCRUD.getPort(input.getPortUUID());
241             port.addFloatingIP(input.getFixedIPAddress(), input);
242         }
243
244         floatingIPDB.putIfAbsent(input.getID(), input);
245         return true;
246     }
247
248     @Override
249     public boolean removeFloatingIP(String uuid) {
250         INeutronNetworkCRUD networkCRUD = NeutronCRUDInterfaces.getINeutronNetworkCRUD(this);
251         INeutronSubnetCRUD subnetCRUD = NeutronCRUDInterfaces.getINeutronSubnetCRUD(this);
252         INeutronPortCRUD portCRUD = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
253
254         if (!floatingIPExists(uuid))
255             return false;
256         NeutronFloatingIP floatIP = getFloatingIP(uuid);
257         //if floating_ip_address isn't there, allocate from the subnet pool
258         NeutronSubnet subnet = subnetCRUD.getSubnet(networkCRUD.getNetwork(floatIP.getFloatingNetworkUUID()).getSubnets().get(0));
259         subnet.releaseIP(floatIP.getFloatingIPAddress());
260         if (floatIP.getPortUUID() != null) {
261             NeutronPort port = portCRUD.getPort(floatIP.getPortUUID());
262             port.removeFloatingIP(floatIP.getFixedIPAddress());
263         }
264         floatingIPDB.remove(uuid);
265         return true;
266     }
267
268     @Override
269     public boolean updateFloatingIP(String uuid, NeutronFloatingIP delta) {
270         INeutronPortCRUD portCRUD = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
271
272         if (!floatingIPExists(uuid))
273             return false;
274         NeutronFloatingIP target = floatingIPDB.get(uuid);
275         if (target.getPortUUID() != null) {
276             NeutronPort port = portCRUD.getPort(target.getPortUUID());
277             port.removeFloatingIP(target.getFixedIPAddress());
278         }
279
280         //if port_id is there, bind port to this floating ip
281         if (delta.getPortUUID() != null) {
282             NeutronPort port = portCRUD.getPort(delta.getPortUUID());
283             port.addFloatingIP(delta.getFixedIPAddress(), delta);
284         }
285
286         target.setPortUUID(delta.getPortUUID());
287         target.setFixedIPAddress(delta.getFixedIPAddress());
288         return true;
289     }
290
291     @SuppressWarnings("unchecked")
292     private void loadConfiguration() {
293         ObjectReader objReader = new ObjectReader();
294         ConcurrentMap<String, NeutronFloatingIP> confList = (ConcurrentMap<String, NeutronFloatingIP>)
295                                                             objReader.read(this, fileName);
296
297         if (confList == null) {
298             return;
299         }
300
301         for (String key : confList.keySet()) {
302             floatingIPDB.put(key, confList.get(key));
303         }
304     }
305
306     @Override
307     public Status saveConfiguration() {
308         ObjectWriter objWriter = new ObjectWriter();
309         return objWriter.write(new ConcurrentHashMap<String, NeutronFloatingIP>(floatingIPDB), fileName);
310     }
311
312     @Override
313     public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
314         return ois.readObject();
315     }
316 }