Bug fixes in models simulators
[policy/models.git] / models-sim / policy-models-simulators / src / main / java / org / onap / policy / models / simulators / Main.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2020 AT&T Intellectual Property. 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.models.simulators;
22
23 import java.io.FileNotFoundException;
24 import java.lang.reflect.InvocationTargetException;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Properties;
29 import java.util.concurrent.atomic.AtomicReference;
30 import lombok.AccessLevel;
31 import lombok.Getter;
32 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
33 import org.onap.policy.common.endpoints.event.comm.TopicSink;
34 import org.onap.policy.common.endpoints.event.comm.TopicSource;
35 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
36 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
37 import org.onap.policy.common.endpoints.parameters.TopicParameters;
38 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
39 import org.onap.policy.common.gson.GsonMessageBodyHandler;
40 import org.onap.policy.common.parameters.BeanValidationResult;
41 import org.onap.policy.common.utils.coder.Coder;
42 import org.onap.policy.common.utils.coder.CoderException;
43 import org.onap.policy.common.utils.coder.StandardCoder;
44 import org.onap.policy.common.utils.network.NetworkUtil;
45 import org.onap.policy.common.utils.resources.ResourceUtils;
46 import org.onap.policy.common.utils.services.ServiceManagerContainer;
47 import org.onap.policy.models.sim.dmaap.parameters.DmaapSimParameterGroup;
48 import org.onap.policy.models.sim.dmaap.provider.DmaapSimProvider;
49 import org.onap.policy.models.sim.dmaap.rest.CambriaMessageBodyHandler;
50 import org.onap.policy.models.sim.dmaap.rest.TextMessageBodyHandler;
51 import org.onap.policy.simulators.TopicServer;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /**
56  * This class runs all simulators specified in the parameter file.
57  */
58 public class Main extends ServiceManagerContainer {
59     private static final Logger logger = LoggerFactory.getLogger(Main.class);
60
61     private static final String CANNOT_CONNECT = "cannot connect to port ";
62
63     @Getter(AccessLevel.PROTECTED)
64     private static Main instance;
65
66
67     /**
68      * Runs the simulators.
69      *
70      * @param paramFile parameter file name
71      */
72     public Main(String paramFile) {
73         super(Main.class.getPackage().getName());
74
75         SimulatorParameters params = readParameters(paramFile);
76         BeanValidationResult result = params.validate("simulators");
77         if (!result.isValid()) {
78             logger.error("invalid parameters:\n{}", result.getResult());
79             throw new IllegalArgumentException("invalid simulator parameters");
80         }
81
82         DmaapSimParameterGroup dmaapProv = params.getDmaapProvider();
83         String dmaapName = dmaapProv.getName();
84         String provName = dmaapName.replace("simulator", "provider");
85
86         // dmaap provider
87         AtomicReference<DmaapSimProvider> provRef = new AtomicReference<>();
88         addAction(provName, () -> provRef.set(buildDmaapProvider(dmaapProv)), () -> provRef.get().shutdown());
89
90         // REST server simulators
91         // @formatter:off
92         for (ClassRestServerParameters restsim : params.getRestServers()) {
93             AtomicReference<HttpServletServer> ref = new AtomicReference<>();
94             addAction(restsim.getName(),
95                 () -> ref.set(buildRestServer(dmaapName, restsim)),
96                 () -> ref.get().shutdown());
97         }
98
99         // NOTE: topics must be started AFTER the (dmaap) rest servers
100
101         // topic sinks
102         Map<String, TopicSink> sinks = new HashMap<>();
103         for (TopicParameters topicParams : params.getTopicSinks()) {
104             String topic = topicParams.getTopic();
105             addAction("Sink " + topic,
106                 () -> sinks.put(topic, startSink(topicParams)),
107                 () -> sinks.get(topic).shutdown());
108         }
109
110         // topic sources
111         Map<String, TopicSource> sources = new HashMap<>();
112         for (TopicParameters topicParams : params.getTopicSources()) {
113             String topic = topicParams.getTopic();
114             addAction("Source " + topic,
115                 () -> sources.put(topic, startSource(topicParams)),
116                 () -> sources.get(topic).shutdown());
117         }
118
119         // topic server simulators
120         for (TopicServerParameters topicsim : params.getTopicServers()) {
121             AtomicReference<TopicServer<?>> ref = new AtomicReference<>();
122             addAction(topicsim.getName(),
123                 () -> ref.set(buildTopicServer(topicsim, sinks, sources)),
124                 () -> ref.get().shutdown());
125         }
126         // @formatter:on
127     }
128
129     /**
130      * The main method.
131      *
132      * @param args the arguments, the first of which is the name of the parameter file
133      */
134     public static void main(final String[] args) {
135         try {
136             if (args.length != 1) {
137                 throw new IllegalArgumentException("arg(s): parameter-file-name");
138             }
139
140             instance = new Main(args[0]);
141             instance.start();
142
143         } catch (RuntimeException e) {
144             logger.error("failed to start simulators", e);
145         }
146     }
147
148     private SimulatorParameters readParameters(String paramFile) {
149         try {
150             String paramsJson = getResourceAsString(paramFile);
151             if (paramsJson == null) {
152                 throw new IllegalArgumentException(new FileNotFoundException(paramFile));
153             }
154
155             String hostName = NetworkUtil.getHostname();
156             logger.info("replacing 'HOST_NAME' with {} in {}", hostName, paramFile);
157
158             paramsJson = paramsJson.replace("${HOST_NAME}", hostName);
159
160             return makeCoder().decode(paramsJson, SimulatorParameters.class);
161
162         } catch (CoderException e) {
163             throw new IllegalArgumentException("cannot decode " + paramFile, e);
164         }
165     }
166
167     private DmaapSimProvider buildDmaapProvider(DmaapSimParameterGroup params) {
168         DmaapSimProvider prov = new DmaapSimProvider(params);
169         DmaapSimProvider.setInstance(prov);
170         prov.start();
171
172         return prov;
173     }
174
175     private TopicSink startSink(TopicParameters params) {
176         TopicSink sink = TopicEndpointManager.getManager().addTopicSinks(List.of(params)).get(0);
177         sink.start();
178         return sink;
179     }
180
181     private TopicSource startSource(TopicParameters params) {
182         TopicSource source = TopicEndpointManager.getManager().addTopicSources(List.of(params)).get(0);
183         source.start();
184         return source;
185     }
186
187     private HttpServletServer buildRestServer(String dmaapName, ClassRestServerParameters params) {
188         try {
189             Properties props = getServerProperties(dmaapName, params);
190             HttpServletServer testServer = makeServer(props);
191             testServer.waitedStart(5000);
192
193             String svcpfx = PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + params.getName();
194             String hostName = props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX);
195
196             if (!isTcpPortOpen(hostName, testServer.getPort())) {
197                 throw new IllegalStateException(CANNOT_CONNECT + testServer.getPort());
198             }
199
200             return testServer;
201
202         } catch (InterruptedException e) {
203             Thread.currentThread().interrupt();
204             throw new IllegalStateException("interrupted while building " + params.getName(), e);
205         }
206     }
207
208     private TopicServer<?> buildTopicServer(TopicServerParameters params, Map<String, TopicSink> sinks,
209                     Map<String, TopicSource> sources) {
210         try {
211             // find the desired sink
212             TopicSink sink = sinks.get(params.getSink());
213             if (sink == null) {
214                 throw new IllegalArgumentException("invalid sink topic " + params.getSink());
215             }
216
217             // find the desired source
218             TopicSource source = sources.get(params.getSource());
219             if (source == null) {
220                 throw new IllegalArgumentException("invalid source topic " + params.getSource());
221             }
222
223             // create the topic server
224             return (TopicServer<?>) Class.forName(params.getProviderClass())
225                             .getDeclaredConstructor(TopicSink.class, TopicSource.class).newInstance(sink, source);
226
227         } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException
228                         | SecurityException | ClassNotFoundException e) {
229             throw new IllegalArgumentException("cannot create TopicServer: " + params.getName(), e);
230         }
231     }
232
233     /**
234      * Creates a set of properties, suitable for building a REST server, from the
235      * parameters.
236      *
237      * @param params parameters from which to build the properties
238      * @return a set of properties representing the given parameters
239      */
240     private static Properties getServerProperties(String dmaapName, ClassRestServerParameters params) {
241         final Properties props = new Properties();
242         props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, params.getName());
243
244         final String svcpfx = PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + params.getName();
245
246         props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, params.getName());
247         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, params.getHost());
248         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
249                         Integer.toString(params.getPort()));
250         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX,
251                         Boolean.toString(params.isHttps()));
252         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
253                         params.getProviderClass());
254         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "false");
255         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SWAGGER_SUFFIX, "false");
256         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
257
258         if (dmaapName.equals(params.getName())) {
259             props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
260                             String.join(",", CambriaMessageBodyHandler.class.getName(),
261                                             GsonMessageBodyHandler.class.getName(),
262                                             TextMessageBodyHandler.class.getName()));
263         } else {
264             props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER, String.join(",",
265                             GsonMessageBodyHandler.class.getName(), TextMessageBodyHandler.class.getName()));
266         }
267
268         return props;
269     }
270
271     // the following methods may be overridden by junit tests
272
273     protected String getResourceAsString(String resourceName) {
274         return ResourceUtils.getResourceAsString(resourceName);
275     }
276
277     protected Coder makeCoder() {
278         return new StandardCoder();
279     }
280
281     protected HttpServletServer makeServer(Properties props) {
282         return HttpServletServerFactoryInstance.getServerFactory().build(props).get(0);
283     }
284
285     protected boolean isTcpPortOpen(String hostName, int port) throws InterruptedException {
286         return NetworkUtil.isTcpPortOpen(hostName, port, 100, 200L);
287     }
288 }