2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.logging.filter.base;
23 import java.net.InetAddress;
24 import java.net.UnknownHostException;
25 import java.time.ZoneOffset;
26 import java.time.ZonedDateTime;
27 import java.time.format.DateTimeFormatter;
28 import java.time.temporal.ChronoUnit;
29 import java.util.Base64;
30 import java.util.UUID;
31 import javax.servlet.http.HttpServletRequest;
32 import javax.ws.rs.core.HttpHeaders;
33 import javax.ws.rs.core.Response;
34 import org.onap.logging.ref.slf4j.ONAPLogConstants;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
39 public class MDCSetup {
41 protected static Logger logger = LoggerFactory.getLogger(MDCSetup.class);
42 private static final String INSTANCE_UUID = UUID.randomUUID().toString();
43 protected static final String serverIpAddressOverride = "SERVER_IP_ADDRESS_OVERRIDE";
44 protected static final String serverFqdnOverride = "SERVER_FQDN_OVERRIDE";
45 protected static final String checkHeaderLogPattern = "Checking {} header to determine the value of {}";
46 protected String serverFqdn;
47 protected String serverIpAddress;
48 protected String[] prioritizedIdHeadersNames;
49 protected String[] prioritizedPartnerHeadersNames;
52 this.prioritizedIdHeadersNames =
53 new String[] {ONAPLogConstants.Headers.REQUEST_ID, Constants.HttpHeaders.HEADER_REQUEST_ID,
54 Constants.HttpHeaders.TRANSACTION_ID, Constants.HttpHeaders.ECOMP_REQUEST_ID};
55 this.prioritizedPartnerHeadersNames =
56 new String[] {HttpHeaders.AUTHORIZATION, ONAPLogConstants.Headers.PARTNER_NAME, HttpHeaders.USER_AGENT};
57 initServerFqdnandIp();
60 public void setInstanceID() {
61 MDC.put(ONAPLogConstants.MDCs.INSTANCE_UUID, INSTANCE_UUID);
64 protected void initServerFqdnandIp() {
65 serverFqdn = getProperty(serverFqdnOverride);
66 serverIpAddress = getProperty(serverIpAddressOverride);
68 if (serverIpAddress.equals(Constants.DefaultValues.UNKNOWN)
69 || serverFqdn.equals(Constants.DefaultValues.UNKNOWN)) {
71 InetAddress addr = InetAddress.getLocalHost();
72 if (serverFqdn.equals(Constants.DefaultValues.UNKNOWN)) {
73 serverFqdn = addr.getCanonicalHostName();
75 if (serverIpAddress.equals(Constants.DefaultValues.UNKNOWN)) {
76 serverIpAddress = addr.getHostAddress();
78 } catch (UnknownHostException e) {
79 logger.trace("Cannot Resolve Host Name." + e.getMessage());
84 public void setServerFQDN() {
85 MDC.put(ONAPLogConstants.MDCs.SERVER_FQDN, serverFqdn);
86 MDC.put(ONAPLogConstants.MDCs.SERVER_IP_ADDRESS, serverIpAddress);
89 public void setClientIPAddress(HttpServletRequest httpServletRequest) {
90 String clientIpAddress = "";
91 if (httpServletRequest != null) {
92 // This logic is to avoid setting the client ip address to that of the load
93 // balancer in front of the application
94 String getForwadedFor = httpServletRequest.getHeader("X-Forwarded-For");
95 if (getForwadedFor != null) {
96 clientIpAddress = getForwadedFor;
98 clientIpAddress = httpServletRequest.getRemoteAddr();
101 MDC.put(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS, clientIpAddress);
104 public void setEntryTimeStamp() {
105 MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP,
106 ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
109 public String getRequestId(SimpleMap headers) {
110 String requestId = null;
111 for (String headerName : this.prioritizedIdHeadersNames) {
112 logger.trace(checkHeaderLogPattern, headerName, ONAPLogConstants.Headers.REQUEST_ID);
113 requestId = headers.get(headerName);
114 if (requestId != null && !requestId.isEmpty()) {
118 logger.trace("No valid requestId headers. Generating requestId: {}", requestId);
119 return UUID.randomUUID().toString();
122 public void setInvocationId(SimpleMap headers) {
123 String invocationId = headers.get(ONAPLogConstants.Headers.INVOCATION_ID);
124 if (invocationId == null || invocationId.isEmpty())
125 invocationId = UUID.randomUUID().toString();
126 MDC.put(ONAPLogConstants.MDCs.SERVER_INVOCATION_ID, invocationId);
127 MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
130 public void setMDCPartnerName(SimpleMap headers) {
131 String partnerName = getMDCPartnerName(headers);
132 MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, partnerName);
135 protected String getMDCPartnerName(SimpleMap headers) {
136 String partnerName = null;
137 for (String headerName : prioritizedPartnerHeadersNames) {
138 logger.trace(checkHeaderLogPattern, headerName, ONAPLogConstants.MDCs.PARTNER_NAME);
139 if (headerName.equals(HttpHeaders.AUTHORIZATION)) {
140 partnerName = getBasicAuthUserName(headers);
142 partnerName = headers.get(headerName);
144 if (partnerName != null && !partnerName.isEmpty()) {
149 logger.trace("{} value could not be determined, defaulting partnerName to {}.",
150 ONAPLogConstants.MDCs.PARTNER_NAME, Constants.DefaultValues.UNKNOWN);
151 return Constants.DefaultValues.UNKNOWN;
154 public void setLogTimestamp() {
155 MDC.put(ONAPLogConstants.MDCs.LOG_TIMESTAMP,
156 ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
159 public void setElapsedTime() {
161 DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
162 ZonedDateTime entryTimestamp =
163 ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP), timeFormatter);
164 ZonedDateTime endTimestamp =
165 ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP), timeFormatter);
167 MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME,
168 Long.toString(ChronoUnit.MILLIS.between(entryTimestamp, endTimestamp)));
169 } catch (Exception e) {
170 logger.trace("Unable to calculate elapsed time due to error: {}", e.getMessage());
174 public void setElapsedTimeInvokeTimestamp() {
176 DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
177 ZonedDateTime entryTimestamp =
178 ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP), timeFormatter);
179 ZonedDateTime endTimestamp =
180 ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP), timeFormatter);
182 MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME,
183 Long.toString(ChronoUnit.MILLIS.between(entryTimestamp, endTimestamp)));
184 } catch (Exception e) {
185 logger.trace("Unable to calculate elapsed time due to error: {}", e.getMessage());
189 public void setResponseStatusCode(int code) {
191 if (Response.Status.Family.familyOf(code).equals(Response.Status.Family.SUCCESSFUL)) {
192 statusCode = ONAPLogConstants.ResponseStatus.COMPLETE.toString();
194 statusCode = ONAPLogConstants.ResponseStatus.ERROR.toString();
198 MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode);
201 public void setTargetEntity(ONAPComponentsList targetEntity) {
202 MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, targetEntity.toString());
205 public void clearClientMDCs() {
206 MDC.remove(ONAPLogConstants.MDCs.CLIENT_INVOCATION_ID);
207 MDC.remove(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION);
208 MDC.remove(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE);
209 MDC.remove(ONAPLogConstants.MDCs.RESPONSE_CODE);
210 MDC.remove(ONAPLogConstants.MDCs.TARGET_ENTITY);
211 MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME);
212 MDC.remove(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP);
213 MDC.remove(ONAPLogConstants.MDCs.ERROR_CODE);
214 MDC.remove(ONAPLogConstants.MDCs.ERROR_DESC);
217 public void setResponseDescription(int statusCode) {
218 MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, Response.Status.fromStatusCode(statusCode).toString());
221 public void setErrorCode(int statusCode) {
222 MDC.put(ONAPLogConstants.MDCs.ERROR_CODE, String.valueOf(statusCode));
225 public void setErrorDesc(int statusCode) {
226 MDC.put(ONAPLogConstants.MDCs.ERROR_DESC, Response.Status.fromStatusCode(statusCode).toString());
229 public String getProperty(String property) {
230 String propertyValue = System.getProperty(property);
231 if (propertyValue == null || propertyValue.isEmpty()) {
232 propertyValue = System.getenv(property);
233 if (propertyValue == null || propertyValue.isEmpty()) {
234 propertyValue = Constants.DefaultValues.UNKNOWN;
237 return propertyValue;
240 protected String getBasicAuthUserName(SimpleMap headers) {
241 String encodedAuthorizationValue = headers.get(HttpHeaders.AUTHORIZATION);
242 if (encodedAuthorizationValue != null && encodedAuthorizationValue.startsWith("Basic")) {
244 // This will strip the word Basic and single space
245 encodedAuthorizationValue = encodedAuthorizationValue.substring(6);
246 byte[] decodedBytes = Base64.getDecoder().decode(encodedAuthorizationValue);
247 String decodedString = new String(decodedBytes);
248 int idx = decodedString.indexOf(':');
249 return decodedString.substring(0, idx);
250 } catch (IllegalArgumentException e) {
251 logger.error("could not decode basic auth value " + encodedAuthorizationValue, e);