2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
4 * Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved.
5 * Modifications Copyright 2023-2024 Nordix Foundation.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.models.simulators;
25 import java.io.FileNotFoundException;
26 import java.io.IOException;
27 import java.util.Properties;
28 import java.util.concurrent.atomic.AtomicReference;
29 import lombok.AccessLevel;
31 import org.apache.commons.lang3.StringUtils;
32 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
33 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
34 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
35 import org.onap.policy.common.gson.GsonMessageBodyHandler;
36 import org.onap.policy.common.parameters.BeanValidationResult;
37 import org.onap.policy.common.utils.coder.Coder;
38 import org.onap.policy.common.utils.coder.CoderException;
39 import org.onap.policy.common.utils.coder.StandardCoder;
40 import org.onap.policy.common.utils.network.NetworkUtil;
41 import org.onap.policy.common.utils.resources.ResourceUtils;
42 import org.onap.policy.common.utils.services.Registry;
43 import org.onap.policy.common.utils.services.ServiceManagerContainer;
44 import org.onap.policy.simulators.CdsSimulator;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
49 * This class runs all simulators specified in the parameter file.
51 public class Main extends ServiceManagerContainer {
52 private static final Logger logger = LoggerFactory.getLogger(Main.class);
54 private static final String CANNOT_CONNECT = "cannot connect to port ";
56 @Getter(AccessLevel.PROTECTED)
57 private static Main instance;
61 * Runs the simulators.
63 * @param paramFile parameter file name
65 public Main(String paramFile) {
66 super(Main.class.getPackage().getName());
68 SimulatorParameters params = readParameters(paramFile);
69 String messageBroker = "models-sim";
71 CdsServerParameters cdsServer = params.getGrpcServer();
74 if (cdsServer != null) {
75 AtomicReference<CdsSimulator> cdsSim = new AtomicReference<>();
76 addAction(cdsServer.getName(), () -> cdsSim.set(buildCdsSimulator(cdsServer)), () -> cdsSim.get().stop());
79 // REST server simulators
81 for (ClassRestServerParameters restsim : params.getRestServers()) {
82 AtomicReference<HttpServletServer> ref = new AtomicReference<>();
83 if (StringUtils.isNotBlank(restsim.getResourceLocation())) {
84 String resourceLocationId = restsim.getProviderClass() + "_RESOURCE_LOCATION";
85 addAction(resourceLocationId,
86 () -> Registry.register(resourceLocationId, restsim.getResourceLocation()),
87 () -> Registry.unregister(resourceLocationId));
89 addAction(restsim.getName(),
90 () -> ref.set(buildRestServer(messageBroker, restsim)),
91 () -> ref.get().shutdown());
97 * The main method. The arguments are validated, thus adding the NOSONAR.
99 * @param args the arguments, the first of which is the name of the parameter file
101 public static void main(final String[] args) { // NOSONAR
103 * Only one argument is used and is validated implicitly by the constructor (i.e.,
104 * file-not-found), thus sonar is disabled.
108 if (args.length != 1) {
109 throw new IllegalArgumentException("arg(s): parameter-file-name");
112 instance = new Main(args[0]);
115 } catch (RuntimeException e) {
116 logger.error("failed to start simulators", e);
120 private SimulatorParameters readParameters(String paramFile) {
122 var paramsJson = getResourceAsString(paramFile);
123 if (paramsJson == null) {
124 throw new IllegalArgumentException(new FileNotFoundException(paramFile));
127 String hostName = NetworkUtil.getHostname();
128 logger.info("replacing 'HOST_NAME' with {} in {}", hostName, paramFile);
130 paramsJson = paramsJson.replace("${HOST_NAME}", hostName);
132 return makeCoder().decode(paramsJson, SimulatorParameters.class);
134 } catch (CoderException e) {
135 throw new IllegalArgumentException("cannot decode " + paramFile, e);
139 private CdsSimulator buildCdsSimulator(CdsServerParameters params) throws IOException {
140 var cdsSimulator = new CdsSimulator(params.getHost(), params.getPort(), params.getResourceLocation(),
141 params.getSuccessRepeatCount(), params.getRequestedResponseDelayMs());
142 cdsSimulator.start();
147 private HttpServletServer buildRestServer(String messageBroker, ClassRestServerParameters params) {
149 var props = getServerProperties(messageBroker, params);
150 HttpServletServer testServer = makeServer(props);
151 testServer.waitedStart(5000);
153 String svcpfx = PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + params.getName();
154 String hostName = props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX);
156 if (!isTcpPortOpen(hostName, testServer.getPort())) {
157 throw new IllegalStateException(CANNOT_CONNECT + testServer.getPort());
162 } catch (InterruptedException e) {
163 Thread.currentThread().interrupt();
164 throw new IllegalStateException("interrupted while building " + params.getName(), e);
170 * Creates a set of properties, suitable for building a REST server, from the
173 * @param params parameters from which to build the properties
174 * @return a Map of properties representing the given parameters
176 private static Properties getServerProperties(String messageBroker, ClassRestServerParameters params) {
177 final var props = new Properties();
178 props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, params.getName());
180 final String svcpfx = PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + params.getName();
182 props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, params.getName());
183 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, params.getHost());
184 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
185 Integer.toString(params.getPort()));
186 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX,
187 Boolean.toString(params.isHttps()));
188 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
189 params.getProviderClass());
190 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "false");
191 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SWAGGER_SUFFIX, "false");
192 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SNI_HOST_CHECK_SUFFIX, "false");
193 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
195 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER, String.join(",",
196 GsonMessageBodyHandler.class.getName(), TextMessageBodyHandler.class.getName()));
202 // the following methods may be overridden by junit tests
204 protected String getResourceAsString(String resourceName) {
205 return ResourceUtils.getResourceAsString(resourceName);
208 protected Coder makeCoder() {
209 return new StandardCoder();
212 protected HttpServletServer makeServer(Properties props) {
213 return HttpServletServerFactoryInstance.getServerFactory().build(props).get(0);
216 protected boolean isTcpPortOpen(String hostName, int port) throws InterruptedException {
217 return NetworkUtil.isTcpPortOpen(hostName, port, 100, 200L);