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