6cbee6935a1be0e7ef3b5d83777c95cf580f9846
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2020 Nordix Foundation.
5  *  Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.apex.testsuites.performance.benchmark.eventgenerator;
24
25 import com.google.gson.Gson;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.atomic.AtomicReference;
28 import javax.inject.Inject;
29 import javax.inject.Provider;
30 import javax.ws.rs.GET;
31 import javax.ws.rs.POST;
32 import javax.ws.rs.Path;
33 import javax.ws.rs.core.Response;
34 import lombok.AccessLevel;
35 import lombok.Getter;
36 import lombok.Setter;
37 import org.glassfish.grizzly.http.server.Request;
38 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
39 import org.onap.policy.apex.testsuites.performance.benchmark.eventgenerator.events.OutputEvent;
40 import org.slf4j.ext.XLogger;
41 import org.slf4j.ext.XLoggerFactory;
42
43 /**
44  * This class is the REST end point for event simulator REST calls.
45  */
46 @Path("/")
47 public class EventGeneratorEndpoint {
48
49     // Get a reference to the logger
50     private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventGeneratorEndpoint.class);
51
52     // Parameters for event generation
53     private static AtomicReference<EventGeneratorParameters> parameters = new AtomicReference<>(
54         new EventGeneratorParameters());
55
56     // The map of event batches sent in the test
57     private static ConcurrentHashMap<Integer, EventBatch> batchMap = new ConcurrentHashMap<>();
58
59     // Flag indicating that event processing has finished
60     @Getter(AccessLevel.PROTECTED)
61     @Setter(AccessLevel.PROTECTED)
62     private static boolean finished = false;
63
64     // The current HTTP request
65     private final Provider<Request> httpRequest;
66
67     /**
68      * Inject the HTTP request with a constructor.
69      *
70      * @param httpRequest the current request
71      */
72     @Inject
73     public EventGeneratorEndpoint(final Provider<Request> httpRequest) {
74         this.httpRequest = httpRequest;
75     }
76
77     /**
78      * Set the parameters for the end point.
79      *
80      * @param incomingParameters the new parameters
81      */
82     public static void setParameters(EventGeneratorParameters incomingParameters) {
83         parameters.set(incomingParameters);
84     }
85
86     /**
87      * Get event generator statistics.
88      *
89      * @return the response
90      */
91     @Path("/Stats")
92     @GET
93     public Response serviceGetStats() {
94         return Response.status(200).entity(new EventGeneratorStats(batchMap).getStatsAsJsonString()).build();
95     }
96
97     /**
98      * Generate a single event.
99      *
100      * @return the event
101      */
102     @Path("/GetEvents")
103     @GET
104     public Response getEvents() {
105         ThreadUtilities.sleep(parameters.get().getDelayBetweenBatches());
106
107         // Check if event generation is finished
108         if (isFinished()) {
109             return Response.status(204).build();
110         }
111
112         // A batch count of 0 means to continue to handle events for ever
113         if (parameters.get().getBatchCount() > 0 && batchMap.size() >= parameters.get().getBatchCount()) {
114             setFinished(true);
115             return Response.status(204).build();
116         }
117
118         EventBatch batch = new EventBatch(parameters.get().getBatchSize(), getApexClient());
119         batchMap.put(batch.getBatchNumber(), batch);
120
121         return Response.status(200).entity(batch.getBatchAsJsonString()).build();
122     }
123
124     /**
125      * Get a single response to an event.
126      *
127      * @param jsonString the json string
128      * @return the response
129      */
130     @Path("/PostEvent")
131     @POST
132     public Response postEventResponse(final String jsonString) {
133         final OutputEvent outputEvent = new Gson().fromJson(jsonString, OutputEvent.class);
134
135         EventBatch batch = batchMap.get(outputEvent.findBatchNumber());
136
137         if (batch == null) {
138             String errorMessage = "no input event found for received output event " + outputEvent;
139             LOGGER.warn(errorMessage);
140             return Response.status(409).build();
141         }
142
143         batch.handleResponse(outputEvent);
144         return Response.status(200).build();
145     }
146
147     /**
148      * Get the name, address, and port of the Apex client getting the events.
149      *
150      * @return the Apex client
151      */
152     private String getApexClient() {
153         return httpRequest.get().getRemoteHost() + '(' + httpRequest.get().getRemoteAddr() + "):" + httpRequest.get()
154             .getRemotePort();
155     }
156
157     /**
158      * Get event generation statistics.
159      *
160      * @return the statistics on event generation
161      */
162     protected static String getEventGenerationStats() {
163         return new EventGeneratorStats(batchMap).getStatsAsJsonString();
164     }
165
166     /**
167      * Clear event generation statistics.
168      */
169     protected static void clearEventGenerationStats() {
170         batchMap.clear();
171     }
172 }