7d7548569497a3666ef65d5e447c4f2bbe2fe737
[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.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;
37
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.common.parameters.ParameterGroup;
47 import org.onap.policy.common.parameters.ParameterService;
48 import org.slf4j.ext.XLogger;
49 import org.slf4j.ext.XLoggerFactory;
50
51
52 /**
53  * The Class ConcurrentContextJVM tests concurrent use of context in a single JVM.
54  *
55  * @author Liam Fallon (liam.fallon@ericsson.com)
56  */
57 public final class ConcurrentContextJvm {
58     // Logger for this class
59     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ConcurrentContextJvm.class);
60
61     private static final int IPV4_ADDRESS_LENGTH = 4;
62
63     private final int jvmNo;
64
65     private final ExecutorService executorService;
66
67     private final ConfigrationProvider configrationProvider;
68
69     private ConcurrentContextJvm(final int jvmNo, final ConfigrationProvider configrationProvider) {
70         this.jvmNo = jvmNo;
71         this.configrationProvider = configrationProvider;
72         final String name = configrationProvider.getTestName() + ":ConcurrentContextThread_" + jvmNo;
73         this.executorService = configrationProvider.getExecutorService(name, configrationProvider.getThreadCount());
74     }
75
76     /**
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
79      */
80     public void execute() throws ApexException {
81         LOGGER.debug("starting JVMs and threads . . .");
82
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);
87
88         final List<Future<?>> tasks = new ArrayList<>(configrationProvider.getThreadCount());
89
90         for (int t = 0; t < configrationProvider.getThreadCount(); t++) {
91             tasks.add(executorService.submit(new ConcurrentContextThread(jvmNo, t, configrationProvider)));
92         }
93
94         try {
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();
102         }
103
104         LOGGER.debug("threads finished, end value is {}", contextAlbum.get(Constants.TEST_VALUE));
105         distributor.clear();
106         LOGGER.info("Shutting down now ... ");
107         executorService.shutdownNow();
108     }
109
110
111
112     /**
113      * The main method.
114      *
115      * @param args the args
116      * @throws Exception Any exception thrown by the test code
117      */
118     @SuppressWarnings("unchecked")
119     public static void main(final String[] args) throws Exception {
120         configure();
121
122         System.out.println("JVM Arguments: " + Arrays.toString(args));
123         // CHECKSTYLE:OFF: checkstyle:magicNumber
124
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].... ");
130             return;
131         }
132
133
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);;
141
142         System.setProperty("hazelcast.config", hazelCastfileLocation);
143
144         for (int p = 7; p < args.length - 1; p += 2) {
145             @SuppressWarnings("rawtypes")
146             final Class parametersClass = Class.forName(args[p]);
147             final ParameterGroup parameters =
148                     (ParameterGroup) new Gson().fromJson(args[p + 1], parametersClass);
149             ParameterService.register(parameters);
150         }
151
152         for (final Entry<String, ParameterGroup> parameterEntry : ParameterService.getAll()) {
153             LOGGER.info("Parameter class " + parameterEntry.getKey() + "="
154                     + 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             return;
166         }
167         // CHECKSTYLE:ON: checkstyle:magicNumber
168
169     }
170
171     private static String getStringValue(final String key, final String[] args, final int position) {
172         try {
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);
178         }
179     }
180
181     private static int getIntValue(final String key, final String[] args, final int position) {
182         final String value = getStringValue(key, args, position);
183         try {
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);
189         }
190     }
191
192
193     /**
194      * This method sets up any static configuration required by the JVM.
195      *
196      * @throws Exception on configuration errors
197      */
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
201         // work. IN order to
202         // ensure that all
203         // the JVMs in a test pick up the same IP address, this function sets te address to be the
204         // first non-loopback
205         // IPv4 address
206         // on a host
207         final TreeSet<String> ipAddressSet = new TreeSet<String>();
208
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());
216                 }
217             }
218         }
219
220         if (ipAddressSet.size() == 0) {
221             throw new Exception("cound not find real IP address for test");
222         }
223         System.out.println("Setting jgroups.tcp.address to: " + ipAddressSet.first());
224         System.setProperty("jgroups.tcp.address", ipAddressSet.first());
225     }
226 }