Decouple config and netconf subsystems.
[controller.git] / opendaylight / config / config-manager / src / test / java / org / opendaylight / controller / config / manager / impl / AbstractConfigTest.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  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 package org.opendaylight.controller.config.manager.impl;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.mockito.Matchers.any;
12 import static org.mockito.Mockito.doAnswer;
13 import static org.mockito.Mockito.doNothing;
14 import static org.mockito.Mockito.mock;
15
16 import com.google.common.base.Preconditions;
17 import java.io.File;
18 import java.io.IOException;
19 import java.lang.management.ManagementFactory;
20 import java.lang.reflect.InvocationHandler;
21 import java.lang.reflect.InvocationTargetException;
22 import java.lang.reflect.Method;
23 import java.lang.reflect.Proxy;
24 import java.util.Dictionary;
25 import java.util.LinkedList;
26 import java.util.List;
27 import java.util.Set;
28 import javax.management.InstanceAlreadyExistsException;
29 import javax.management.MBeanServer;
30 import javax.management.ObjectName;
31 import javax.management.RuntimeMBeanException;
32 import org.junit.After;
33 import org.junit.Before;
34 import org.mockito.Matchers;
35 import org.mockito.Mock;
36 import org.mockito.MockitoAnnotations;
37 import org.mockito.invocation.InvocationOnMock;
38 import org.mockito.stubbing.Answer;
39 import org.opendaylight.controller.config.api.jmx.CommitStatus;
40 import org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver;
41 import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
42 import org.opendaylight.controller.config.manager.impl.jmx.ConfigRegistryJMXRegistrator;
43 import org.opendaylight.controller.config.manager.impl.jmx.InternalJMXRegistrator;
44 import org.opendaylight.controller.config.manager.impl.jmx.JMXNotifierConfigRegistry;
45 import org.opendaylight.controller.config.manager.impl.osgi.mapping.BindingContextProvider;
46 import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolImpl;
47 import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPool;
48 import org.opendaylight.controller.config.spi.Module;
49 import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
50 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
51 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
52 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
53 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
54 import org.osgi.framework.BundleContext;
55 import org.osgi.framework.ServiceRegistration;
56
57 /**
58  * Each test that relies on
59  * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl}
60  * needs to subclass this test.
61  * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl} is
62  * registered to platform MBean Server using
63  * {@link #initConfigTransactionManagerImpl(org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver)}
64  * typically during setting up the each test.
65  */
66 public abstract class AbstractConfigTest extends
67         AbstractLockedPlatformMBeanServerTest {
68     protected ConfigRegistryJMXRegistrator configRegistryJMXRegistrator;
69     protected ConfigRegistryImpl configRegistry;
70     private JMXNotifierConfigRegistry notifyingConfigRegistry;
71     protected ConfigRegistryJMXClient configRegistryClient;
72     protected BaseJMXRegistrator baseJmxRegistrator;
73     protected InternalJMXRegistrator internalJmxRegistrator;
74     @Mock
75     protected BundleContext mockedContext;
76     @Mock
77     protected ServiceRegistration<?> mockedServiceRegistration;
78
79     @Before
80     public void setUpMocks() {
81         MockitoAnnotations.initMocks(this);
82     }
83
84
85     // Default handler for OSGi service registration
86     protected static class RecordingBundleContextServiceRegistrationHandler implements BundleContextServiceRegistrationHandler {
87         private final List<RegistrationHolder> registrations = new LinkedList<>();
88         @Override
89         public void handleServiceRegistration(Class<?> clazz, Object serviceInstance, Dictionary<String, ?> props) {
90
91             registrations.add(new RegistrationHolder(clazz, serviceInstance, props));
92         }
93
94         public List<RegistrationHolder> getRegistrations() {
95             return registrations;
96         }
97
98         protected static class RegistrationHolder {
99             protected final Class<?> clazz;
100             protected final Object instance;
101             protected final Dictionary<String, ?> props;
102
103             public RegistrationHolder(Class<?> clazz, Object instance, Dictionary<String, ?> props) {
104                 this.clazz = clazz;
105                 this.instance = instance;
106                 this.props = props;
107             }
108         }
109
110     }
111
112     protected BundleContextServiceRegistrationHandler currentBundleContextServiceRegistrationHandler;
113
114     protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(Class<?> serviceType) {
115         return currentBundleContextServiceRegistrationHandler;
116     }
117
118     // this method should be called in @Before
119     protected void initConfigTransactionManagerImpl(
120             ModuleFactoriesResolver resolver) {
121
122         final MBeanServer platformMBeanServer = ManagementFactory
123                 .getPlatformMBeanServer();
124
125         configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(platformMBeanServer);
126         initBundleContext();
127
128         internalJmxRegistrator = new InternalJMXRegistrator(platformMBeanServer);
129         baseJmxRegistrator = new BaseJMXRegistrator(internalJmxRegistrator);
130
131         configRegistry = new ConfigRegistryImpl(resolver, platformMBeanServer, baseJmxRegistrator, new BindingContextProvider() {
132             @Override
133             public synchronized void update(final ClassLoadingStrategy classLoadingStrategy, final SchemaContextProvider ctxProvider) {
134                 // NOOP
135             }
136
137             @Override
138             public synchronized BindingRuntimeContext getBindingContext() {
139                 return getBindingRuntimeContext();
140             }
141         });
142         notifyingConfigRegistry = new JMXNotifierConfigRegistry(this.configRegistry, platformMBeanServer);
143
144         try {
145             configRegistryJMXRegistrator.registerToJMXNoNotifications(configRegistry);
146             configRegistryJMXRegistrator.registerToJMX(notifyingConfigRegistry);
147         } catch (InstanceAlreadyExistsException e) {
148             throw new RuntimeException(e);
149         }
150         configRegistryClient = new ConfigRegistryJMXClient(platformMBeanServer);
151         currentBundleContextServiceRegistrationHandler = new RecordingBundleContextServiceRegistrationHandler();
152     }
153
154     private void initBundleContext() {
155         doNothing().when(mockedServiceRegistration).unregister();
156         RegisterServiceAnswer answer = new RegisterServiceAnswer();
157         doAnswer(answer).when(mockedContext).registerService(Matchers.<String>any(), any(), Matchers.<Dictionary<String, ?>>any());
158         doAnswer(answer).when(mockedContext).registerService(Matchers.<Class>any(), any(), Matchers.<Dictionary<String, ?>>any());
159     }
160
161     @After
162     public final void cleanUpConfigTransactionManagerImpl() {
163         configRegistryJMXRegistrator.close();
164         notifyingConfigRegistry.close();
165         configRegistry.close();
166         TestingFixedThreadPool.cleanUp();
167         TestingScheduledThreadPoolImpl.cleanUp();
168     }
169
170     /**
171      * Can be called in @After of tests if some other cleanup is needed that
172      * would be discarded by closing config beans in this method
173      */
174     protected void destroyAllConfigBeans() throws Exception {
175         ConfigTransactionJMXClient transaction = configRegistryClient
176                 .createTransaction();
177         Set<ObjectName> all = transaction.lookupConfigBeans();
178         // workaround for getting same Module more times
179         while (all.size() > 0) {
180             transaction.destroyModule(all.iterator().next());
181             all = transaction.lookupConfigBeans();
182         }
183         transaction.commit();
184     }
185
186     protected void assertStatus(CommitStatus status, int expectedNewInstances,
187             int expectedRecreatedInstances, int expectedReusedInstances) {
188         assertEquals("New instances mismatch in " + status, expectedNewInstances, status.getNewInstances().size());
189         assertEquals("Recreated instances mismatch in " + status, expectedRecreatedInstances, status.getRecreatedInstances()
190                 .size());
191         assertEquals("Reused instances mismatch in " + status, expectedReusedInstances, status.getReusedInstances()
192                 .size());
193     }
194
195
196     protected void assertBeanCount(int i, String configMXBeanName) {
197         assertEquals(i, configRegistry.lookupConfigBeans(configMXBeanName)
198                 .size());
199     }
200
201     /**
202      *
203      * @param configBeanClass
204      *            Empty constructor class of config bean to be instantiated
205      *            whenever create
206      * @param implementationName
207      * @return
208      */
209     protected ClassBasedModuleFactory createClassBasedCBF(
210             Class<? extends Module> configBeanClass, String implementationName) {
211         return new ClassBasedModuleFactory(implementationName, configBeanClass);
212     }
213
214     protected BindingRuntimeContext getBindingRuntimeContext() {
215         return mock(BindingRuntimeContext.class);
216     }
217
218     public static interface BundleContextServiceRegistrationHandler {
219
220         void handleServiceRegistration(Class<?> clazz, Object serviceInstance, Dictionary<String, ?> props);
221
222     }
223
224     private class RegisterServiceAnswer implements Answer<ServiceRegistration<?>> {
225
226         @Override
227         public ServiceRegistration<?> answer(InvocationOnMock invocation) throws Throwable {
228             Object[] args = invocation.getArguments();
229
230             Preconditions.checkArgument(args.length == 3, "Unexpected arguments size (expected 3 was %s)", args.length);
231
232             Object serviceTypeRaw = args[0];
233             Object serviceInstance = args[1];
234             Dictionary<String, ?> props = (Dictionary<String, ?>) args[2];
235
236             if (serviceTypeRaw instanceof Class) {
237                 Class<?> serviceType = (Class<?>) serviceTypeRaw;
238                 invokeServiceHandler(serviceInstance, serviceType, props);
239
240             } else if(serviceTypeRaw instanceof String[]) {
241                 for (String className : (String[]) serviceTypeRaw) {
242                     invokeServiceHandler(serviceInstance, className, props);
243                 }
244             } else if (serviceTypeRaw instanceof String) {
245                 invokeServiceHandler(serviceInstance, (String) serviceTypeRaw, props);
246             } else {
247                 throw new IllegalStateException("Not handling service registration of type, Unknown type" +  serviceTypeRaw);
248             }
249
250
251             return mockedServiceRegistration;
252         }
253
254         public void invokeServiceHandler(Object serviceInstance, String className, Dictionary<String, ?> props) {
255             try {
256                 Class<?> serviceType = Class.forName(className);
257                 invokeServiceHandler(serviceInstance, serviceType, props);
258             } catch (ClassNotFoundException e) {
259                 throw new IllegalStateException("Not handling service registration of type " +  className, e);
260             }
261         }
262
263         private void invokeServiceHandler(Object serviceInstance, Class<?> serviceType, Dictionary<String, ?> props) {
264             BundleContextServiceRegistrationHandler serviceRegistrationHandler = getBundleContextServiceRegistrationHandler(serviceType);
265
266             if (serviceRegistrationHandler != null) {
267                 serviceRegistrationHandler.handleServiceRegistration(serviceType, serviceInstance, props);
268             }
269         }
270     }
271
272     /**
273      * Expand inner exception wrapped by JMX
274      *
275      * @param innerObject jmx proxy which will be wrapped and returned
276      */
277     protected <T> T rethrowCause(final T innerObject) {
278
279         Object proxy = Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
280                 innerObject.getClass().getInterfaces(), new InvocationHandler() {
281                         @Override
282                         public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
283                             try {
284                                 return method.invoke(innerObject, args);
285                             } catch (InvocationTargetException e) {
286                                 try {
287                                     throw e.getTargetException();
288                                 } catch (RuntimeMBeanException e2) {
289                                     throw e2.getTargetException();
290                                 }
291                             }
292                         }
293                     }
294         );
295         return (T) proxy;
296     }
297
298     /**
299      * removes contents of the directory
300      * @param dir to be cleaned
301      * @throws IOException
302      */
303     protected void cleanDirectory(File dir) throws IOException {
304         if (!dir.isDirectory()) {
305             throw new IllegalStateException("dir must be a directory");
306         }
307
308         final File[] files = dir.listFiles();
309         if (files == null) {
310             throw new IOException("Failed to list contents of " + dir);
311         }
312
313         for (File file : files) {
314             if (file.isDirectory()) {
315                 cleanDirectory(dir);
316             }
317             file.delete();
318         }
319     }
320
321 }