aa7280beed8d451968c0ee9f47550ed742dc46a3
[controller.git] / opendaylight / networkconfiguration / neutron / implementation / src / main / java / org / opendaylight / controller / networkconfig / neutron / implementation / NeutronLoadBalancerInterface.java
1 /*
2  * Copyright (C) 2014 Red Hat, Inc.
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 org.apache.felix.dm.Component;
12 import org.opendaylight.controller.clustering.services.CacheConfigException;
13 import org.opendaylight.controller.clustering.services.CacheExistException;
14 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
15 import org.opendaylight.controller.clustering.services.IClusterServices;
16 import org.opendaylight.controller.configuration.ConfigurationObject;
17 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
18 import org.opendaylight.controller.configuration.IConfigurationContainerService;
19 import org.opendaylight.controller.networkconfig.neutron.INeutronLoadBalancerCRUD;
20 import org.opendaylight.controller.networkconfig.neutron.NeutronLoadBalancer;
21 import org.opendaylight.controller.sal.utils.IObjectReader;
22 import org.opendaylight.controller.sal.utils.Status;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 import java.io.FileNotFoundException;
27 import java.io.IOException;
28 import java.io.ObjectInputStream;
29 import java.lang.reflect.Method;
30 import java.util.ArrayList;
31 import java.util.Dictionary;
32 import java.util.EnumSet;
33 import java.util.HashSet;
34 import java.util.List;
35 import java.util.Map.Entry;
36 import java.util.Set;
37 import java.util.concurrent.ConcurrentMap;
38
39 public class NeutronLoadBalancerInterface implements INeutronLoadBalancerCRUD, IConfigurationContainerAware,
40         IObjectReader {
41     private static final Logger logger = LoggerFactory.getLogger(NeutronLoadBalancerInterface.class);
42     private static final String FILE_NAME = "neutron.loadBalancer.conf";
43     private String containerName = null;
44
45     private IClusterContainerServices clusterContainerService = null;
46     private IConfigurationContainerService configurationService;
47     private ConcurrentMap<String, NeutronLoadBalancer> loadBalancerDB;
48
49     // methods needed for creating caches
50     void setClusterContainerService(IClusterContainerServices s) {
51         logger.debug("Cluster Service set");
52         clusterContainerService = s;
53     }
54
55     void unsetClusterContainerService(IClusterContainerServices s) {
56         if (clusterContainerService == s) {
57             logger.debug("Cluster Service removed!");
58             clusterContainerService = null;
59         }
60     }
61
62     public void setConfigurationContainerService(IConfigurationContainerService service) {
63         logger.trace("Configuration service set: {}", service);
64         configurationService = service;
65     }
66
67     public void unsetConfigurationContainerService(IConfigurationContainerService service) {
68         logger.trace("Configuration service removed: {}", service);
69         configurationService = null;
70     }
71
72     private void allocateCache() {
73         if (this.clusterContainerService == null) {
74             logger.error("un-initialized clusterContainerService, can't create cache");
75             return;
76         }
77         logger.debug("Creating Cache for Neutron LoadBalancer");
78         try {
79             // neutron caches
80             this.clusterContainerService.createCache("neutronLoadBalancers",
81                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
82         } catch (CacheConfigException cce) {
83             logger.error("Cache couldn't be created for Neutron LoadBalancer -  check cache mode");
84         } catch (CacheExistException cce) {
85             logger.error("Cache for Neutron LoadBalancer already exists, destroy and recreate");
86         }
87         logger.debug("Cache successfully created for Neutron LoadBalancer");
88     }
89
90     @SuppressWarnings ({"unchecked"})
91     private void retrieveCache() {
92         if (clusterContainerService == null) {
93             logger.error("un-initialized clusterContainerService, can't retrieve cache");
94             return;
95         }
96
97         logger.debug("Retrieving cache for Neutron LoadBalancer");
98         loadBalancerDB = (ConcurrentMap<String, NeutronLoadBalancer>) clusterContainerService
99                 .getCache("neutronLoadBalancers");
100         if (loadBalancerDB == null) {
101             logger.error("Cache couldn't be retrieved for Neutron LoadBalancer");
102         }
103         logger.debug("Cache was successfully retrieved for Neutron LoadBalancer");
104     }
105
106     private void destroyCache() {
107         if (clusterContainerService == null) {
108             logger.error("un-initialized clusterMger, can't destroy cache");
109             return;
110         }
111         logger.debug("Destroying Cache for LoadBalancer");
112         clusterContainerService.destroyCache("neutronLoadBalancers");
113     }
114
115     private void startUp() {
116         allocateCache();
117         retrieveCache();
118         loadConfiguration();
119     }
120
121     /**
122      * Function called by the dependency manager when all the required
123      * dependencies are satisfied
124      */
125     void init(Component c) {
126         Dictionary<?, ?> props = c.getServiceProperties();
127         if (props != null) {
128             this.containerName = (String) props.get("containerName");
129             logger.debug("Running containerName: {}", this.containerName);
130         } else {
131             // In the Global instance case the containerName is empty
132             this.containerName = "";
133         }
134         startUp();
135     }
136
137     /**
138      * Function called by the dependency manager when at least one dependency
139      * become unsatisfied or when the component is shutting down because for
140      * example bundle is being stopped.
141      */
142     void destroy() {
143         destroyCache();
144     }
145
146     /**
147      * Function called by dependency manager after "init ()" is called and after
148      * the services provided by the class are registered in the service registry
149      */
150     void start() {
151     }
152
153     /**
154      * Function called by the dependency manager before the services exported by
155      * the component are unregistered, this will be followed by a "destroy ()"
156      * calls
157      */
158     void stop() {
159     }
160
161     // this method uses reflection to update an object from it's delta.
162
163     private boolean overwrite(Object target, Object delta) {
164         Method[] methods = target.getClass().getMethods();
165
166         for (Method toMethod : methods) {
167             if (toMethod.getDeclaringClass().equals(target.getClass())
168                     && toMethod.getName().startsWith("set")) {
169
170                 String toName = toMethod.getName();
171                 String fromName = toName.replace("set", "get");
172
173                 try {
174                     Method fromMethod = delta.getClass().getMethod(fromName);
175                     Object value = fromMethod.invoke(delta, (Object[]) null);
176                     if (value != null) {
177                         toMethod.invoke(target, value);
178                     }
179                 } catch (Exception e) {
180                     e.printStackTrace();
181                     return false;
182                 }
183             }
184         }
185         return true;
186     }
187
188     @Override
189     public boolean neutronLoadBalancerExists(String uuid) {
190         return loadBalancerDB.containsKey(uuid);
191     }
192
193     @Override
194     public NeutronLoadBalancer getNeutronLoadBalancer(String uuid) {
195         if (!neutronLoadBalancerExists(uuid)) {
196             logger.debug("No LoadBalancer Have Been Defined");
197             return null;
198         }
199         return loadBalancerDB.get(uuid);
200     }
201
202     @Override
203     public List<NeutronLoadBalancer> getAllNeutronLoadBalancers() {
204         Set<NeutronLoadBalancer> allLoadBalancers = new HashSet<NeutronLoadBalancer>();
205         for (Entry<String, NeutronLoadBalancer> entry : loadBalancerDB.entrySet()) {
206             NeutronLoadBalancer loadBalancer = entry.getValue();
207             allLoadBalancers.add(loadBalancer);
208         }
209         logger.debug("Exiting getLoadBalancers, Found {} OpenStackLoadBalancer", allLoadBalancers.size());
210         List<NeutronLoadBalancer> ans = new ArrayList<NeutronLoadBalancer>();
211         ans.addAll(allLoadBalancers);
212         return ans;
213     }
214
215     @Override
216     public boolean addNeutronLoadBalancer(NeutronLoadBalancer input) {
217         if (neutronLoadBalancerExists(input.getLoadBalancerID())) {
218             return false;
219         }
220         loadBalancerDB.putIfAbsent(input.getLoadBalancerID(), input);
221         //TODO: add code to find INeutronLoadBalancerAware services and call newtorkCreated on them
222         return true;
223     }
224
225     @Override
226     public boolean removeNeutronLoadBalancer(String uuid) {
227         if (!neutronLoadBalancerExists(uuid)) {
228             return false;
229         }
230         loadBalancerDB.remove(uuid);
231         //TODO: add code to find INeutronLoadBalancerAware services and call newtorkDeleted on them
232         return true;
233     }
234
235     @Override
236     public boolean updateNeutronLoadBalancer(String uuid, NeutronLoadBalancer delta) {
237         if (!neutronLoadBalancerExists(uuid)) {
238             return false;
239         }
240         NeutronLoadBalancer target = loadBalancerDB.get(uuid);
241         return overwrite(target, delta);
242     }
243
244     @Override
245     public boolean neutronLoadBalancerInUse(String loadBalancerUUID) {
246         return !neutronLoadBalancerExists(loadBalancerUUID);
247     }
248
249     private void loadConfiguration() {
250         for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, FILE_NAME)) {
251             NeutronLoadBalancer nn = (NeutronLoadBalancer) conf;
252             loadBalancerDB.put(nn.getLoadBalancerID(), nn);
253         }
254     }
255
256     @Override
257     public Status saveConfiguration() {
258         return configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(loadBalancerDB.values()),
259                 FILE_NAME);
260     }
261
262     @Override
263     public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
264         return ois.readObject();
265     }
266 }