Merge "Add shutdown hook."
[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 com.google.common.base.Preconditions;
11 import junit.framework.Assert;
12 import org.junit.After;
13 import org.mockito.Matchers;
14 import org.mockito.invocation.InvocationOnMock;
15 import org.mockito.stubbing.Answer;
16 import org.opendaylight.controller.config.api.jmx.CommitStatus;
17 import org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver;
18 import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
19 import org.opendaylight.controller.config.manager.impl.jmx.ConfigRegistryJMXRegistrator;
20 import org.opendaylight.controller.config.manager.impl.jmx.InternalJMXRegistrator;
21 import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolImpl;
22 import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPool;
23 import org.opendaylight.controller.config.spi.Module;
24 import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
25 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
26 import org.osgi.framework.BundleContext;
27 import org.osgi.framework.ServiceRegistration;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 import javax.management.InstanceAlreadyExistsException;
32 import javax.management.MBeanServer;
33 import javax.management.ObjectName;
34 import javax.management.RuntimeMBeanException;
35 import java.io.Closeable;
36 import java.io.InputStream;
37 import java.lang.management.ManagementFactory;
38 import java.util.ArrayList;
39 import java.util.Collection;
40 import java.util.Collections;
41 import java.lang.reflect.InvocationHandler;
42 import java.lang.reflect.InvocationTargetException;
43 import java.lang.reflect.Method;
44 import java.lang.reflect.Proxy;
45 import java.util.Dictionary;
46 import java.util.List;
47 import java.util.Set;
48
49 import static org.junit.Assert.assertEquals;
50 import static org.mockito.Matchers.any;
51 import static org.mockito.Mockito.doAnswer;
52 import static org.mockito.Mockito.doNothing;
53 import static org.mockito.Mockito.mock;
54
55 /**
56  * Each test that relies on
57  * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl}
58  * needs to subclass this test.
59  * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl} is
60  * registered to platform MBean Server using
61  * {@link #initConfigTransactionManagerImpl(org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver)}
62  * typically during setting up the each test.
63  */
64 public abstract class AbstractConfigTest extends
65         AbstractLockedPlatformMBeanServerTest {
66     protected ConfigRegistryJMXRegistrator configRegistryJMXRegistrator;
67     protected ConfigRegistryImpl configRegistry;
68     protected ConfigRegistryJMXClient configRegistryClient;
69     protected BaseJMXRegistrator baseJmxRegistrator;
70     protected InternalJMXRegistrator internalJmxRegistrator;
71     protected BundleContext mockedContext = mock(BundleContext.class);
72     protected ServiceRegistration<?> mockedServiceRegistration;
73
74     private static final Logger logger = LoggerFactory.getLogger(AbstractConfigTest.class);
75
76     // Default handler for OSGi service registration
77     private static final BundleContextServiceRegistrationHandler noopServiceRegHandler = new BundleContextServiceRegistrationHandler() {
78         @Override
79         public void handleServiceRegistration(Object serviceInstance) {}
80     };
81
82     protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(Class<?> serviceType) {
83         return noopServiceRegHandler;
84     }
85
86     // this method should be called in @Before
87     protected void initConfigTransactionManagerImpl(
88             ModuleFactoriesResolver resolver) {
89         final MBeanServer platformMBeanServer = ManagementFactory
90                 .getPlatformMBeanServer();
91
92         configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(
93                 platformMBeanServer);
94         initBundleContext();
95
96         internalJmxRegistrator = new InternalJMXRegistrator(platformMBeanServer);
97         baseJmxRegistrator = new BaseJMXRegistrator(internalJmxRegistrator);
98
99         configRegistry = new ConfigRegistryImpl(resolver,
100                 platformMBeanServer, baseJmxRegistrator);
101
102         try {
103             configRegistryJMXRegistrator.registerToJMX(configRegistry);
104         } catch (InstanceAlreadyExistsException e) {
105             throw new RuntimeException(e);
106         }
107         configRegistryClient = new ConfigRegistryJMXClient(platformMBeanServer);
108     }
109
110     private void initBundleContext() {
111         this.mockedServiceRegistration = mock(ServiceRegistration.class);
112         doNothing().when(mockedServiceRegistration).unregister();
113
114         RegisterServiceAnswer answer = new RegisterServiceAnswer();
115
116         doAnswer(answer).when(mockedContext).registerService(Matchers.any(String[].class),
117                 any(Closeable.class), Matchers.<Dictionary<String, ?>>any());
118         doAnswer(answer).when(mockedContext).registerService(Matchers.<Class<Closeable>>any(), any(Closeable.class),
119                 Matchers.<Dictionary<String, ?>>any());
120     }
121
122
123     public Collection<InputStream> getFilesAsInputStreams(List<String> paths) {
124         final Collection<InputStream> resources = new ArrayList<>();
125         List<String> failedToFind = new ArrayList<>();
126         for (String path : paths) {
127             InputStream resourceAsStream = getClass().getResourceAsStream(path);
128             if (resourceAsStream == null) {
129                 failedToFind.add(path);
130             } else {
131                 resources.add(resourceAsStream);
132             }
133         }
134         Assert.assertEquals("Some files were not found", Collections.<String>emptyList(), failedToFind);
135
136         return resources;
137     }
138
139     @After
140     public final void cleanUpConfigTransactionManagerImpl() {
141         configRegistryJMXRegistrator.close();
142         configRegistry.close();
143         TestingFixedThreadPool.cleanUp();
144         TestingScheduledThreadPoolImpl.cleanUp();
145     }
146
147     /**
148      * Can be called in @After of tests if some other cleanup is needed that
149      * would be discarded by closing config beans in this method
150      */
151     protected void destroyAllConfigBeans() throws Exception {
152         ConfigTransactionJMXClient transaction = configRegistryClient
153                 .createTransaction();
154         Set<ObjectName> all = transaction.lookupConfigBeans();
155         // workaround for getting same Module more times
156         while (all.size() > 0) {
157             transaction.destroyModule(all.iterator().next());
158             all = transaction.lookupConfigBeans();
159         }
160         transaction.commit();
161     }
162
163     protected void assertSame(ObjectName oN1, ObjectName oN2) {
164         assertEquals(oN1.getKeyProperty("instanceName"),
165                 oN2.getKeyProperty("instanceName"));
166         assertEquals(oN1.getKeyProperty("interfaceName"),
167                 oN2.getKeyProperty("interfaceName"));
168     }
169
170     protected void assertStatus(CommitStatus status, int expectedNewInstances,
171             int expectedRecreatedInstances, int expectedReusedInstances) {
172         assertEquals("New instances mismatch in " + status, expectedNewInstances, status.getNewInstances().size());
173         assertEquals("Recreated instances mismatch in " + status, expectedRecreatedInstances, status.getRecreatedInstances()
174                 .size());
175         assertEquals("Reused instances mismatch in " + status, expectedReusedInstances, status.getReusedInstances()
176                 .size());
177     }
178
179     protected ObjectName createTestConfigBean(
180             ConfigTransactionJMXClient transaction, String implementationName,
181             String name) throws InstanceAlreadyExistsException {
182         return transaction.createModule(implementationName,
183                 name);
184     }
185
186     protected void assertBeanCount(int i, String configMXBeanName) {
187         assertEquals(i, configRegistry.lookupConfigBeans(configMXBeanName)
188                 .size());
189     }
190
191     protected void assertBeanExists(int count, String moduleName,
192             String instanceName) {
193         assertEquals(1,
194                 configRegistry.lookupConfigBeans(moduleName, instanceName)
195                         .size());
196     }
197
198     /**
199      *
200      * @param configBeanClass
201      *            Empty constructor class of config bean to be instantiated
202      *            whenever create
203      * @param implementationName
204      * @return
205      */
206     protected ClassBasedModuleFactory createClassBasedCBF(
207             Class<? extends Module> configBeanClass, String implementationName) {
208         return new ClassBasedModuleFactory(implementationName, configBeanClass);
209     }
210
211
212     public static interface BundleContextServiceRegistrationHandler {
213
214        void handleServiceRegistration(Object serviceInstance);
215
216     }
217
218     private class RegisterServiceAnswer implements Answer {
219
220         @Override
221         public Object answer(InvocationOnMock invocation) throws Throwable {
222             Object[] args = invocation.getArguments();
223
224             Preconditions.checkArgument(args.length == 3, "Unexpected arguments size (expected 3 was %s)", args.length);
225
226             Object serviceTypeRaw = args[0];
227             Object serviceInstance = args[1];
228
229             if (serviceTypeRaw instanceof Class) {
230                 Class<?> serviceType = (Class<?>) serviceTypeRaw;
231                 invokeServiceHandler(serviceInstance, serviceType);
232
233             } else if(serviceTypeRaw instanceof String[]) {
234                 for (String className : (String[]) serviceTypeRaw) {
235                     try {
236                         Class<?> serviceType = Class.forName(className);
237                         invokeServiceHandler(serviceInstance, serviceType);
238                     } catch (ClassNotFoundException e) {
239                         logger.warn("Not handling service registration of type {} ", className, e);
240                     }
241                 }
242
243             } else
244                 logger.debug("Not handling service registration of type {}, Unknown type", serviceTypeRaw);
245
246             return mockedServiceRegistration;
247         }
248
249         private void invokeServiceHandler(Object serviceInstance, Class<?> serviceType) {
250             BundleContextServiceRegistrationHandler serviceRegistrationHandler = getBundleContextServiceRegistrationHandler(serviceType);
251
252             if (serviceRegistrationHandler != null) {
253                 serviceRegistrationHandler.handleServiceRegistration(serviceType.cast(serviceInstance));
254             }
255         }
256     }
257
258     /**
259      * Expand inner exception wrapped by JMX
260      *
261      * @param innerObject jmx proxy which will be wrapped and returned
262      */
263     protected <T> T rethrowCause(final T innerObject) {
264
265         Object proxy = Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
266                 innerObject.getClass().getInterfaces(), new InvocationHandler() {
267             @Override
268             public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
269                 try {
270                     return method.invoke(innerObject, args);
271                 } catch (InvocationTargetException e) {
272                     try {
273                         throw e.getTargetException();
274                     } catch (RuntimeMBeanException e2) {
275                         throw e2.getTargetException();
276                     }
277                 }
278             }
279         });
280         return (T) proxy;
281     }
282
283 }