use logging interceptor in SDC client
[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 static java.nio.charset.StandardCharsets.UTF_8;
24
25 import java.io.File;
26 import java.io.IOException;
27 import java.util.List;
28 import java.util.Objects;
29 import java.util.function.Supplier;
30 import java.util.stream.Collectors;
31 import java.util.stream.Stream;
32 import javax.servlet.http.HttpServletRequest;
33 import javax.ws.rs.InternalServerErrorException;
34 import javax.ws.rs.NotAuthorizedException;
35 import org.apache.commons.io.input.ReversedLinesFileReader;
36 import org.apache.commons.lang3.StringUtils;
37 import org.onap.portalsdk.core.controller.RestrictedBaseController;
38 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
39 import org.onap.vid.model.ExceptionResponse;
40 import org.onap.vid.roles.Role;
41 import org.onap.vid.roles.RoleProvider;
42 import org.onap.vid.utils.Streams;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.http.HttpStatus;
45 import org.springframework.web.bind.annotation.ExceptionHandler;
46 import org.springframework.web.bind.annotation.GetMapping;
47 import org.springframework.web.bind.annotation.PathVariable;
48 import org.springframework.web.bind.annotation.RequestMapping;
49 import org.springframework.web.bind.annotation.RequestParam;
50 import org.springframework.web.bind.annotation.ResponseStatus;
51 import org.springframework.web.bind.annotation.RestController;
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     private RoleProvider roleProvider;
60     private LogfilePathCreator logfilePathCreator;
61
62     @Autowired
63     public LoggerController(RoleProvider roleProvider, LogfilePathCreator logfilePathCreator) {
64         this.roleProvider = roleProvider;
65         this.logfilePathCreator = logfilePathCreator;
66     }
67
68     @GetMapping(value = "/{loggerName:audit|audit2019|error|metrics|metrics2019}")
69     public String getLog(@PathVariable String loggerName, HttpServletRequest request,
70                          @RequestParam(value="limit", defaultValue = "5000") Integer limit) throws IOException {
71
72         List<Role> roles = roleProvider.getUserRoles(request);
73         boolean userPermitted = roleProvider.userPermissionIsReadLogs(roles);
74         if (!userPermitted) {
75             throw new NotAuthorizedException("User not authorized to get logs");
76         }
77
78         String logfilePath = logfilePathCreator.getLogfilePath(loggerName);
79         try (final ReversedLinesFileReader reader = new ReversedLinesFileReader(new File(logfilePath), UTF_8)) {
80             Supplier<String> reverseLinesSupplier = () -> {
81                 try {
82                     return reader.readLine();
83                 } catch (NullPointerException e) {
84                     // EOF Reached
85                     return null;
86                 } catch (IOException e) {
87                     throw new InternalServerErrorException("error while reading " + logfilePath, e);
88                 }
89             };
90
91             return Streams.takeWhile(
92                     Stream.generate(reverseLinesSupplier),
93                     line -> !StringUtils.contains(line, "Logging is started"))
94                     .limit(limit)
95                     .limit(5_000)
96                     .filter(Objects::nonNull)
97                     .collect(Collectors.joining("\n"));
98         }
99     }
100
101     @ExceptionHandler({ NotAuthorizedException.class })
102     @ResponseStatus(HttpStatus.UNAUTHORIZED)
103     public String notAuthorizedHandler(NotAuthorizedException e) {
104         return "UNAUTHORIZED";
105     }
106
107     @ExceptionHandler({ IOException.class, InternalServerErrorException.class })
108     @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
109     public ExceptionResponse ioExceptionHandler(Exception e) {
110         return ControllersUtils.handleException(e, LOGGER);
111     }
112
113 }