Merge "BUG 2335 : Add jolokia feature"
[controller.git] / opendaylight / networkconfiguration / neutron / implementation / src / main / java / org / opendaylight / controller / networkconfig / neutron / implementation / NeutronPortInterface.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.Iterator;
20 import java.util.List;
21 import java.util.Map.Entry;
22 import java.util.Set;
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.ConfigurationObject;
31 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
32 import org.opendaylight.controller.configuration.IConfigurationContainerService;
33 import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkCRUD;
34 import org.opendaylight.controller.networkconfig.neutron.INeutronPortCRUD;
35 import org.opendaylight.controller.networkconfig.neutron.INeutronSubnetCRUD;
36 import org.opendaylight.controller.networkconfig.neutron.NeutronCRUDInterfaces;
37 import org.opendaylight.controller.networkconfig.neutron.NeutronNetwork;
38 import org.opendaylight.controller.networkconfig.neutron.NeutronPort;
39 import org.opendaylight.controller.networkconfig.neutron.NeutronSubnet;
40 import org.opendaylight.controller.networkconfig.neutron.Neutron_IPs;
41 import org.opendaylight.controller.sal.utils.IObjectReader;
42 import org.opendaylight.controller.sal.utils.Status;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 public class NeutronPortInterface implements INeutronPortCRUD, IConfigurationContainerAware,
47                                              IObjectReader {
48     private static final Logger logger = LoggerFactory.getLogger(NeutronPortInterface.class);
49     private static final String FILE_NAME ="neutron.port.conf";
50     private String containerName = null;
51
52     private IClusterContainerServices clusterContainerService = null;
53     private IConfigurationContainerService configurationService;
54     private ConcurrentMap<String, NeutronPort> portDB;
55
56     // methods needed for creating caches
57
58     void setClusterContainerService(IClusterContainerServices s) {
59         logger.debug("Cluster Service set");
60         clusterContainerService = s;
61     }
62
63     void unsetClusterContainerService(IClusterContainerServices s) {
64         if (clusterContainerService == s) {
65             logger.debug("Cluster Service removed!");
66             clusterContainerService = null;
67         }
68     }
69
70     public void setConfigurationContainerService(IConfigurationContainerService service) {
71         logger.trace("Configuration service set: {}", service);
72         configurationService = service;
73     }
74
75     public void unsetConfigurationContainerService(IConfigurationContainerService service) {
76         logger.trace("Configuration service removed: {}", service);
77         configurationService = null;
78     }
79
80     private void allocateCache() {
81         if (clusterContainerService == null) {
82             logger.error("un-initialized clusterContainerService, can't create cache");
83             return;
84         }
85         logger.debug("Creating Cache for OpenDOVE");
86         try {
87             // neutron caches
88             clusterContainerService.createCache("neutronPorts",
89                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
90         } catch (CacheConfigException cce) {
91             logger.error("Cache couldn't be created for OpenDOVE -  check cache mode");
92         } catch (CacheExistException cce) {
93             logger.error("Cache for OpenDOVE already exists, destroy and recreate");
94         }
95         logger.debug("Cache successfully created for OpenDOVE");
96     }
97
98     @SuppressWarnings({ "unchecked" })
99     private void retrieveCache() {
100         if (clusterContainerService == null) {
101             logger.error("un-initialized clusterContainerService, can't retrieve cache");
102             return;
103         }
104
105         logger.debug("Retrieving cache for Neutron Ports");
106         portDB = (ConcurrentMap<String, NeutronPort>) clusterContainerService
107         .getCache("neutronPorts");
108         if (portDB == null) {
109             logger.error("Cache couldn't be retrieved for Neutron Ports");
110         }
111         logger.debug("Cache was successfully retrieved for Neutron Ports");
112     }
113
114     private void destroyCache() {
115         if (clusterContainerService == null) {
116             logger.error("un-initialized clusterMger, can't destroy cache");
117             return;
118         }
119         logger.debug("Destroying Cache for HostTracker");
120         clusterContainerService.destroyCache("neutronPorts");
121     }
122
123     private void startUp() {
124         allocateCache();
125         retrieveCache();
126         loadConfiguration();
127     }
128
129     /**
130      * Function called by the dependency manager when all the required
131      * dependencies are satisfied
132      *
133      */
134     void init(Component c) {
135         Dictionary<?, ?> props = c.getServiceProperties();
136         if (props != null) {
137             containerName = (String) props.get("containerName");
138             logger.debug("Running containerName: {}", containerName);
139         } else {
140             // In the Global instance case the containerName is empty
141             containerName = "";
142         }
143         startUp();
144     }
145
146     /**
147      * Function called by the dependency manager when at least one dependency
148      * become unsatisfied or when the component is shutting down because for
149      * example bundle is being stopped.
150      *
151      */
152     void destroy() {
153         destroyCache();
154     }
155
156     /**
157      * Function called by dependency manager after "init ()" is called and after
158      * the services provided by the class are registered in the service registry
159      *
160      */
161     void start() {
162     }
163
164     /**
165      * Function called by the dependency manager before the services exported by
166      * the component are unregistered, this will be followed by a "destroy ()"
167      * calls
168      *
169      */
170     void stop() {
171     }
172
173     // this method uses reflection to update an object from it's delta.
174
175     private boolean overwrite(Object target, Object delta) {
176         Method[] methods = target.getClass().getMethods();
177
178         for(Method toMethod: methods){
179             if(toMethod.getDeclaringClass().equals(target.getClass())
180                     && toMethod.getName().startsWith("set")){
181
182                 String toName = toMethod.getName();
183                 String fromName = toName.replace("set", "get");
184
185                 try {
186                     Method fromMethod = delta.getClass().getMethod(fromName);
187                     Object value = fromMethod.invoke(delta, (Object[])null);
188                     if(value != null){
189                         toMethod.invoke(target, value);
190                     }
191                 } catch (Exception e) {
192                     e.printStackTrace();
193                     return false;
194                 }
195             }
196         }
197         return true;
198     }
199
200     // IfNBPortCRUD methods
201
202     @Override
203     public boolean portExists(String uuid) {
204         return portDB.containsKey(uuid);
205     }
206
207     @Override
208     public NeutronPort getPort(String uuid) {
209         if (!portExists(uuid)) {
210             return null;
211         }
212         return portDB.get(uuid);
213     }
214
215     @Override
216     public List<NeutronPort> getAllPorts() {
217         Set<NeutronPort> allPorts = new HashSet<NeutronPort>();
218         for (Entry<String, NeutronPort> entry : portDB.entrySet()) {
219             NeutronPort port = entry.getValue();
220             allPorts.add(port);
221         }
222         logger.debug("Exiting getAllPorts, Found {} OpenStackPorts", allPorts.size());
223         List<NeutronPort> ans = new ArrayList<NeutronPort>();
224         ans.addAll(allPorts);
225         return ans;
226     }
227
228     @Override
229     public boolean addPort(NeutronPort input) {
230         if (portExists(input.getID())) {
231             return false;
232         }
233         portDB.putIfAbsent(input.getID(), input);
234         // if there are no fixed IPs, allocate one for each subnet in the network
235         INeutronSubnetCRUD systemCRUD = NeutronCRUDInterfaces.getINeutronSubnetCRUD(this);
236         if (input.getFixedIPs() == null){
237            input.setFixedIPs(new ArrayList<Neutron_IPs>());
238         }
239         if (input.getFixedIPs().size() == 0) {
240             List<Neutron_IPs> list = input.getFixedIPs();
241             Iterator<NeutronSubnet> subnetIterator = systemCRUD.getAllSubnets().iterator();
242             while (subnetIterator.hasNext()) {
243                 NeutronSubnet subnet = subnetIterator.next();
244                 if (subnet.getNetworkUUID().equals(input.getNetworkUUID())) {
245                     list.add(new Neutron_IPs(subnet.getID()));
246                 }
247             }
248         }
249         Iterator<Neutron_IPs> fixedIPIterator = input.getFixedIPs().iterator();
250         while (fixedIPIterator.hasNext()) {
251             Neutron_IPs ip = fixedIPIterator.next();
252             NeutronSubnet subnet = systemCRUD.getSubnet(ip.getSubnetUUID());
253             if (ip.getIpAddress() == null) {
254                 ip.setIpAddress(subnet.getLowAddr());
255             }
256             if (!ip.getIpAddress().equals(subnet.getGatewayIP())) {
257                 subnet.allocateIP(ip.getIpAddress());
258             }
259             else {
260                 subnet.setGatewayIPAllocated();
261             }
262             subnet.addPort(input);
263         }
264         INeutronNetworkCRUD networkIf = NeutronCRUDInterfaces.getINeutronNetworkCRUD(this);
265
266         NeutronNetwork network = networkIf.getNetwork(input.getNetworkUUID());
267         network.addPort(input);
268         return true;
269     }
270
271     @Override
272     public boolean removePort(String uuid) {
273         if (!portExists(uuid)) {
274             return false;
275         }
276         NeutronPort port = getPort(uuid);
277         portDB.remove(uuid);
278         INeutronNetworkCRUD networkCRUD = NeutronCRUDInterfaces.getINeutronNetworkCRUD(this);
279         INeutronSubnetCRUD systemCRUD = NeutronCRUDInterfaces.getINeutronSubnetCRUD(this);
280
281         NeutronNetwork network = networkCRUD.getNetwork(port.getNetworkUUID());
282         network.removePort(port);
283         Iterator<Neutron_IPs> fixedIPIterator = port.getFixedIPs().iterator();
284         while (fixedIPIterator.hasNext()) {
285             Neutron_IPs ip = fixedIPIterator.next();
286             NeutronSubnet subnet = systemCRUD.getSubnet(ip.getSubnetUUID());
287             if (!ip.getIpAddress().equals(subnet.getGatewayIP())) {
288                 subnet.releaseIP(ip.getIpAddress());
289             }
290             else {
291                 subnet.resetGatewayIPAllocated();
292             }
293             subnet.removePort(port);
294         }
295         return true;
296     }
297
298     @Override
299     public boolean updatePort(String uuid, NeutronPort delta) {
300         if (!portExists(uuid)) {
301             return false;
302         }
303         NeutronPort target = portDB.get(uuid);
304         // remove old Fixed_IPs
305         if (delta.getFixedIPs() != null) {
306             NeutronPort port = getPort(uuid);
307             INeutronSubnetCRUD systemCRUD = NeutronCRUDInterfaces.getINeutronSubnetCRUD(this);
308             for (Neutron_IPs ip: port.getFixedIPs()) {
309                 NeutronSubnet subnet = systemCRUD.getSubnet(ip.getSubnetUUID());
310                 subnet.releaseIP(ip.getIpAddress());
311             }
312
313             // allocate new Fixed_IPs
314             for (Neutron_IPs ip: delta.getFixedIPs()) {
315                 NeutronSubnet subnet = systemCRUD.getSubnet(ip.getSubnetUUID());
316                 if (ip.getIpAddress() == null) {
317                     ip.setIpAddress(subnet.getLowAddr());
318                 }
319                 subnet.allocateIP(ip.getIpAddress());
320             }
321         }
322         return overwrite(target, delta);
323     }
324
325     @Override
326     public boolean macInUse(String macAddress) {
327         List<NeutronPort> ports = getAllPorts();
328         Iterator<NeutronPort> portIterator = ports.iterator();
329         while (portIterator.hasNext()) {
330             NeutronPort port = portIterator.next();
331             if (macAddress.equalsIgnoreCase(port.getMacAddress())) {
332                 return true;
333             }
334         }
335         return false;
336     }
337
338     @Override
339     public NeutronPort getGatewayPort(String subnetUUID) {
340         INeutronSubnetCRUD systemCRUD = NeutronCRUDInterfaces.getINeutronSubnetCRUD(this);
341         NeutronSubnet subnet = systemCRUD.getSubnet(subnetUUID);
342         Iterator<NeutronPort> portIterator = getAllPorts().iterator();
343         while (portIterator.hasNext()) {
344             NeutronPort port = portIterator.next();
345             List<Neutron_IPs> fixedIPs = port.getFixedIPs();
346             if (fixedIPs.size() == 1) {
347                 if (subnet.getGatewayIP().equals(fixedIPs.get(0).getIpAddress())) {
348                     return port;
349                 }
350             }
351         }
352         return null;
353     }
354
355     private void loadConfiguration() {
356         for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, FILE_NAME)) {
357             NeutronPort nn = (NeutronPort) conf;
358             portDB.put(nn.getID(), nn);
359         }
360     }
361
362     @Override
363     public Status saveConfiguration() {
364         return configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(portDB.values()),
365                 FILE_NAME);
366     }
367
368     @Override
369     public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
370         return ois.readObject();
371     }
372
373 }