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