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