aboutsummaryrefslogtreecommitdiffstats
path: root/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/ConsulController.java
blob: 8350737a896f8f2f47c09f62b0d0f3e6540280d1 (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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/*******************************************************************************
 * =============LICENSE_START=========================================================
 *
 * =================================================================================
 *  Copyright (c) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 *  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.
 * ============LICENSE_END=========================================================
 *
 *  ECOMP is a trademark and service mark of AT&T Intellectual Property.
 *******************************************************************************/
package org.onap.ccsdk.dashboard.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import java.net.URI;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration;
import org.onap.ccsdk.dashboard.model.ConsulNodeInfo;
import org.onap.ccsdk.dashboard.model.ConsulServiceHealth;
import org.onap.ccsdk.dashboard.model.RestResponsePage;
import org.onap.ccsdk.dashboard.rest.IControllerRestClient;
import org.onap.ccsdk.dashboard.exception.DashboardControllerException;
import org.onap.ccsdk.dashboard.model.ConsulServiceInfo;
import org.onap.ccsdk.dashboard.model.ECTransportModel;
import org.onap.ccsdk.dashboard.model.RestResponseError;
import org.onap.ccsdk.dashboard.model.RestResponseSuccess;
import org.onap.portalsdk.core.domain.User;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.util.SystemProperties;
import org.onap.portalsdk.core.web.support.UserUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.HttpStatusCodeException;

/**
 * Controller for Consul features: health checks of services, nodes, data
 * centers. Methods serve Ajax requests made by Angular scripts on pages that
 * show content.
 */
@Controller
@RequestMapping("/healthservices")
public class ConsulController extends DashboardRestrictedBaseController {

    private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ConsulController.class);

    /**
     * Enum for selecting an item type.
     */
    public enum ConsulDataItem {
        SERVICE_INFO, SERVICE_HEALTH, NODES, DATACENTERS;
    }

    private static final String NODES_PATH = "/nodes";
    private static final String SERVICES_PATH = "/services";

    /**
     * Supports sorting results by node name
     */
    private static Comparator<ConsulNodeInfo> nodeHealthComparator = Comparator.comparing(o -> o.node);

    /**
     * Supports sorting results by service name
     */
    private static Comparator<ConsulServiceHealth> serviceHealthComparator = Comparator.comparing(o -> o.serviceName);

    /**
     * Supports sorting results by service name
     */
    private static Comparator<ConsulServiceInfo> serviceInfoComparator = Comparator.comparing(o -> o.name);

    /**
     * Gets one page of objects and supporting information via the REST client. On
     * success, returns a page of objects as String.
     *
     * @param option
     *            Specifies which item type to get
     * @param pageNum
     *            Page number of results
     * @param pageSize
     *            Number of items per browser page
     * @return JSON block as String, see above.
     * @throws DashboardControllerException,
     *             JsonProcessingException On any error; e.g., Network failure.
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    private String getItemListForPage(long userId, ConsulDataItem option, int pageNum, int pageSize)
        throws DashboardControllerException, JsonProcessingException {
        IControllerRestClient restClient = getControllerRestClient(userId);
        List itemList;
        switch (option) {
            case NODES:
                itemList = restClient.getNodes();
                itemList.sort(nodeHealthComparator);
                break;
            case DATACENTERS:
                itemList = restClient.getDatacenters();
                break;
            default:
                throw new DashboardControllerException(
                    "getItemListForPage failed: unimplemented case: " + option.name());
        }

        // Shrink if needed
        if (itemList.size() > pageSize) {
            itemList = getPageOfList(pageNum, pageSize, itemList);
        }
        int pageCount = (int) Math.ceil((double) itemList.size() / pageSize);
        RestResponsePage<List> model = new RestResponsePage<>(itemList.size(), pageCount, itemList);
        return objectMapper.writeValueAsString(model);
    }

    /**
     * Gets one page of the specified items. This method traps exceptions and
     * constructs an appropriate JSON block to report errors.
     *
     * @param request
     *            Inbound request
     * @param option
     *            Item type to get
     * @return JSON with one page of objects; or an error.
     */
    protected String getItemListForPageWrapper(HttpServletRequest request, ConsulDataItem option) {
        String outboundJson;
        try {
            User appUser = UserUtils.getUserSession(request);
            if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) {
                throw new DashboardControllerException("getItemListForPageWrapper: Failed to get application user");
            }
            int pageNum = getRequestPageNumber(request);
            int pageSize = getRequestPageSize(request);
            outboundJson = getItemListForPage(appUser.getId(), option, pageNum, pageSize);
        } catch (Exception ex) {
            // Remote service failed; build descriptive error message
            logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPageWrapper caught exception", ex);
            RestResponseError result = new RestResponseError("Failed to get " + option.name(), ex);
            try {
                outboundJson = objectMapper.writeValueAsString(result);
            } catch (JsonProcessingException jpe) {
                // Should never, ever happen
                outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}";
            }
        }
        return outboundJson;
    }

    /**
     * Serves all service details.
     *
     * @param request
     *            HttpServletRequest
     * @return List of ConsulServiceInfo objects, as JSON
     * @throws JsonProcessingException
     *             if serialization fails
     */
    @RequestMapping(value = {SERVICES_PATH}, method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public String getServices(HttpServletRequest request) throws JsonProcessingException {
        MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date()));
        logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME);
        Object result;
        try {
            IControllerRestClient restClient = getControllerRestClient(request);
            List<ConsulServiceInfo> itemList = restClient.getServices();
            itemList.sort(serviceInfoComparator);
            result = itemList;
        } catch (Exception t) {
            result = new RestResponseError("getServices failed", t);
        }
        MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date()));
        logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI());
        return objectMapper.writeValueAsString(result);
    }

    /**
     * Serves service health details - not paginated.
     *
     * @param request
     *            HttpServletRequest
     * @param serviceId
     *            Service ID
     * @return List of ConsulServiceHealth objects as JSON
     * @throws JsonProcessingException
     *             if serialization fails
     */
    @RequestMapping(value = {
        SERVICES_PATH + "/{serviceId}"}, method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public String getServiceHealthDetails(HttpServletRequest request, @PathVariable String serviceId)
        throws JsonProcessingException {
        MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date()));
        logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME);
        Object result;
        try {
            IControllerRestClient restClient = getControllerRestClient(request);
            result = restClient.getServiceHealth(serviceId);
        } catch (Exception t) {
            result = new RestResponseError("getServiceHealthDetails failed", t);
        }
        MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date()));
        logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI());
        return objectMapper.writeValueAsString(result);
    }

    /**
     * Serves service health historical data - not paginated.
     *
     * @param request
     *            HttpServletRequest
     * @param serviceName
     *            Service name as path parameter
     * @param start
     *            Earliest date-time as an ISO 8061 value, such as
     *            2007-12-03T10:15:30+01:00
     * @param end
     *            Latest date-time as an ISO 8061 value, such as
     *            2007-12-03T10:15:30+01:00
     * @return List of ConsulServiceHealth objects as JSON
     * @throws JsonProcessingException
     *             if serialization fails
     */
    @RequestMapping(value = {"/svchist/{serviceName}"}, method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public String getServiceHealthHistory(HttpServletRequest request, //
        @PathVariable String serviceName, //
        @RequestParam String start, //
        @RequestParam String end) throws JsonProcessingException {
        MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date()));
        logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME);
        Object result = null;
        try {
            Instant startDateTime = Instant.parse(start);
            Instant endDateTime = Instant.parse(end);
            IControllerRestClient restClient = getControllerRestClient(request);
            result = restClient.getServiceHealthHistory(serviceName, startDateTime, endDateTime);
        } catch (HttpStatusCodeException e) {
            // Rare, but can happen
            result = new RestResponseError(e.getResponseBodyAsString());
        } catch (Exception t) {
            // Work around the hack to report no-match.
            result = new RestResponseError("getServiceHealthHistory failed: " + t.getMessage());
        }
        MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date()));
        logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI());
        return objectMapper.writeValueAsString(result);
    }

    /**
     * Serves one page of service health information by getting all service names,
     * then iterating over them to get the health of each service.
     *
     * ECOMP-C does NOT provide an API to get the health of all services in one
     * request.
     *
     * @param request
     *            HttpServletRequest
     * @return List of ConsulServiceHealth objects, as JSON
     * @throws JsonProcessingException
     *             on serialization exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = {"/serviceshealth"}, method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public String getServicesHealth(HttpServletRequest request) throws JsonProcessingException {
        MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date()));
        logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME);
        ECTransportModel result = null;
        try {
            List<ConsulServiceHealth> itemList = new ArrayList<>();
            IControllerRestClient restClient = getControllerRestClient(request);
            List<ConsulServiceInfo> svcInfoList = restClient.getServices();
            for (ConsulServiceInfo csi : svcInfoList) {
                List<ConsulServiceHealth> csh = restClient.getServiceHealth(csi.name);
                itemList.addAll(csh);
            }
            itemList.sort(serviceHealthComparator);
            // Paginate
            final int pageNum = getRequestPageNumber(request);
            final int pageSize = getRequestPageSize(request);
            final int totalItems = itemList.size();
            final int pageCount = (int) Math.ceil((double) totalItems / pageSize);
            // Shrink if needed
            if (totalItems > pageSize) {
                itemList = getPageOfList(pageNum, pageSize, itemList);
            }
            result = new RestResponsePage<>(totalItems, pageCount, itemList);
        } catch (Exception t) {
            result = new RestResponseError("getServicesHealth failed", t);
        }
        MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date()));
        logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI());
        return objectMapper.writeValueAsString(result);
    }

    /**
     * Serves one page of node information.
     *
     * @param request
     *            HttpServletRequest
     * @return List of ConsulNodeInfo objects, as JSON
     */
    @RequestMapping(value = {NODES_PATH}, method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public String getNodesInfo(HttpServletRequest request) {
        MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date()));
        logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME);
        String json = getItemListForPageWrapper(request, ConsulDataItem.NODES);
        MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date()));
        logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI());
        return json;
    }

    /**
     * Serves node services health details - not paginated.
     *
     * @param request
     *            HttpServletRequest
     * @param nodeName
     *            Node name
     * @return List of ConsulServiceHealth objects as JSON
     * @throws JsonProcessingException
     *             if serialization fails
     */
    @RequestMapping(value = {NODES_PATH + "/{nodeName}"}, method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public String getNodeServicesHealth(HttpServletRequest request, @PathVariable String nodeName)
        throws JsonProcessingException {
        MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date()));
        logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME);
        Object result = null;
        try {
            IControllerRestClient restClient = getControllerRestClient(request);
            result = restClient.getNodeServicesHealth(nodeName);
        } catch (Exception t) {
            result = new RestResponseError("getNodeServicesHealth failed", t);
        }
        MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date()));
        logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI());
        return objectMapper.writeValueAsString(result);
    }

    /**
     * Serves one page of data centers health.
     *
     * @param request
     *            HttpServletRequest
     * @return List of ConsulHealthStatus objects
     */
    @RequestMapping(value = {"/datacenters"}, method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public String getDatacentersHealth(HttpServletRequest request) {
        MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date()));
        logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME);
        String json = getItemListForPageWrapper(request, ConsulDataItem.DATACENTERS);
        MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date()));
        logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI());
        return json;
    }

    /**
     * Processes request to register a service for health checks.
     *
     * @param request
     *            HttpServletRequest
     * @param registration
     *            Consul service registration
     * @return URI of the newly registered resource
     * @throws JsonProcessingException
     *             on serialization error
     */
    @RequestMapping(value = {"/register"}, method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public String registerService(HttpServletRequest request, @RequestBody ConsulHealthServiceRegistration registration)
        throws JsonProcessingException {
        MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date()));
        logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME);
        ECTransportModel result = null;
        try {
            IControllerRestClient restClient = getControllerRestClient(request);
            URI uri = restClient.registerService(registration);
            result = new RestResponseSuccess(uri.toString());
        } catch (HttpStatusCodeException e) {
            result = new RestResponseError(e.getResponseBodyAsString());
        } catch (Exception t) {
            result = new RestResponseError("registerService failed", t);
        }
        MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date()));
        logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI());
        return objectMapper.writeValueAsString(result);
    }

    /**
     * Processes request to deregister a service for health checks.
     *
     * @param request
     *            HttpServletRequest
     * @param serviceName
     *            Consul service name to deregister
     * @return Success or error indicator
     * @throws JsonProcessingException
     *             on serialization error
     */
    @RequestMapping(value = {
        "/deregister" + "/{serviceName}"}, method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public String deregisterService(HttpServletRequest request, @PathVariable String serviceName)
        throws JsonProcessingException {
        MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(new Date()));
        logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME);
        ECTransportModel result = null;
        try {
            IControllerRestClient restClient = getControllerRestClient(request);
            int code = restClient.deregisterService(serviceName);
            result = new RestResponseSuccess("Deregistration yielded code " + Integer.toString(code));
        } catch (HttpStatusCodeException e) {
            result = new RestResponseError(e.getResponseBodyAsString());
        } catch (Exception t) {
            result = new RestResponseError("deregisterService failed", t);
        }
        MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(new Date()));
        logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI());
        return objectMapper.writeValueAsString(result);
    }
}