2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.apex.context.test.locking;
23 import com.google.gson.Gson;
25 import java.net.InetAddress;
26 import java.net.NetworkInterface;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Collections;
30 import java.util.Enumeration;
31 import java.util.List;
32 import java.util.Map.Entry;
33 import java.util.TreeSet;
34 import java.util.concurrent.ExecutorService;
35 import java.util.concurrent.Future;
36 import java.util.concurrent.TimeUnit;
38 import org.onap.policy.apex.context.ContextAlbum;
39 import org.onap.policy.apex.context.Distributor;
40 import org.onap.policy.apex.context.test.utils.ConfigrationProvider;
41 import org.onap.policy.apex.context.test.utils.ConfigrationProviderImpl;
42 import org.onap.policy.apex.context.test.utils.Constants;
43 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
44 import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException;
45 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
46 import org.onap.policy.apex.model.basicmodel.service.AbstractParameters;
47 import org.onap.policy.apex.model.basicmodel.service.ParameterService;
48 import org.slf4j.ext.XLogger;
49 import org.slf4j.ext.XLoggerFactory;
53 * The Class ConcurrentContextJVM tests concurrent use of context in a single JVM.
55 * @author Liam Fallon (liam.fallon@ericsson.com)
57 public final class ConcurrentContextJVM {
58 // Logger for this class
59 private static final XLogger LOGGER = XLoggerFactory.getXLogger(ConcurrentContextJVM.class);
61 private static final int IPV4_ADDRESS_LENGTH = 4;
63 private final int jvmNo;
65 private final ExecutorService executorService;
67 private final ConfigrationProvider configrationProvider;
69 private ConcurrentContextJVM(final int jvmNo, final ConfigrationProvider configrationProvider) {
71 this.configrationProvider = configrationProvider;
72 final String name = configrationProvider.getTestName() + ":ConcurrentContextThread_" + jvmNo;
73 this.executorService = configrationProvider.getExecutorService(name, configrationProvider.getThreadCount());
77 * This method executes the test of concurrent use of context in a single JVM.
78 * @throws ApexException the Apex exception occurs while running the test
80 public void execute() throws ApexException {
81 LOGGER.debug("starting JVMs and threads . . .");
83 final AxArtifactKey distributorKey = new AxArtifactKey("ApexDistributor" + jvmNo, "0.0.1");
84 final Distributor distributor = configrationProvider.getDistributor(distributorKey);
85 final ContextAlbum contextAlbum = configrationProvider.getContextAlbum(distributor);
86 assert (contextAlbum != null);
88 final List<Future<?>> tasks = new ArrayList<>(configrationProvider.getThreadCount());
90 for (int t = 0; t < configrationProvider.getThreadCount(); t++) {
91 tasks.add(executorService.submit(new ConcurrentContextThread(jvmNo, t, configrationProvider)));
95 executorService.shutdown();
96 // wait for threads to finish, if not Timeout
97 executorService.awaitTermination(10, TimeUnit.MINUTES);
98 } catch (final InterruptedException interruptedException) {
99 LOGGER.error("Exception while waiting for threads to finish", interruptedException);
100 // restore the interrupt status
101 Thread.currentThread().interrupt();
104 LOGGER.debug("threads finished, end value is {}", contextAlbum.get(Constants.TEST_VALUE));
106 LOGGER.info("Shutting down now ... ");
107 executorService.shutdownNow();
115 * @param args the args
116 * @throws Exception Any exception thrown by the test code
118 @SuppressWarnings("unchecked")
119 public static void main(final String[] args) throws Exception {
122 System.out.println("JVM Arguments: " + Arrays.toString(args));
123 // CHECKSTYLE:OFF: checkstyle:magicNumber
125 // An even number of arguments greater than 3
126 if (args.length < 9) {
127 LOGGER.error("invalid arguments: " + Arrays.toString(args));
128 LOGGER.error("usage: TestConcurrentContextJVM testType jvmNo threadCount threadLoops albumSize "
129 + "lockType [parameterKey parameterJson].... ");
134 final String testName = getStringValue("testType", args, 0);
135 final int jvmNo = getIntValue("jvmNo", args, 1);
136 final int threadCount = getIntValue("threadCount", args, 2);
137 final int threadLoops = getIntValue("threadLoops", args, 3);
138 final int albumSize = getIntValue("albumSize", args, 4);
139 final int lockType = getIntValue("lockType", args, 5);
140 final String hazelCastfileLocation = getStringValue("hazelcast file location", args, 6);;
142 System.setProperty("hazelcast.config", hazelCastfileLocation);
144 for (int p = 7; p < args.length - 1; p += 2) {
145 @SuppressWarnings("rawtypes")
146 final Class parametersClass = Class.forName(args[p]);
147 final AbstractParameters parameters =
148 (AbstractParameters) new Gson().fromJson(args[p + 1], parametersClass);
149 ParameterService.registerParameters(parametersClass, parameters);
152 for (final Entry<Class<?>, AbstractParameters> parameterEntry : ParameterService.getAll()) {
153 LOGGER.info("Parameter class " + parameterEntry.getKey().getCanonicalName() + "="
154 + parameterEntry.getValue().toString());
158 final ConfigrationProvider configrationProvider =
159 new ConfigrationProviderImpl(testName, 1, threadCount, threadLoops, albumSize, lockType);
160 final ConcurrentContextJVM concurrentContextJVM = new ConcurrentContextJVM(jvmNo, configrationProvider);
161 concurrentContextJVM.execute();
163 } catch (final Exception e) {
164 LOGGER.error("error running test in JVM", e);
167 // CHECKSTYLE:ON: checkstyle:magicNumber
171 private static String getStringValue(final String key, final String[] args, final int position) {
173 return args[position];
174 } catch (final Exception e) {
175 final String msg = "invalid argument " + key;
176 LOGGER.error(msg, e);
177 throw new ApexRuntimeException(msg, e);
181 private static int getIntValue(final String key, final String[] args, final int position) {
182 final String value = getStringValue(key, args, position);
184 return Integer.parseInt(value);
185 } catch (final Exception e) {
186 final String msg = "Expects number found " + value;
187 LOGGER.error(msg, e);
188 throw new ApexRuntimeException(msg, e);
194 * This method sets up any static configuration required by the JVM.
196 * @throws Exception on configuration errors
198 public static void configure() throws Exception {
199 System.setProperty("java.net.preferIPv4Stack", "true");
200 // The JGroups IP address must be set to a real (not loopback) IP address for Infinispan to
203 // the JVMs in a test pick up the same IP address, this function sets te address to be the
204 // first non-loopback
207 final TreeSet<String> ipAddressSet = new TreeSet<String>();
209 final Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
210 for (final NetworkInterface netint : Collections.list(nets)) {
211 final Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
212 for (final InetAddress inetAddress : Collections.list(inetAddresses)) {
213 // Look for real IPv4 Internet addresses
214 if (!inetAddress.isLoopbackAddress() && inetAddress.getAddress().length == IPV4_ADDRESS_LENGTH) {
215 ipAddressSet.add(inetAddress.getHostAddress());
220 if (ipAddressSet.size() == 0) {
221 throw new Exception("cound not find real IP address for test");
223 System.out.println("Setting jgroups.tcp.address to: " + ipAddressSet.first());
224 System.setProperty("jgroups.tcp.address", ipAddressSet.first());