3f6cad8e7831d7dd37ed413acad4e1bb49010d19
[policy/apex-pdp.git] / testsuites / performance / performance-benchmark-test / src / main / java / org / onap / policy / apex / testsuites / performance / benchmark / eventgenerator / EventGenerator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2020 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.testsuites.performance.benchmark.eventgenerator;
23
24 import java.io.IOException;
25 import java.net.URI;
26 import java.nio.file.InvalidPathException;
27 import java.util.Arrays;
28
29 import org.apache.commons.cli.ParseException;
30 import org.glassfish.grizzly.http.server.HttpServer;
31 import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
32 import org.glassfish.jersey.server.ResourceConfig;
33 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
34 import org.onap.policy.common.utils.resources.TextFileUtils;
35 import org.slf4j.ext.XLogger;
36 import org.slf4j.ext.XLoggerFactory;
37
38 /**
39  * This class is the main class of a REST server that generates sample events.
40  */
41 public class EventGenerator {
42     // Get a reference to the logger
43     private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventGenerator.class);
44
45     // Parameters for event generation
46     private final EventGeneratorParameters parameters;
47
48     // The HTTP server we are running
49     private final HttpServer eventGeneratorServer;
50
51     /**
52      * Instantiates a new event generator with the given parameters.
53      *
54      * @param parameters the parameters for the event generator
55      */
56     public EventGenerator(final EventGeneratorParameters parameters) {
57         this.parameters = parameters;
58
59         // Set the parameters in the event generator endpoint
60         EventGeneratorEndpoint.clearEventGenerationStats();
61         EventGeneratorEndpoint.setParameters(parameters);
62
63         // Add a shutdown hook to shut down the rest services when the process is exiting
64         Runtime.getRuntime().addShutdownHook(new Thread(new EventGeneratorShutdownHook()));
65
66         LOGGER.info("Event generator REST server starting");
67
68         final ResourceConfig rc = new ResourceConfig(EventGeneratorEndpoint.class);
69         eventGeneratorServer = GrizzlyHttpServerFactory.createHttpServer(getBaseUri(), rc);
70
71         // Wait for the HTTP server to come up
72         while (!eventGeneratorServer.isStarted()) {
73             ThreadUtilities.sleep(50);
74         }
75
76         LOGGER.info("Event generator REST server started");
77     }
78
79     /**
80      * Get the current event generation statistics.
81      *
82      * @return the statistics as a JSON string
83      */
84     public String getEventGenerationStats() {
85         return EventGeneratorEndpoint.getEventGenerationStats();
86     }
87
88     /**
89      * Check if event generation is finished.
90      *
91      * @return true if event generation is finished
92      */
93     public boolean isFinished() {
94         return EventGeneratorEndpoint.isFinished();
95     }
96
97     /**
98      * Tear down the event generator.
99      */
100     public void tearDown() {
101         LOGGER.info("Event generator shutting down");
102
103         eventGeneratorServer.shutdown();
104
105         if (parameters.getOutFile() != null) {
106             try {
107                 TextFileUtils.putStringAsTextFile(getEventGenerationStats(), parameters.getOutFile());
108             } catch (IOException | InvalidPathException ioe) {
109                 LOGGER.warn("could not output statistics to file \"" + parameters.getOutFile() + "\"", ioe);
110             }
111         }
112
113         LOGGER.info("Event generator shut down");
114     }
115
116     /**
117      * Get the base URI for the server.
118      *
119      * @return the base URI
120      */
121     private URI getBaseUri() {
122         String baseUri = "http://" + parameters.getHost() + ':' + parameters.getPort() + '/' + "/EventGenerator";
123         return URI.create(baseUri);
124     }
125
126     /**
127      * This class is a shutdown hook for the Apex editor command.
128      */
129     private class EventGeneratorShutdownHook implements Runnable {
130         /**
131          * {@inheritDoc}.
132          */
133         @Override
134         public void run() {
135             tearDown();
136         }
137     }
138
139     /**
140      * The main method.
141      *
142      * @param args the arguments
143      * @throws Exception the exception
144      */
145     public static void main(final String[] args) {
146         LOGGER.info("Starting event generator with arguments: " + Arrays.toString(args));
147
148         EventGeneratorParameterHandler parameterHandler = new EventGeneratorParameterHandler();
149
150         EventGeneratorParameters parameters = null;
151
152         try {
153             parameters = parameterHandler.parse(args);
154         } catch (ParseException pe) {
155             LOGGER.trace("Event generator start exception", pe);
156             LOGGER.info("Start of event generator failed: {}", pe.getMessage());
157             return;
158         }
159
160         // Null parameters means we print help
161         if (parameters == null) {
162             LOGGER.info(parameterHandler.getHelp(EventGenerator.class.getName()));
163             return;
164         }
165
166         // Start the event generator
167         EventGenerator eventGenerator = new EventGenerator(parameters);
168         LOGGER.info("Event generator started");
169
170         // Wait for event generation to finish
171         while (!eventGenerator.isFinished()) {
172             ThreadUtilities.sleep(200);
173         }
174
175         // Shut down the server
176         eventGenerator.tearDown();
177
178         LOGGER.info("Event generator statistics\n" + eventGenerator.getEventGenerationStats());
179
180         LOGGER.info("Event generator finished");
181     }
182 }