a673824ea6ca58635e7a45510ee2e23ef23e349b
[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      * 
65      * @return the verified context
66      * @throws ApexModelException the exception occurs in model handling
67      * @throws ApexException the Apex exception occurs in handling Apex
68      */
69     public Map<String, TestContextLongItem> testConcurrentContext() throws ApexException {
70
71         try {
72             setupAndVerifyContext();
73         } catch (final Exception exception) {
74             LOGGER.error("Error occured while setting up and verifying concurrent context", exception);
75             throw exception;
76         }
77
78         LOGGER.debug("starting JVMs and threads . . .");
79
80         final ExecutorService executorService = configrationProvider.getExecutorService();
81
82         final List<Closeable> tasks = new ArrayList<>(configrationProvider.getThreadCount());
83
84         addShutDownHook(tasks);
85
86         // Check if we have a single JVM or multiple JVMs
87         if (configrationProvider.getJvmCount() == 1) {
88             // Run everything in this JVM
89             for (int t = 0; t < configrationProvider.getThreadCount(); t++) {
90                 final ConcurrentContextThread task = new ConcurrentContextThread(0, t, configrationProvider);
91                 tasks.add(task);
92                 executorService.execute(task);
93             }
94
95         } else {
96             // Spawn JVMs to run the tests
97             for (int j = 0; j < configrationProvider.getJvmCount(); j++) {
98                 final ConcurrentContextJvmThread task = new ConcurrentContextJvmThread(j, configrationProvider);
99                 tasks.add(task);
100                 executorService.execute(task);
101             }
102         }
103
104         try {
105             executorService.shutdown();
106             // wait for threads to finish, if not Timeout
107             executorService.awaitTermination(10, TimeUnit.MINUTES);
108         } catch (final InterruptedException interruptedException) {
109             LOGGER.error("Exception while waiting for threads to finish", interruptedException);
110             // restore the interrupt status
111             Thread.currentThread().interrupt();
112         }
113
114         LOGGER.info("Shutting down now ...");
115         executorService.shutdownNow();
116
117         return verifyAndClearContext();
118     }
119
120
121     private void addShutDownHook(final List<Closeable> tasks) {
122         Runtime.getRuntime().addShutdownHook(new Thread() {
123             @Override
124             public void run() {
125                 LOGGER.info("Shutting down ...");
126                 for (final Closeable task : tasks) {
127                     try {
128                         task.close();
129                     } catch (final IOException ioException) {
130                         LOGGER.error("Unable to close task ... ", ioException);
131                     }
132                 }
133             }
134         });
135     }
136
137     /**
138      * Setup and verify context.
139      *
140      * @throws ContextException the context exception
141      */
142     private void setupAndVerifyContext() {
143         contextDistributor = configrationProvider.getDistributor();
144         ltypeAlbum = configrationProvider.getContextAlbum(contextDistributor);
145         final Map<String, Object> initValues = configrationProvider.getContextAlbumInitValues();
146
147         for (final Entry<String, Object> entry : initValues.entrySet()) {
148             ltypeAlbum.put(entry.getKey(), entry.getValue());
149         }
150     }
151
152     private Map<String, TestContextLongItem> verifyAndClearContext() throws ContextException {
153         final Map<String, TestContextLongItem> values = new HashMap<>();
154         try {
155
156             for (final Entry<String, Object> entry : ltypeAlbum.entrySet()) {
157                 values.put(entry.getKey(), (TestContextLongItem) entry.getValue());
158             }
159         } catch (final Exception exception) {
160             LOGGER.error("Error: ", exception);
161         }
162         contextDistributor.clear();
163         contextDistributor = null;
164
165         return values;
166     }
167 }