60750498a2ca5add889db3bd14663768414cf97c
[policy/gui.git] /
1 /*-
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
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.gui.pdp.monitoring.rest;
24
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;
32 import java.util.Map;
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;
43 import lombok.Getter;
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;
55
56 /**
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}
61  *
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.
64  *
65  * @author Yehui Wang (yehui.wang@est.tech)
66  */
67 @Path("monitoring/")
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<>();
75
76     // Set the maximum number of stored data entries to be stored for each engine
77     private static final int MAX_CACHED_ENTITIES = 50;
78
79     private static Gson gson = new Gson();
80
81     /**
82      * Query Pdps.
83      *
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
91      */
92     @GET
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 {
97
98         return Response
99                 .ok(getHttpClient(useHttps, hostname, port, username, password, "policy/pap/v1/pdps").get().getEntity(),
100                         MediaType.APPLICATION_JSON)
101                 .build();
102     }
103
104     /**
105      * Query Pdp statistics.
106      *
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
116      */
117     @GET
118     @Path("statistics/")
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 {
123
124         var pdpGroups = getHttpClient(useHttps, hostname, port, username, password, "policy/pap/v1/pdps").get()
125                 .readEntity(PdpGroups.class);
126         String groupName;
127         String subGroup;
128         String instanceId;
129         String[] idArray = id.split("/");
130         if (idArray.length == 3) {
131             groupName = idArray[0];
132             subGroup = idArray[1];
133             instanceId = idArray[2];
134         } else {
135             throw new IllegalArgumentException("Cannot parse groupName, subGroup and instanceId from " + id);
136         }
137
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();
143
144         final var responseObject = new StatisticsResponse();
145
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());
152
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());
157
158         final List<EngineStatus> engineStatusList = new ArrayList<>();
159
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());
169
170             // Engine Status data
171             for (final PdpEngineWorkerStatistics engineStats : pdpStatistics.getEngineStats()) {
172                 try {
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()),
183                             List.class));
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);
191                 }
192             }
193         } else {
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");
201         }
202
203         responseObject.setStatus(engineStatusList);
204         return Response.ok(new StandardCoder().encode(responseObject), MediaType.APPLICATION_JSON).build();
205     }
206
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);
219     }
220
221     /**
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.
224      *
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
230      */
231     private synchronized List<Counter> getValuesFromCache(final String uri, final String id, final long timestamp,
232             final long latestValue) {
233
234         Map<String, List<Counter>> engineStatus = cache.computeIfAbsent(uri, k -> new HashMap<>());
235
236         List<Counter> valueList = engineStatus.computeIfAbsent(id, k -> new SlidingWindowList<>(MAX_CACHED_ENTITIES));
237
238         valueList.add(new Counter(timestamp, latestValue));
239
240         return valueList;
241     }
242
243     /**
244      * A list of values that uses a FIFO sliding window of a fixed size.
245      */
246     @EqualsAndHashCode(callSuper = true)
247     @AllArgsConstructor
248     public class SlidingWindowList<V> extends LinkedList<V> {
249         private static final long serialVersionUID = -7187277916025957447L;
250
251         private final int maxEntries;
252
253         @Override
254         public boolean add(final V elm) {
255             if (this.size() > (maxEntries - 1)) {
256                 this.removeFirst();
257             }
258             return super.add(elm);
259         }
260     }
261
262     /**
263      * A class used to storing a single data entry for an engine.
264      */
265     @Getter
266     @AllArgsConstructor
267     public class Counter {
268         private final long timestamp;
269         private final long value;
270     }
271
272 }