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