2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2020-2021 Nordix Foundation.
4 * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
5 * Modifications Copyright (C) 2021 Bell Canada. 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
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.gui.pdp.monitoring.rest;
25 import com.google.gson.Gson;
26 import com.google.gson.reflect.TypeToken;
27 import java.util.ArrayList;
28 import java.util.Date;
29 import java.util.HashMap;
30 import java.util.LinkedList;
31 import java.util.List;
33 import java.util.Objects;
34 import javax.ws.rs.Consumes;
35 import javax.ws.rs.GET;
36 import javax.ws.rs.Path;
37 import javax.ws.rs.Produces;
38 import javax.ws.rs.QueryParam;
39 import javax.ws.rs.core.MediaType;
40 import javax.ws.rs.core.Response;
41 import lombok.AllArgsConstructor;
42 import lombok.EqualsAndHashCode;
44 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
45 import org.onap.policy.common.endpoints.http.client.HttpClient;
46 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
47 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
48 import org.onap.policy.common.utils.coder.CoderException;
49 import org.onap.policy.common.utils.coder.StandardCoder;
50 import org.onap.policy.models.pdp.concepts.PdpEngineWorkerStatistics;
51 import org.onap.policy.models.pdp.concepts.PdpGroups;
52 import org.onap.policy.models.pdp.concepts.PdpStatistics;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
57 * The class represents the root resource exposed at the base URL<br>
58 * The url to access this resource would be in the form {@code <baseURL>/rest/....} <br>
59 * For example: a GET request to the following URL
60 * {@code http://localhost:18989/papservices/rest/?hostName=localhost&port=12345}
62 * <b>Note:</b> An allocated {@code hostName} and {@code port} query parameter must be included in
63 * all requests. Datasets for different {@code hostName} are completely isolated from one another.
65 * @author Yehui Wang (yehui.wang@est.tech)
68 @Produces({MediaType.APPLICATION_JSON})
69 @Consumes({MediaType.APPLICATION_JSON})
70 public class PdpMonitoringRestResource {
71 // Get a reference to the logger
72 private static final Logger LOGGER = LoggerFactory.getLogger(PdpMonitoringRestResource.class);
73 // Set up a map separated by host and engine for the data
74 private static final Map<String, HashMap<String, List<Counter>>> cache = new HashMap<>();
76 // Set the maximum number of stored data entries to be stored for each engine
77 private static final int MAX_CACHED_ENTITIES = 50;
79 private static Gson gson = new Gson();
84 * @param useHttps use Http or not
85 * @param hostname hostname the host name of the engine service to connect to.
86 * @param port port the port number of the engine service to connect to.
87 * @param username user name
88 * @param password password
89 * @return a Response object containing Pdps in JSON
90 * @throws HttpClientConfigException exception
93 public Response getPdps(@QueryParam("useHttps") final String useHttps,
94 @QueryParam("hostname") final String hostname, @QueryParam("port") final int port,
95 @QueryParam("username") final String username, @QueryParam("password") final String password)
96 throws HttpClientConfigException {
99 .ok(getHttpClient(useHttps, hostname, port, username, password, "policy/pap/v1/pdps").get().getEntity(),
100 MediaType.APPLICATION_JSON)
105 * Query Pdp statistics.
107 * @param useHttps use Http or not
108 * @param hostname the host name of the engine service to connect to.
109 * @param port the port number of the engine service to connect to.
110 * @param username user name
111 * @param password password
112 * @param id PdpGroupName/PdpSubGroup/PdpIntanceID
113 * @return a Response object containing the Pdp status and context data in JSON
114 * @throws HttpClientConfigException exception
115 * @throws CoderException Coder exception
119 public Response getStatistics(@QueryParam("useHttps") final String useHttps,
120 @QueryParam("hostname") final String hostname, @QueryParam("port") final int port,
121 @QueryParam("username") final String username, @QueryParam("password") final String password,
122 @QueryParam("id") final String id) throws HttpClientConfigException, CoderException {
124 var pdpGroups = getHttpClient(useHttps, hostname, port, username, password, "policy/pap/v1/pdps").get()
125 .readEntity(PdpGroups.class);
129 String[] idArray = id.split("/");
130 if (idArray.length == 3) {
131 groupName = idArray[0];
132 subGroup = idArray[1];
133 instanceId = idArray[2];
135 throw new IllegalArgumentException("Cannot parse groupName, subGroup and instanceId from " + id);
138 var pdp = pdpGroups.getGroups().stream().filter(group -> group.getName().equals(groupName))
139 .flatMap(group -> group.getPdpSubgroups().stream().filter(sub -> sub.getPdpType().equals(subGroup)))
140 .flatMap(sub -> sub.getPdpInstances().stream()
141 .filter(instance -> instance.getInstanceId().equals(instanceId)))
142 .filter(Objects::nonNull).findFirst().orElseThrow();
144 final var responseObject = new StatisticsResponse();
146 // Engine Service data
147 responseObject.setEngineId(pdp.getInstanceId());
148 responseObject.setServer(hostname);
149 responseObject.setPort(Integer.toString(port));
150 responseObject.setHealthStatus(pdp.getHealthy().name());
151 responseObject.setPdpState(pdp.getPdpState().name());
153 String statisticsEntity = getHttpClient(useHttps, hostname, port, username, password,
154 "policy/pap/v1/pdps/statistics/" + id + "?recordCount=1").get().readEntity(String.class);
155 Map<String, Map<String, List<PdpStatistics>>> pdpStats = gson.fromJson(statisticsEntity,
156 new TypeToken<Map<String, Map<String, List<PdpStatistics>>>>() {}.getType());
158 final List<EngineStatus> engineStatusList = new ArrayList<>();
160 if (!pdpStats.isEmpty()) {
161 var pdpStatistics = pdpStats.get(groupName).get(subGroup).get(0);
162 responseObject.setTimeStamp(pdpStatistics.getTimeStamp().toString());
163 responseObject.setPolicyDeployCount(pdpStatistics.getPolicyDeployCount());
164 responseObject.setPolicyDeploySuccessCount(pdpStatistics.getPolicyDeploySuccessCount());
165 responseObject.setPolicyDeployFailCount(pdpStatistics.getPolicyDeployFailCount());
166 responseObject.setPolicyExecutedCount(pdpStatistics.getPolicyExecutedCount());
167 responseObject.setPolicyExecutedSuccessCount(pdpStatistics.getPolicyExecutedSuccessCount());
168 responseObject.setPolicyExecutedFailCount(pdpStatistics.getPolicyExecutedFailCount());
170 // Engine Status data
171 for (final PdpEngineWorkerStatistics engineStats : pdpStatistics.getEngineStats()) {
173 final var engineStatusObject = new EngineStatus();
174 engineStatusObject.setTimestamp(pdpStatistics.getTimeStamp().toString());
175 engineStatusObject.setId(engineStats.getEngineId());
176 engineStatusObject.setStatus(engineStats.getEngineWorkerState().name());
177 engineStatusObject.setLastMessage(new Date(engineStats.getEngineTimeStamp()).toString());
178 engineStatusObject.setUpTime(engineStats.getUpTime());
179 engineStatusObject.setPolicyExecutions(engineStats.getEventCount());
180 engineStatusObject.setLastPolicyDuration(gson.toJson(
181 getValuesFromCache(id, engineStats.getEngineId() + "_last_policy_duration",
182 pdpStatistics.getTimeStamp().getEpochSecond(), engineStats.getLastExecutionTime()),
184 engineStatusObject.setAveragePolicyDuration(
185 gson.toJson(getValuesFromCache(id, engineStats.getEngineId() + "_average_policy_duration",
186 pdpStatistics.getTimeStamp().getEpochSecond(),
187 (long) engineStats.getAverageExecutionTime()), List.class));
188 engineStatusList.add(engineStatusObject);
189 } catch (final RuntimeException e) {
190 LOGGER.warn("Error getting status of engine with ID " + engineStats.getEngineId() + "<br>", e);
194 responseObject.setTimeStamp("N/A");
195 responseObject.setPolicyDeployCount("N/A");
196 responseObject.setPolicyDeploySuccessCount("N/A");
197 responseObject.setPolicyDeployFailCount("N/A");
198 responseObject.setPolicyExecutedCount("N/A");
199 responseObject.setPolicyExecutedSuccessCount("N/A");
200 responseObject.setPolicyExecutedFailCount("N/A");
203 responseObject.setStatus(engineStatusList);
204 return Response.ok(new StandardCoder().encode(responseObject), MediaType.APPLICATION_JSON).build();
207 private HttpClient getHttpClient(String useHttps, String hostname, int port, String username, String password,
208 String basePath) throws HttpClientConfigException {
209 var busParams = new BusTopicParams();
210 busParams.setClientName("pdp-monitoring");
211 busParams.setHostname(hostname);
212 busParams.setManaged(false);
213 busParams.setPassword(password);
214 busParams.setPort(port);
215 busParams.setUseHttps(useHttps.equals("https"));
216 busParams.setUserName(username);
217 busParams.setBasePath(basePath);
218 return HttpClientFactoryInstance.getClientFactory().build(busParams);
222 * This method takes in the latest data entry for an engine, adds it to an existing data set and
223 * returns the full map for that host and engine.
225 * @param uri the pdp uri
226 * @param id the engines id
227 * @param timestamp the timestamp of the latest data entry
228 * @param latestValue the value of the latest data entry
229 * @return a list of {@code Counter} objects for that engine
231 private synchronized List<Counter> getValuesFromCache(final String uri, final String id, final long timestamp,
232 final long latestValue) {
234 Map<String, List<Counter>> engineStatus = cache.computeIfAbsent(uri, k -> new HashMap<>());
236 List<Counter> valueList = engineStatus.computeIfAbsent(id, k -> new SlidingWindowList<>(MAX_CACHED_ENTITIES));
238 valueList.add(new Counter(timestamp, latestValue));
244 * A list of values that uses a FIFO sliding window of a fixed size.
246 @EqualsAndHashCode(callSuper = true)
248 public class SlidingWindowList<V> extends LinkedList<V> {
249 private static final long serialVersionUID = -7187277916025957447L;
251 private final int maxEntries;
254 public boolean add(final V elm) {
255 if (this.size() > (maxEntries - 1)) {
258 return super.add(elm);
263 * A class used to storing a single data entry for an engine.
267 public class Counter {
268 private final long timestamp;
269 private final long value;