88cdccc88fcde6b62a9fe9ab8c981c27cb074f44
[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 java.io.Closeable;
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.TimeUnit;
32
33 import org.onap.policy.apex.context.ContextAlbum;
34 import org.onap.policy.apex.context.ContextException;
35 import org.onap.policy.apex.context.Distributor;
36 import org.onap.policy.apex.context.test.concepts.TestContextLongItem;
37 import org.onap.policy.apex.context.test.utils.ConfigrationProvider;
38 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
39 import org.onap.policy.apex.model.basicmodel.handling.ApexModelException;
40 import org.slf4j.ext.XLogger;
41 import org.slf4j.ext.XLoggerFactory;
42
43 /**
44  * The Class TestConcurrentContext tests concurrent use of context.
45  *
46  * @author Liam Fallon (liam.fallon@ericsson.com)
47  */
48 public class ConcurrentContext {
49     // Logger for this class
50     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ConcurrentContext.class);
51
52     // The context distributor and map used by each test
53     private Distributor contextDistributor = null;
54     private ContextAlbum ltypeAlbum = null;
55
56     private final ConfigrationProvider configrationProvider;
57
58     public ConcurrentContext(final ConfigrationProvider configrationProvider) {
59         this.configrationProvider = configrationProvider;
60     }
61
62     /**
63      * The method tests concurrent use of context.
64      * @return the verified context
65      * @throws ApexModelException the exception occurs in model handling
66      * @throws IOException the IO exception occurs in handling IO
67      * @throws ApexException the Apex exception occurs in handling Apex
68      */
69     public Map<String, TestContextLongItem> testConcurrentContext()
70             throws ApexModelException, IOException, ApexException {
71
72         try {
73             setupAndVerifyContext();
74         } catch (final Exception exception) {
75             LOGGER.error("Error occured while setting up and verifying concurrent context", exception);
76             throw exception;
77         }
78
79         LOGGER.debug("starting JVMs and threads . . .");
80
81         final ExecutorService executorService = configrationProvider.getExecutorService();
82
83         final List<Closeable> tasks = new ArrayList<>(configrationProvider.getThreadCount());
84
85         addShutDownHook(tasks);
86
87         // Check if we have a single JVM or multiple JVMs
88         if (configrationProvider.getJvmCount() == 1) {
89             // Run everything in this JVM
90             for (int t = 0; t < configrationProvider.getThreadCount(); t++) {
91                 final ConcurrentContextThread task = new ConcurrentContextThread(0, t, configrationProvider);
92                 tasks.add(task);
93                 executorService.execute(task);
94             }
95
96         } else {
97             // Spawn JVMs to run the tests
98             for (int j = 0; j < configrationProvider.getJvmCount(); j++) {
99                 final ConcurrentContextJvmThread task = new ConcurrentContextJvmThread(j, configrationProvider);
100                 tasks.add(task);
101                 executorService.execute(task);
102             }
103         }
104
105         try {
106             executorService.shutdown();
107             // wait for threads to finish, if not Timeout
108             executorService.awaitTermination(10, TimeUnit.MINUTES);
109         } catch (final InterruptedException interruptedException) {
110             LOGGER.error("Exception while waiting for threads to finish", interruptedException);
111             // restore the interrupt status
112             Thread.currentThread().interrupt();
113         }
114
115         LOGGER.info("Shutting down now ...");
116         executorService.shutdownNow();
117
118         return verifyAndClearContext();
119     }
120
121
122     private void addShutDownHook(final List<Closeable> tasks) {
123         Runtime.getRuntime().addShutdownHook(new Thread() {
124             @Override
125             public void run() {
126                 LOGGER.info("Shutting down ...");
127                 for (final Closeable task : tasks) {
128                     try {
129                         task.close();
130                     } catch (final IOException ioException) {
131                         LOGGER.error("Unable to close task ... ", ioException);
132                     }
133                 }
134             }
135         });
136     }
137
138     /**
139      * Setup and verify context.
140      *
141      * @throws ContextException the context exception
142      */
143     private void setupAndVerifyContext() throws ContextException {
144         contextDistributor = configrationProvider.getDistributor();
145         ltypeAlbum = configrationProvider.getContextAlbum(contextDistributor);
146         final Map<String, Object> initValues = configrationProvider.getContextAlbumInitValues();
147
148         for (final Entry<String, Object> entry : initValues.entrySet()) {
149             ltypeAlbum.put(entry.getKey(), entry.getValue());
150         }
151     }
152
153     private Map<String, TestContextLongItem> verifyAndClearContext() throws ContextException {
154         final Map<String, TestContextLongItem> values = new HashMap<>();
155         try {
156
157             for (Entry<String, Object> entry : ltypeAlbum.entrySet()) {
158                 values.put(entry.getKey(), (TestContextLongItem) entry.getValue());
159             }
160         } catch (final Exception exception) {
161             LOGGER.error("Error: ", exception);
162         }
163         contextDistributor.clear();
164         contextDistributor = null;
165
166         return values;
167     }
168 }