aboutsummaryrefslogtreecommitdiffstats
path: root/client/client-monitoring/src/main/java/org/onap/policy/apex/client/monitoring/rest/ApexMonitoringRestResource.java
blob: f31f47cd43aac3215e4384879e4c937322eb5905 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
 *  Modifications Copyright (C) 2020 Nordix Foundation.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.apex.client.monitoring.rest;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.onap.policy.apex.core.deployment.ApexDeploymentException;
import org.onap.policy.apex.core.deployment.EngineServiceFacade;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
import org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;

/**
 * The class represents the root resource exposed at the base URL<br> The url to access this resource would be in the
 * form {@code <baseURL>/rest/....} <br> For example: a GET request to the following URL
 * {@code http://localhost:18989/apexservices/rest/?hostName=localhost&port=12345}
 *
 * <b>Note:</b> An allocated {@code hostName} and {@code port} query parameter must be included in all requests.
 * Datasets for different {@code hostName} are completely isolated from one another.
 *
 */
@Path("monitoring/")
@Produces(
    { MediaType.APPLICATION_JSON })
@Consumes(
    { MediaType.APPLICATION_JSON })

public class ApexMonitoringRestResource {
    // Get a reference to the logger
    private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexMonitoringRestResource.class);

    // Recurring string constants
    private static final String ERROR_CONNECTING_PREFIX = "Error connecting to Apex Engine Service at ";

    // Set the maximum number of stored data entries to be stored for each engine
    private static final int MAX_CACHED_ENTITIES = 50;

    // Set up a map separated by host and engine for the data
    private static final HashMap<String, HashMap<String, List<Counter>>> cache = new HashMap<>();

    // Set up a map separated by host for storing the state of periodic events
    private static final HashMap<String, Boolean> periodicEventsStateCache = new HashMap<>();

    /**
     * Query the engine service for data.
     *
     * @param hostName the host name of the engine service to connect to.
     * @param port the port number of the engine service to connect to.
     * @return a Response object containing the engines service, status and context data in JSON
     */
    @GET
    public Response createSession(@QueryParam("hostName") final String hostName, @QueryParam("port") final int port) {
        final Gson gson = new Gson();
        final String host = hostName + ":" + port;
        final EngineServiceFacade engineServiceFacade = getEngineServiceFacade(hostName, port);

        try {
            engineServiceFacade.init();
        } catch (final ApexDeploymentException e) {
            final String errorMessage = ERROR_CONNECTING_PREFIX + host;
            LOGGER.warn(errorMessage + "<br>", e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage + "\n" + e.getMessage())
                            .build();
        }

        final JsonObject responseObject = new JsonObject();

        // Engine Service data
        responseObject.addProperty("engine_id", engineServiceFacade.getKey().getId());
        responseObject.addProperty("model_id",
                        engineServiceFacade.getApexModelKey() != null ? engineServiceFacade.getApexModelKey().getId()
                                        : "Not Set");
        responseObject.addProperty("server", hostName);
        responseObject.addProperty("port", Integer.toString(port));
        responseObject.addProperty("periodic_events", getPeriodicEventsState(host));

        // Engine Status data
        final JsonArray engineStatusList = new JsonArray();

        for (final AxArtifactKey engineKey : engineServiceFacade.getEngineKeyArray()) {
            try {
                final JsonObject engineStatusObject = new JsonObject();
                final AxEngineModel axEngineModel = engineServiceFacade.getEngineStatus(engineKey);
                engineStatusObject.addProperty("timestamp", axEngineModel.getTimeStampString());
                engineStatusObject.addProperty("id", engineKey.getId());
                engineStatusObject.addProperty("status", axEngineModel.getState().toString());
                engineStatusObject.addProperty("last_message", axEngineModel.getStats().getTimeStampString());
                engineStatusObject.addProperty("up_time", axEngineModel.getStats().getUpTime() / 1000L);
                engineStatusObject.addProperty("policy_executions", axEngineModel.getStats().getEventCount());
                engineStatusObject.addProperty("last_policy_duration",
                                gson.toJson(getValuesFromCache(host, engineKey.getId() + "_last_policy_duration",
                                                axEngineModel.getTimestamp(),
                                                axEngineModel.getStats().getLastExecutionTime()), List.class));
                engineStatusObject
                                .addProperty("average_policy_duration", gson.toJson(
                                                getValuesFromCache(host, engineKey.getId() + "_average_policy_duration",
                                                                axEngineModel.getTimestamp(),
                                                                (long) axEngineModel.getStats()
                                                                                .getAverageExecutionTime()),
                                                List.class));
                engineStatusList.add(engineStatusObject);
            } catch (final ApexException e) {
                LOGGER.warn("Error getting status of engine with ID " + engineKey.getId() + "<br>", e);
            }
        }
        responseObject.add("status", engineStatusList);

        // Engine context data
        final JsonArray engineContextList = new JsonArray();
        for (final AxArtifactKey engineKey : engineServiceFacade.getEngineKeyArray()) {
            try {
                final String engineInfo = engineServiceFacade.getEngineInfo(engineKey);
                if (engineInfo != null && !engineInfo.trim().isEmpty()) {
                    final JsonObject engineContextObject = new JsonObject();
                    engineContextObject.addProperty("id", engineKey.getId());
                    engineContextObject.addProperty("engine_info", engineInfo);
                    engineContextList.add(engineContextObject);
                }
            } catch (final ApexException e) {
                LOGGER.warn("Error getting runtime information of engine with ID " + engineKey.getId() + "<br>", e);
            }
        }
        responseObject.add("context", engineContextList);

        return Response.ok(responseObject.toString(), MediaType.APPLICATION_JSON).build();
    }

    /**
     * Start/Stop and Apex engine.
     *
     * @param hostName the host name of the engine service to connect to.
     * @param port the port number of the engine service to connect to.
     * @param engineId the id of the engine to be started/stopped.
     * @param startStop the parameter to start/stop the engine. Expects either "Start" or "Stop"
     * @return a Response object of type 200
     */
    @GET
    @Path("startstop/")
    public Response startStop(@QueryParam("hostName") final String hostName, @QueryParam("port") final int port,
                    @QueryParam("engineId") final String engineId, @QueryParam("startstop") final String startStop) {
        final EngineServiceFacade engineServiceFacade = getEngineServiceFacade(hostName, port);

        try {
            engineServiceFacade.init();
        } catch (final ApexDeploymentException e) {
            final String errorMessage = ERROR_CONNECTING_PREFIX + hostName + ":" + port;
            LOGGER.warn(errorMessage + "<br>", e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage + "\n" + e.getMessage())
                            .build();
        }

        try {
            final Map<String, String[]> parameterMap = new HashMap<>();
            parameterMap.put("hostname", new String[]
                { hostName });
            parameterMap.put("port", new String[]
                { Integer.toString(port) });
            parameterMap.put("AxArtifactKey#" + engineId, new String[]
                { startStop });
            final AxArtifactKey engineKey = ParameterCheck.getEngineKey(parameterMap);
            if ("Start".equals(startStop)) {
                engineServiceFacade.startEngine(engineKey);
            } else if ("Stop".equals(startStop)) {
                engineServiceFacade.stopEngine(engineKey);
            }
        } catch (final Exception e) {
            final String errorMessage = "Error calling " + startStop + " on Apex Engine: " + engineId;
            LOGGER.warn(errorMessage + "<br>", e);
            final StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage + "\n" + sw.toString())
                            .build();
        }

        return Response.ok("{}").build();
    }

    /**
     * Start/Stop Apex engine Periodic Events.
     *
     * @param hostName the host name of the engine service to connect to.
     * @param port the port number of the engine service to connect to.
     * @param engineId the id of the engine to be started/stopped.
     * @param startStop the parameter to start/stop the engine. Expects either "Start" or "Stop"
     * @param period the time between each event in milliseconds
     * @return a Response object of type 200
     */
    @GET
    @Path("periodiceventstartstop/")
    public Response periodiceventStartStop(@QueryParam("hostName") final String hostName,
                    @QueryParam("port") final int port, @QueryParam("engineId") final String engineId,
                    @QueryParam("startstop") final String startStop, @QueryParam("period") final long period) {
        final EngineServiceFacade engineServiceFacade = getEngineServiceFacade(hostName, port);
        final String host = hostName + ":" + port;
        try {
            engineServiceFacade.init();
            final Map<String, String[]> parameterMap = new HashMap<>();
            parameterMap.put("hostname", new String[]
                { hostName });
            parameterMap.put("port", new String[]
                { Integer.toString(port) });
            parameterMap.put("AxArtifactKey#" + engineId, new String[]
                { startStop });
            parameterMap.put("period", new String[]
                { Long.toString(period) });
            final AxArtifactKey engineKey = ParameterCheck.getEngineKey(parameterMap);
            if ("Start".equals(startStop)) {
                engineServiceFacade.startPerioidicEvents(engineKey, period);
                setPeriodicEventsState(host, true);
            } else if ("Stop".equals(startStop)) {
                engineServiceFacade.stopPerioidicEvents(engineKey);
                setPeriodicEventsState(host, false);
            }
        } catch (final ApexDeploymentException e) {
            final String errorMessage = ERROR_CONNECTING_PREFIX + host;
            LOGGER.warn(errorMessage + "<br>", e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage + "\n" + e.getMessage())
                            .build();
        }

        return Response.ok("{}").build();
    }

    /**
     * Check if periodic events are running.
     *
     * @param host the engine's host url
     * @return a boolean stating if periodic events are running for a given host
     */
    private Boolean getPeriodicEventsState(final String host) {
        if (periodicEventsStateCache.containsKey(host)) {
            return periodicEventsStateCache.get(host);
        } else {
            return false;
        }
    }

    /**
     * Sets the state of periodic events for a host.
     *
     * @param host the engine's host url
     * @param boolean that states if periodic events have been started or stopped
     */
    private void setPeriodicEventsState(final String host, final Boolean isRunning) {
        periodicEventsStateCache.put(host, isRunning);
    }

    /**
     * This method takes in the latest data entry for an engine, adds it to an existing data set and returns the full
     * map for that host and engine.
     *
     * @param host the engine's host url
     * @param id the engines id
     * @param timestamp the timestamp of the latest data entry
     * @param latestValue the value of the latest data entry
     * @return a list of {@code Counter} objects for that engine
     */
    private List<Counter> getValuesFromCache(final String host, final String id, final long timestamp,
                    final long latestValue) {
        SlidingWindowList<Counter> valueList;

        if (!cache.containsKey(host)) {
            cache.put(host, new HashMap<>());
        }

        if (cache.get(host).containsKey(id)) {
            valueList = (SlidingWindowList<Counter>) cache.get(host).get(id);
        } else {
            valueList = new SlidingWindowList<>(MAX_CACHED_ENTITIES);
        }
        valueList.add(new Counter(timestamp, latestValue));

        cache.get(host).put(id, valueList);

        return valueList;
    }


    /**
     * Get an engine service facade for sending REST requests. This method is package because it is used by unit test.
     *
     * @param hostName the host name of the Apex engine
     * @param port the port of the Apex engine
     * @return the engine service facade
     */
    protected EngineServiceFacade getEngineServiceFacade(final String hostName, final int port) {
        return new EngineServiceFacade(hostName, port);
    }

    /**
     * A list of values that uses a FIFO sliding window of a fixed size.
     */
    public class SlidingWindowList<V> extends LinkedList<V> {
        private static final long serialVersionUID = -7187277916025957447L;

        private final int maxEntries;

        public SlidingWindowList(final int maxEntries) {
            this.maxEntries = maxEntries;
        }

        @Override
        public boolean add(final V elm) {
            if (this.size() > (maxEntries - 1)) {
                this.removeFirst();
            }
            return super.add(elm);
        }

        private ApexMonitoringRestResource getOuterType() {
            return ApexMonitoringRestResource.this;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = super.hashCode();
            result = prime * result + getOuterType().hashCode();
            result = prime * result + maxEntries;
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }

            if (!super.equals(obj)) {
                return false;
            }

            if (getClass() != obj.getClass()) {
                return false;
            }

            @SuppressWarnings("unchecked")
            SlidingWindowList<V> other = (SlidingWindowList<V>) obj;
            if (!getOuterType().equals(other.getOuterType())) {
                return false;
            }

            return maxEntries == other.maxEntries;
        }
    }

    /**
     * A class used to storing a single data entry for an engine.
     */
    public class Counter {
        private long timestamp;
        private long value;

        public Counter(final long timestamp, final long value) {
            this.timestamp = timestamp;
            this.value = value;
        }

        public long getTimestamp() {
            return timestamp;
        }

        public long getValue() {
            return value;
        }
    }
}