c7043bc530d6ae3b8e207fde625d6c013c2c52d3
[policy/apex-pdp.git] /
1 /*-
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
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.context.test.locking;
22
23 import com.google.gson.Gson;
24
25 import java.net.InetAddress;
26 import java.net.NetworkInterface;
27 import java.net.SocketException;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Collections;
31 import java.util.Enumeration;
32 import java.util.List;
33 import java.util.Map.Entry;
34 import java.util.TreeSet;
35 import java.util.concurrent.ExecutorService;
36 import java.util.concurrent.Future;
37 import java.util.concurrent.TimeUnit;
38
39 import org.onap.policy.apex.context.ContextAlbum;
40 import org.onap.policy.apex.context.Distributor;
41 import org.onap.policy.apex.context.test.utils.ConfigrationProvider;
42 import org.onap.policy.apex.context.test.utils.ConfigrationProviderImpl;
43 import org.onap.policy.apex.context.test.utils.Constants;
44 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
45 import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException;
46 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
47 import org.onap.policy.common.parameters.ParameterGroup;
48 import org.onap.policy.common.parameters.ParameterService;
49 import org.slf4j.ext.XLogger;
50 import org.slf4j.ext.XLoggerFactory;
51
52
53 /**
54  * The Class ConcurrentContextJVM tests concurrent use of context in a single JVM.
55  *
56  * @author Liam Fallon (liam.fallon@ericsson.com)
57  */
58 public final class ConcurrentContextJvm {
59     // Logger for this class
60     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ConcurrentContextJvm.class);
61
62     private static final int IPV4_ADDRESS_LENGTH = 4;
63
64     private final int jvmNo;
65
66     private final ExecutorService executorService;
67
68     private final ConfigrationProvider configrationProvider;
69
70     private ConcurrentContextJvm(final int jvmNo, final ConfigrationProvider configrationProvider) {
71         this.jvmNo = jvmNo;
72         this.configrationProvider = configrationProvider;
73         final String name = configrationProvider.getTestName() + ":ConcurrentContextThread_" + jvmNo;
74         this.executorService = configrationProvider.getExecutorService(name, configrationProvider.getThreadCount());
75     }
76
77     /**
78      * This method executes the test of concurrent use of context in a single JVM.
79      * 
80      * @throws ApexException the Apex exception occurs while running the test
81      */
82     public void execute() throws ApexException {
83         LOGGER.debug("starting JVMs and threads . . .");
84
85         final AxArtifactKey distributorKey = new AxArtifactKey("ApexDistributor" + jvmNo, "0.0.1");
86         final Distributor distributor = configrationProvider.getDistributor(distributorKey);
87         final ContextAlbum contextAlbum = configrationProvider.getContextAlbum(distributor);
88         assert (contextAlbum != null);
89
90         final List<Future<?>> tasks = new ArrayList<>(configrationProvider.getThreadCount());
91
92         for (int t = 0; t < configrationProvider.getThreadCount(); t++) {
93             tasks.add(executorService.submit(new ConcurrentContextThread(jvmNo, t, configrationProvider)));
94         }
95
96         try {
97             executorService.shutdown();
98             // wait for threads to finish, if not Timeout
99             executorService.awaitTermination(10, TimeUnit.MINUTES);
100         } catch (final InterruptedException interruptedException) {
101             LOGGER.error("Exception while waiting for threads to finish", interruptedException);
102             // restore the interrupt status
103             Thread.currentThread().interrupt();
104         }
105
106         LOGGER.debug("threads finished, end value is {}", contextAlbum.get(Constants.TEST_VALUE));
107         distributor.clear();
108         LOGGER.info("Shutting down now ... ");
109         executorService.shutdownNow();
110     }
111
112
113
114     /**
115      * The main method.
116      *
117      * @param args the args
118      * @throws Exception Any exception thrown by the test code
119      */
120     @SuppressWarnings("unchecked")
121     public static void main(final String[] args) throws Exception {
122         configure();
123
124         LOGGER.info("JVM Arguments: " + Arrays.toString(args));
125         // CHECKSTYLE:OFF: checkstyle:magicNumber
126
127         // An even number of arguments greater than 3
128         if (args.length < 9) {
129             LOGGER.error("invalid arguments: " + Arrays.toString(args));
130             LOGGER.error("usage: TestConcurrentContextJVM testType jvmNo threadCount threadLoops albumSize "
131                     + "lockType [parameterKey parameterJson].... ");
132             return;
133         }
134
135
136         final String testName = getStringValue("testType", args, 0);
137         final int jvmNo = getIntValue("jvmNo", args, 1);
138         final int threadCount = getIntValue("threadCount", args, 2);
139         final int threadLoops = getIntValue("threadLoops", args, 3);
140         final int albumSize = getIntValue("albumSize", args, 4);
141         final int lockType = getIntValue("lockType", args, 5);
142         final String hazelCastfileLocation = getStringValue("hazelcast file location", args, 6);
143
144         System.setProperty("hazelcast.config", hazelCastfileLocation);
145
146         for (int p = 7; p < args.length - 1; p += 2) {
147             @SuppressWarnings("rawtypes")
148             final Class parametersClass = Class.forName(args[p]);
149             final ParameterGroup parameters = (ParameterGroup) new Gson().fromJson(args[p + 1], parametersClass);
150             ParameterService.register(parameters);
151         }
152
153         for (final Entry<String, ParameterGroup> parameterEntry : ParameterService.getAll()) {
154             LOGGER.info("Parameter class " + parameterEntry.getKey() + "=" + parameterEntry.getValue().toString());
155         }
156
157         try {
158             final ConfigrationProvider configrationProvider =
159                     new ConfigrationProviderImpl(testName, 1, threadCount, threadLoops, albumSize, lockType);
160             final ConcurrentContextJvm concurrentContextJvm = new ConcurrentContextJvm(jvmNo, configrationProvider);
161             concurrentContextJvm.execute();
162
163         } catch (final Exception e) {
164             LOGGER.error("error running test in JVM", e);
165         }
166         // CHECKSTYLE:ON: checkstyle:magicNumber
167     }
168
169     private static String getStringValue(final String key, final String[] args, final int position) {
170         try {
171             return args[position];
172         } catch (final Exception e) {
173             final String msg = "invalid argument " + key;
174             LOGGER.error(msg, e);
175             throw new ApexRuntimeException(msg, e);
176         }
177     }
178
179     private static int getIntValue(final String key, final String[] args, final int position) {
180         final String value = getStringValue(key, args, position);
181         try {
182             return Integer.parseInt(value);
183         } catch (final Exception e) {
184             final String msg = "Expects number found " + value;
185             LOGGER.error(msg, e);
186             throw new ApexRuntimeException(msg, e);
187         }
188     }
189
190
191     /**
192      * This method sets up any static configuration required by the JVM.
193      *
194      * @throws ApexException on configuration errors
195      */
196     public static void configure() throws ApexException {
197         System.setProperty("java.net.preferIPv4Stack", "true");
198         // The JGroups IP address must be set to a real (not loopback) IP address for Infinispan to
199         // work. IN order to
200         // ensure that all
201         // the JVMs in a test pick up the same IP address, this function sets te address to be the
202         // first non-loopback
203         // IPv4 address
204         // on a host
205         final TreeSet<String> ipAddressSet = new TreeSet<>();
206
207         Enumeration<NetworkInterface> nets;
208         try {
209             nets = NetworkInterface.getNetworkInterfaces();
210         } catch (final SocketException e) {
211             throw new ApexException("cound not get network interfaces for test", e);
212         }
213
214         for (final NetworkInterface netint : Collections.list(nets)) {
215             final Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
216             for (final InetAddress inetAddress : Collections.list(inetAddresses)) {
217                 // Look for real IPv4 Internet addresses
218                 if (!inetAddress.isLoopbackAddress() && inetAddress.getAddress().length == IPV4_ADDRESS_LENGTH) {
219                     ipAddressSet.add(inetAddress.getHostAddress());
220                 }
221             }
222         }
223
224         if (ipAddressSet.isEmpty()) {
225             throw new ApexException("cound not find real IP address for test");
226         }
227         LOGGER.info("Setting jgroups.tcp.address to: " + ipAddressSet.first());
228         System.setProperty("jgroups.tcp.address", ipAddressSet.first());
229     }
230 }