Update license headers
[vid.git] / vid-app-common / src / main / java / org / onap / vid / controller / LoggerController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 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  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.vid.controller;
22
23 import ch.qos.logback.classic.LoggerContext;
24 import ch.qos.logback.core.Appender;
25 import ch.qos.logback.core.FileAppender;
26 import ch.qos.logback.core.spi.AppenderAttachable;
27 import org.apache.commons.io.input.ReversedLinesFileReader;
28 import org.apache.commons.lang3.StringUtils;
29 import org.onap.portalsdk.core.controller.RestrictedBaseController;
30 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
31 import org.onap.vid.model.ExceptionResponse;
32 import org.onap.vid.roles.Role;
33 import org.onap.vid.roles.RoleProvider;
34 import org.onap.vid.utils.Streams;
35 import org.slf4j.LoggerFactory;
36 import org.springframework.beans.factory.annotation.Autowired;
37 import org.springframework.http.HttpStatus;
38 import org.springframework.web.bind.annotation.*;
39
40 import javax.servlet.http.HttpServletRequest;
41 import javax.ws.rs.InternalServerErrorException;
42 import javax.ws.rs.NotAuthorizedException;
43 import java.io.File;
44 import java.io.IOException;
45 import java.util.List;
46 import java.util.Objects;
47 import java.util.function.Supplier;
48 import java.util.stream.Collectors;
49 import java.util.stream.Stream;
50
51 import static com.att.eelf.configuration.Configuration.GENERAL_LOGGER_NAME;
52
53
54 @RestController
55 @RequestMapping("logger")
56 public class LoggerController extends RestrictedBaseController {
57
58     private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(LoggerController.class);
59
60     @Autowired
61     RoleProvider roleProvider;
62
63     @RequestMapping(value = "/{loggerName:audit|error|metrics}", method = RequestMethod.GET)
64     public String getLog(@PathVariable String loggerName, HttpServletRequest request,
65                          @RequestParam(value="limit", defaultValue = "5000") Integer limit) throws IOException {
66
67         List<Role> roles = roleProvider.getUserRoles(request);
68         boolean userPermitted = roleProvider.userPermissionIsReadLogs(roles);
69         if (!userPermitted) {
70             throw new NotAuthorizedException("User not authorized to get logs");
71         }
72
73         String logfilePath = getLogfilePath(loggerName);
74
75         try (final ReversedLinesFileReader reader = new ReversedLinesFileReader(new File(logfilePath))) {
76             Supplier<String> reverseLinesSupplier = () -> {
77                 try {
78                     return reader.readLine();
79                 } catch (NullPointerException e) {
80                     // EOF Reached
81                     return null;
82                 } catch (IOException e) {
83                     throw new InternalServerErrorException("error while reading " + logfilePath, e);
84                 }
85             };
86
87             return Streams.takeWhile(
88                     Stream.generate(reverseLinesSupplier),
89                     line -> !StringUtils.contains(line, "Logging is started"))
90                     .limit(limit)
91                     .limit(5_000)
92                     .filter(Objects::nonNull)
93                     .collect(Collectors.joining("\n"));
94         }
95     }
96
97     private String getLogfilePath(String loggerName) {
98         /*
99         Find the requested logger, and pull all of it's appenders.
100         Find the first of the appenders that is a FileAppender, and return it's
101         write-out filename.
102          */
103         LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
104         return context.getLoggerList().stream()
105                 .filter(logger -> logger.getName().equals(GENERAL_LOGGER_NAME + "." + loggerName))
106                 .flatMap(this::pullSubAppenders)
107                 .flatMap(appender -> {
108                     // Appender might be "attachable", if so - roll-up its sub-appenders
109                     return (appender instanceof AppenderAttachable) ?
110                             pullSubAppenders((AppenderAttachable<?>) appender) : Stream.of(appender);
111                 })
112                 .filter(appender -> appender instanceof FileAppender)
113                 .map(appender -> (FileAppender<?>) appender)
114                 .map(FileAppender::getFile)
115                 .findFirst()
116                 .orElseThrow(() -> new InternalServerErrorException("logfile for " + loggerName + " not found"));
117     }
118
119     private <T> Stream<Appender<T>> pullSubAppenders(AppenderAttachable<T> logger) {
120         return Streams.fromIterator(logger.iteratorForAppenders());
121     }
122
123     @ExceptionHandler({ NotAuthorizedException.class })
124     @ResponseStatus(HttpStatus.UNAUTHORIZED)
125     public String notAuthorizedHandler(NotAuthorizedException e) {
126         return "UNAUTHORIZED";
127     }
128
129     @ExceptionHandler({ IOException.class, InternalServerErrorException.class })
130     @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
131     public ExceptionResponse ioExceptionHandler(Exception e) {
132         return ControllersUtils.handleException(e, LOGGER);
133     }
134
135 }