6dc0e46b61749673b799c7d94efb91240658f4e3
[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().size() == 0) {
237             List<Neutron_IPs> list = input.getFixedIPs();
238             Iterator<NeutronSubnet> subnetIterator = systemCRUD.getAllSubnets().iterator();
239             while (subnetIterator.hasNext()) {
240                 NeutronSubnet subnet = subnetIterator.next();
241                 if (subnet.getNetworkUUID().equals(input.getNetworkUUID())) {
242                     list.add(new Neutron_IPs(subnet.getID()));
243                 }
244             }
245         }
246         Iterator<Neutron_IPs> fixedIPIterator = input.getFixedIPs().iterator();
247         while (fixedIPIterator.hasNext()) {
248             Neutron_IPs ip = fixedIPIterator.next();
249             NeutronSubnet subnet = systemCRUD.getSubnet(ip.getSubnetUUID());
250             if (ip.getIpAddress() == null) {
251                 ip.setIpAddress(subnet.getLowAddr());
252             }
253             if (!ip.getIpAddress().equals(subnet.getGatewayIP())) {
254                 subnet.allocateIP(ip.getIpAddress());
255             }
256             else {
257                 subnet.setGatewayIPAllocated();
258             }
259             subnet.addPort(input);
260         }
261         INeutronNetworkCRUD networkIf = NeutronCRUDInterfaces.getINeutronNetworkCRUD(this);
262
263         NeutronNetwork network = networkIf.getNetwork(input.getNetworkUUID());
264         network.addPort(input);
265         return true;
266     }
267
268     @Override
269     public boolean removePort(String uuid) {
270         if (!portExists(uuid)) {
271             return false;
272         }
273         NeutronPort port = getPort(uuid);
274         portDB.remove(uuid);
275         INeutronNetworkCRUD networkCRUD = NeutronCRUDInterfaces.getINeutronNetworkCRUD(this);
276         INeutronSubnetCRUD systemCRUD = NeutronCRUDInterfaces.getINeutronSubnetCRUD(this);
277
278         NeutronNetwork network = networkCRUD.getNetwork(port.getNetworkUUID());
279         network.removePort(port);
280         Iterator<Neutron_IPs> fixedIPIterator = port.getFixedIPs().iterator();
281         while (fixedIPIterator.hasNext()) {
282             Neutron_IPs ip = fixedIPIterator.next();
283             NeutronSubnet subnet = systemCRUD.getSubnet(ip.getSubnetUUID());
284             if (!ip.getIpAddress().equals(subnet.getGatewayIP())) {
285                 subnet.releaseIP(ip.getIpAddress());
286             }
287             else {
288                 subnet.resetGatewayIPAllocated();
289             }
290             subnet.removePort(port);
291         }
292         return true;
293     }
294
295     @Override
296     public boolean updatePort(String uuid, NeutronPort delta) {
297         if (!portExists(uuid)) {
298             return false;
299         }
300         NeutronPort target = portDB.get(uuid);
301         // remove old Fixed_IPs
302         if (delta.getFixedIPs() != null) {
303             NeutronPort port = getPort(uuid);
304             INeutronSubnetCRUD systemCRUD = NeutronCRUDInterfaces.getINeutronSubnetCRUD(this);
305             for (Neutron_IPs ip: port.getFixedIPs()) {
306                 NeutronSubnet subnet = systemCRUD.getSubnet(ip.getSubnetUUID());
307                 subnet.releaseIP(ip.getIpAddress());
308             }
309
310             // allocate new Fixed_IPs
311             for (Neutron_IPs ip: delta.getFixedIPs()) {
312                 NeutronSubnet subnet = systemCRUD.getSubnet(ip.getSubnetUUID());
313                 if (ip.getIpAddress() == null) {
314                     ip.setIpAddress(subnet.getLowAddr());
315                 }
316                 subnet.allocateIP(ip.getIpAddress());
317             }
318         }
319         return overwrite(target, delta);
320     }
321
322     @Override
323     public boolean macInUse(String macAddress) {
324         List<NeutronPort> ports = getAllPorts();
325         Iterator<NeutronPort> portIterator = ports.iterator();
326         while (portIterator.hasNext()) {
327             NeutronPort port = portIterator.next();
328             if (macAddress.equalsIgnoreCase(port.getMacAddress())) {
329                 return true;
330             }
331         }
332         return false;
333     }
334
335     @Override
336     public NeutronPort getGatewayPort(String subnetUUID) {
337         INeutronSubnetCRUD systemCRUD = NeutronCRUDInterfaces.getINeutronSubnetCRUD(this);
338         NeutronSubnet subnet = systemCRUD.getSubnet(subnetUUID);
339         Iterator<NeutronPort> portIterator = getAllPorts().iterator();
340         while (portIterator.hasNext()) {
341             NeutronPort port = portIterator.next();
342             List<Neutron_IPs> fixedIPs = port.getFixedIPs();
343             if (fixedIPs.size() == 1) {
344                 if (subnet.getGatewayIP().equals(fixedIPs.get(0).getIpAddress())) {
345                     return port;
346                 }
347             }
348         }
349         return null;
350     }
351
352     private void loadConfiguration() {
353         for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, FILE_NAME)) {
354             NeutronPort nn = (NeutronPort) conf;
355             portDB.put(nn.getID(), nn);
356         }
357     }
358
359     @Override
360     public Status saveConfiguration() {
361         return configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(portDB.values()),
362                 FILE_NAME);
363     }
364
365     @Override
366     public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
367         return ois.readObject();
368     }
369
370 }