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