b1e382107adcb5e52b58da3e41a5f4b91e9881bf
[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.lang.reflect.Method;
12 import java.util.ArrayList;
13 import java.util.Dictionary;
14 import java.util.EnumSet;
15 import java.util.HashSet;
16 import java.util.List;
17 import java.util.Set;
18 import java.util.Map.Entry;
19 import java.util.concurrent.ConcurrentMap;
20
21 import org.apache.felix.dm.Component;
22 import org.opendaylight.controller.clustering.services.CacheConfigException;
23 import org.opendaylight.controller.clustering.services.CacheExistException;
24 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
25 import org.opendaylight.controller.clustering.services.IClusterServices;
26 import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkCRUD;
27 import org.opendaylight.controller.networkconfig.neutron.NeutronNetwork;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 public class NeutronNetworkInterface implements INeutronNetworkCRUD {
32     private static final Logger logger = LoggerFactory.getLogger(NeutronNetworkInterface.class);
33     private String containerName = null;
34
35     private ConcurrentMap<String, NeutronNetwork> networkDB;
36     private IClusterContainerServices clusterContainerService = null;
37
38     // methods needed for creating caches
39
40     void setClusterContainerService(IClusterContainerServices s) {
41         logger.debug("Cluster Service set");
42         this.clusterContainerService = s;
43     }
44
45     void unsetClusterContainerService(IClusterContainerServices s) {
46         if (this.clusterContainerService == s) {
47             logger.debug("Cluster Service removed!");
48             this.clusterContainerService = null;
49         }
50     }
51
52     @SuppressWarnings("deprecation")
53     private void allocateCache() {
54         if (this.clusterContainerService == null) {
55             logger.error("un-initialized clusterContainerService, can't create cache");
56             return;
57         }
58         logger.debug("Creating Cache for Neutron Networks");
59         try {
60             // neutron caches
61             this.clusterContainerService.createCache("neutronNetworks",
62                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
63         } catch (CacheConfigException cce) {
64             logger.error("Cache couldn't be created for Neutron Networks -  check cache mode");
65         } catch (CacheExistException cce) {
66             logger.error("Cache for Neutron Networks already exists, destroy and recreate");
67         }
68         logger.debug("Cache successfully created for Neutron Networks");
69     }
70
71     @SuppressWarnings({ "unchecked", "deprecation" })
72     private void retrieveCache() {
73         if (this.clusterContainerService == null) {
74             logger.error("un-initialized clusterContainerService, can't retrieve cache");
75             return;
76         }
77         logger.debug("Retrieving cache for Neutron Networks");
78         networkDB = (ConcurrentMap<String, NeutronNetwork>) this.clusterContainerService.getCache("neutronNetworks");
79         if (networkDB == null) {
80             logger.error("Cache couldn't be retrieved for Neutron Networks");
81         }
82         logger.debug("Cache was successfully retrieved for Neutron Networks");
83     }
84
85     private void startUp() {
86         allocateCache();
87         retrieveCache();
88     }
89
90     /**
91      * Function called by the dependency manager when all the required
92      * dependencies are satisfied
93      *
94      */
95     void init(Component c) {
96         Dictionary<?, ?> props = c.getServiceProperties();
97         if (props != null) {
98             this.containerName = (String) props.get("containerName");
99             logger.debug("Running containerName: {}", this.containerName);
100         } else {
101             // In the Global instance case the containerName is empty
102             this.containerName = "";
103         }
104         startUp();
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 Neutron Networks");
114         this.clusterContainerService.destroyCache("Neutron Networks");
115     }
116
117     /**
118      * Function called by the dependency manager when at least one dependency
119      * become unsatisfied or when the component is shutting down because for
120      * example bundle is being stopped.
121      *
122      */
123     void destroy() {
124         destroyCache();
125     }
126
127     /**
128      * Function called by dependency manager after "init ()" is called and after
129      * the services provided by the class are registered in the service registry
130      *
131      */
132     void start() {
133     }
134
135     /**
136      * Function called by the dependency manager before the services exported by
137      * the component are unregistered, this will be followed by a "destroy ()"
138      * calls
139      *
140      */
141     void stop() {
142     }
143
144     // this method uses reflection to update an object from it's delta.
145
146     private boolean overwrite(Object target, Object delta) {
147         Method[] methods = target.getClass().getMethods();
148
149         for(Method toMethod: methods){
150             if(toMethod.getDeclaringClass().equals(target.getClass())
151                     && toMethod.getName().startsWith("set")){
152
153                 String toName = toMethod.getName();
154                 String fromName = toName.replace("set", "get");
155
156                 try {
157                     Method fromMethod = delta.getClass().getMethod(fromName);
158                     Object value = fromMethod.invoke(delta, (Object[])null);
159                     if(value != null){
160                         toMethod.invoke(target, value);
161                     }
162                 } catch (Exception e) {
163                     e.printStackTrace();
164                     return false;
165                 }
166             }
167         }
168         return true;
169     }
170
171     // IfNBNetworkCRUD methods
172
173     public boolean networkExists(String uuid) {
174         return networkDB.containsKey(uuid);
175     }
176
177     public NeutronNetwork getNetwork(String uuid) {
178         if (!networkExists(uuid))
179             return null;
180         return networkDB.get(uuid);
181     }
182
183     public List<NeutronNetwork> getAllNetworks() {
184         Set<NeutronNetwork> allNetworks = new HashSet<NeutronNetwork>();
185         for (Entry<String, NeutronNetwork> entry : networkDB.entrySet()) {
186             NeutronNetwork network = entry.getValue();
187             allNetworks.add(network);
188         }
189         logger.debug("Exiting getAllNetworks, Found {} OpenStackNetworks", allNetworks.size());
190         List<NeutronNetwork> ans = new ArrayList<NeutronNetwork>();
191         ans.addAll(allNetworks);
192         return ans;
193     }
194
195     public boolean addNetwork(NeutronNetwork input) {
196         if (networkExists(input.getID()))
197             return false;
198         networkDB.putIfAbsent(input.getID(), input);
199       //TODO: add code to find INeutronNetworkAware services and call newtorkCreated on them
200         return true;
201     }
202
203     public boolean removeNetwork(String uuid) {
204         if (!networkExists(uuid))
205             return false;
206         networkDB.remove(uuid);
207       //TODO: add code to find INeutronNetworkAware services and call newtorkDeleted on them
208         return true;
209     }
210
211     public boolean updateNetwork(String uuid, NeutronNetwork delta) {
212         if (!networkExists(uuid))
213             return false;
214         NeutronNetwork target = networkDB.get(uuid);
215         return overwrite(target, delta);
216     }
217
218     public boolean networkInUse(String netUUID) {
219         if (!networkExists(netUUID))
220             return true;
221         NeutronNetwork target = networkDB.get(netUUID);
222         if (target.getPortsOnNetwork().size() > 0)
223             return true;
224         return false;
225     }
226 }