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