Config save support for networkconfiguration.neutron
[controller.git] / opendaylight / networkconfiguration / neutron / implementation / src / main / java / org / opendaylight / controller / networkconfig / neutron / implementation / NeutronNetworkInterface.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.NeutronNetwork;
33 import org.opendaylight.controller.sal.utils.GlobalConstants;
34 import org.opendaylight.controller.sal.utils.IObjectReader;
35 import org.opendaylight.controller.sal.utils.ObjectReader;
36 import org.opendaylight.controller.sal.utils.ObjectWriter;
37 import org.opendaylight.controller.sal.utils.Status;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 public class NeutronNetworkInterface implements INeutronNetworkCRUD, IConfigurationContainerAware,
42                                                 IObjectReader {
43     private static final Logger logger = LoggerFactory.getLogger(NeutronNetworkInterface.class);
44     private static String ROOT = GlobalConstants.STARTUPHOME.toString();
45     private static final String FILENAME ="neutron.network";
46     private static String fileName;
47     private String containerName = null;
48
49     private ConcurrentMap<String, NeutronNetwork> networkDB;
50     private IClusterContainerServices clusterContainerService = null;
51
52     // methods needed for creating caches
53
54     void setClusterContainerService(IClusterContainerServices s) {
55         logger.debug("Cluster Service set");
56         this.clusterContainerService = s;
57     }
58
59     void unsetClusterContainerService(IClusterContainerServices s) {
60         if (this.clusterContainerService == s) {
61             logger.debug("Cluster Service removed!");
62             this.clusterContainerService = null;
63         }
64     }
65
66     @SuppressWarnings("deprecation")
67     private void allocateCache() {
68         if (this.clusterContainerService == null) {
69             logger.error("un-initialized clusterContainerService, can't create cache");
70             return;
71         }
72         logger.debug("Creating Cache for Neutron Networks");
73         try {
74             // neutron caches
75             this.clusterContainerService.createCache("neutronNetworks",
76                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
77         } catch (CacheConfigException cce) {
78             logger.error("Cache couldn't be created for Neutron Networks -  check cache mode");
79         } catch (CacheExistException cce) {
80             logger.error("Cache for Neutron Networks already exists, destroy and recreate");
81         }
82         logger.debug("Cache successfully created for Neutron Networks");
83     }
84
85     @SuppressWarnings({ "unchecked", "deprecation" })
86     private void retrieveCache() {
87         if (this.clusterContainerService == null) {
88             logger.error("un-initialized clusterContainerService, can't retrieve cache");
89             return;
90         }
91         logger.debug("Retrieving cache for Neutron Networks");
92         networkDB = (ConcurrentMap<String, NeutronNetwork>) this.clusterContainerService.getCache("neutronNetworks");
93         if (networkDB == null) {
94             logger.error("Cache couldn't be retrieved for Neutron Networks");
95         }
96         logger.debug("Cache was successfully retrieved for Neutron Networks");
97     }
98
99     private void startUp() {
100         allocateCache();
101         retrieveCache();
102         if (networkDB.isEmpty()) {
103             loadConfiguration();
104         }
105     }
106
107     /**
108      * Function called by the dependency manager when all the required
109      * dependencies are satisfied
110      *
111      */
112     void init(Component c) {
113         Dictionary<?, ?> props = c.getServiceProperties();
114         if (props != null) {
115             this.containerName = (String) props.get("containerName");
116             logger.debug("Running containerName: {}", this.containerName);
117         } else {
118             // In the Global instance case the containerName is empty
119             this.containerName = "";
120         }
121         fileName = ROOT + FILENAME + "_" + containerName + ".conf";
122         startUp();
123     }
124
125     @SuppressWarnings("deprecation")
126     private void destroyCache() {
127         if (this.clusterContainerService == null) {
128             logger.error("un-initialized clusterMger, can't destroy cache");
129             return;
130         }
131         logger.debug("Destroying Cache for Neutron Networks");
132         this.clusterContainerService.destroyCache("Neutron Networks");
133     }
134
135     /**
136      * Function called by the dependency manager when at least one dependency
137      * become unsatisfied or when the component is shutting down because for
138      * example bundle is being stopped.
139      *
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      */
150     void start() {
151     }
152
153     /**
154      * Function called by the dependency manager before the services exported by
155      * the component are unregistered, this will be followed by a "destroy ()"
156      * calls
157      *
158      */
159     void stop() {
160     }
161
162     // this method uses reflection to update an object from it's delta.
163
164     private boolean overwrite(Object target, Object delta) {
165         Method[] methods = target.getClass().getMethods();
166
167         for(Method toMethod: methods){
168             if(toMethod.getDeclaringClass().equals(target.getClass())
169                     && toMethod.getName().startsWith("set")){
170
171                 String toName = toMethod.getName();
172                 String fromName = toName.replace("set", "get");
173
174                 try {
175                     Method fromMethod = delta.getClass().getMethod(fromName);
176                     Object value = fromMethod.invoke(delta, (Object[])null);
177                     if(value != null){
178                         toMethod.invoke(target, value);
179                     }
180                 } catch (Exception e) {
181                     e.printStackTrace();
182                     return false;
183                 }
184             }
185         }
186         return true;
187     }
188
189     // IfNBNetworkCRUD methods
190
191     @Override
192     public boolean networkExists(String uuid) {
193         return networkDB.containsKey(uuid);
194     }
195
196     @Override
197     public NeutronNetwork getNetwork(String uuid) {
198         if (!networkExists(uuid))
199             return null;
200         return networkDB.get(uuid);
201     }
202
203     @Override
204     public List<NeutronNetwork> getAllNetworks() {
205         Set<NeutronNetwork> allNetworks = new HashSet<NeutronNetwork>();
206         for (Entry<String, NeutronNetwork> entry : networkDB.entrySet()) {
207             NeutronNetwork network = entry.getValue();
208             allNetworks.add(network);
209         }
210         logger.debug("Exiting getAllNetworks, Found {} OpenStackNetworks", allNetworks.size());
211         List<NeutronNetwork> ans = new ArrayList<NeutronNetwork>();
212         ans.addAll(allNetworks);
213         return ans;
214     }
215
216     @Override
217     public boolean addNetwork(NeutronNetwork input) {
218         if (networkExists(input.getID()))
219             return false;
220         networkDB.putIfAbsent(input.getID(), input);
221       //TODO: add code to find INeutronNetworkAware services and call newtorkCreated on them
222         return true;
223     }
224
225     @Override
226     public boolean removeNetwork(String uuid) {
227         if (!networkExists(uuid))
228             return false;
229         networkDB.remove(uuid);
230       //TODO: add code to find INeutronNetworkAware services and call newtorkDeleted on them
231         return true;
232     }
233
234     @Override
235     public boolean updateNetwork(String uuid, NeutronNetwork delta) {
236         if (!networkExists(uuid))
237             return false;
238         NeutronNetwork target = networkDB.get(uuid);
239         return overwrite(target, delta);
240     }
241
242     @Override
243     public boolean networkInUse(String netUUID) {
244         if (!networkExists(netUUID))
245             return true;
246         NeutronNetwork target = networkDB.get(netUUID);
247         if (target.getPortsOnNetwork().size() > 0)
248             return true;
249         return false;
250     }
251
252     @SuppressWarnings("unchecked")
253     private void loadConfiguration() {
254         ObjectReader objReader = new ObjectReader();
255         ConcurrentMap<String, NeutronNetwork> confList = (ConcurrentMap<String, NeutronNetwork>)
256                                                             objReader.read(this, fileName);
257
258         if (confList == null) {
259             return;
260         }
261
262         for (String key : confList.keySet()) {
263             networkDB.put(key, confList.get(key));
264         }
265     }
266
267     @Override
268     public Status saveConfiguration() {
269         ObjectWriter objWriter = new ObjectWriter();
270         return objWriter.write(new ConcurrentHashMap<String, NeutronNetwork>(networkDB), fileName);
271     }
272
273     @Override
274     public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
275         return ois.readObject();
276     }
277
278 }