37798636479c05ffd5953a465e824b729ceae046
[controller.git] / opendaylight / networkconfiguration / neutron / implementation / src / main / java / org / opendaylight / controller / networkconfig / neutron / implementation / NeutronLoadBalancerListenerInterface.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.INeutronLoadBalancerListenerCRUD;
20 import org.opendaylight.controller.networkconfig.neutron.NeutronLoadBalancerListener;
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 NeutronLoadBalancerListenerInterface implements INeutronLoadBalancerListenerCRUD, IConfigurationContainerAware,
40         IObjectReader {
41     private static final Logger logger = LoggerFactory.getLogger(NeutronLoadBalancerListenerInterface.class);
42     private static final String FILE_NAME = "neutron.loadBalancerListener.conf";
43     private String containerName = null;
44
45     private IClusterContainerServices clusterContainerService = null;
46     private IConfigurationContainerService configurationService;
47     private ConcurrentMap<String, NeutronLoadBalancerListener> loadBalancerListenerDB;
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 LoadBalancerListener");
78         try {
79             // neutron caches
80             this.clusterContainerService.createCache("neutronLoadBalancerListeners",
81                     EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
82         } catch (CacheConfigException cce) {
83             logger.error("Cache couldn't be created for Neutron LoadBalancerListener -  check cache mode");
84         } catch (CacheExistException cce) {
85             logger.error("Cache for Neutron LoadBalancerListener already exists, destroy and recreate");
86         }
87         logger.debug("Cache successfully created for Neutron LoadBalancerListener");
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 LoadBalancerListener");
98         loadBalancerListenerDB = (ConcurrentMap<String, NeutronLoadBalancerListener>) clusterContainerService
99                 .getCache("neutronLoadBalancerListeners");
100         if (loadBalancerListenerDB == null) {
101             logger.error("Cache couldn't be retrieved for Neutron LoadBalancerListener");
102         }
103         logger.debug("Cache was successfully retrieved for Neutron LoadBalancerListener");
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 LoadBalancerListener");
112         clusterContainerService.destroyCache("neutronLoadBalancerListeners");
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 neutronLoadBalancerListenerExists(String uuid) {
190         return loadBalancerListenerDB.containsKey(uuid);
191     }
192
193     @Override
194     public NeutronLoadBalancerListener getNeutronLoadBalancerListener(String uuid) {
195         if (!neutronLoadBalancerListenerExists(uuid)) {
196             logger.debug("No LoadBalancerListener Have Been Defined");
197             return null;
198         }
199         return loadBalancerListenerDB.get(uuid);
200     }
201
202     @Override
203     public List<NeutronLoadBalancerListener> getAllNeutronLoadBalancerListeners() {
204         Set<NeutronLoadBalancerListener> allLoadBalancerListeners = new HashSet<NeutronLoadBalancerListener>();
205         for (Entry<String, NeutronLoadBalancerListener> entry : loadBalancerListenerDB.entrySet()) {
206             NeutronLoadBalancerListener loadBalancerListener = entry.getValue();
207             allLoadBalancerListeners.add(loadBalancerListener);
208         }
209         logger.debug("Exiting getLoadBalancerListeners, Found {} OpenStackLoadBalancerListener", allLoadBalancerListeners.size());
210         List<NeutronLoadBalancerListener> ans = new ArrayList<NeutronLoadBalancerListener>();
211         ans.addAll(allLoadBalancerListeners);
212         return ans;
213     }
214
215     @Override
216     public boolean addNeutronLoadBalancerListener(NeutronLoadBalancerListener input) {
217         if (neutronLoadBalancerListenerExists(input.getLoadBalancerListenerID())) {
218             return false;
219         }
220         loadBalancerListenerDB.putIfAbsent(input.getLoadBalancerListenerID(), input);
221         //TODO: add code to find INeutronLoadBalancerListenerAware services and call newtorkCreated on them
222         return true;
223     }
224
225     @Override
226     public boolean removeNeutronLoadBalancerListener(String uuid) {
227         if (!neutronLoadBalancerListenerExists(uuid)) {
228             return false;
229         }
230         loadBalancerListenerDB.remove(uuid);
231         //TODO: add code to find INeutronLoadBalancerListenerAware services and call newtorkDeleted on them
232         return true;
233     }
234
235     @Override
236     public boolean updateNeutronLoadBalancerListener(String uuid, NeutronLoadBalancerListener delta) {
237         if (!neutronLoadBalancerListenerExists(uuid)) {
238             return false;
239         }
240         NeutronLoadBalancerListener target = loadBalancerListenerDB.get(uuid);
241         return overwrite(target, delta);
242     }
243
244     @Override
245     public boolean neutronLoadBalancerListenerInUse(String loadBalancerListenerUUID) {
246         return !neutronLoadBalancerListenerExists(loadBalancerListenerUUID);
247     }
248
249     private void loadConfiguration() {
250         for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, FILE_NAME)) {
251             NeutronLoadBalancerListener nn = (NeutronLoadBalancerListener) conf;
252             loadBalancerListenerDB.put(nn.getLoadBalancerListenerID(), nn);
253         }
254     }
255
256     @Override
257     public Status saveConfiguration() {
258         return configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(loadBalancerListenerDB.values()),
259                 FILE_NAME);
260     }
261
262     @Override
263     public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
264         return ois.readObject();
265     }
266 }