Merge "[AAI] Fix doc config files"
[aai/aai-common.git] / aai-els-onap-logging / src / main / java / org / onap / logging / filter / base / MDCSetup.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - Logging
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
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.logging.filter.base;
22
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.UUID;
30
31 import javax.servlet.http.HttpServletRequest;
32 import javax.ws.rs.core.HttpHeaders;
33 import javax.ws.rs.core.Response;
34
35 import org.onap.logging.ref.slf4j.ONAPLogConstants;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.slf4j.MDC;
39
40 public class MDCSetup {
41
42     protected static Logger logger = LoggerFactory.getLogger(MDCSetup.class);
43
44     private static final String INSTANCE_UUID = UUID.randomUUID().toString();
45
46     public void setInstanceID() {
47         MDC.put(ONAPLogConstants.MDCs.INSTANCE_UUID, INSTANCE_UUID);
48     }
49
50     public void setServerFQDN() {
51         String serverFQDN = "";
52         InetAddress addr = null;
53         try {
54             addr = InetAddress.getLocalHost();
55             serverFQDN = addr.getCanonicalHostName();
56             MDC.put(ONAPLogConstants.MDCs.SERVER_IP_ADDRESS, addr.getHostAddress());
57         } catch (UnknownHostException e) {
58             logger.warn("Cannot Resolve Host Name");
59             serverFQDN = "";
60         }
61         MDC.put(ONAPLogConstants.MDCs.SERVER_FQDN, serverFQDN);
62     }
63
64     public void setClientIPAddress(HttpServletRequest httpServletRequest) {
65         String clientIpAddress = "";
66         if (httpServletRequest != null) {
67             // This logic is to avoid setting the client ip address to that of the load
68             // balancer in front of the application
69             String getForwadedFor = httpServletRequest.getHeader("X-Forwarded-For");
70             if (getForwadedFor != null) {
71                 clientIpAddress = getForwadedFor;
72             } else {
73                 clientIpAddress = httpServletRequest.getRemoteAddr();
74             }
75         }
76         MDC.put(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS, clientIpAddress);
77     }
78
79     public void setEntryTimeStamp() {
80         MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP,
81                 ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
82     }
83
84     public String getRequestId(SimpleMap headers) {
85         logger.trace("Checking X-ONAP-RequestID header for requestId.");
86         String requestId = headers.get(ONAPLogConstants.Headers.REQUEST_ID);
87         if (requestId != null && !requestId.isEmpty() && isValidUUID(requestId)) {
88             return requestId;
89         }
90         if (requestId != null && !requestId.isEmpty()) {
91             // invalid
92             return UUID.randomUUID().toString();
93         }
94         logger.trace("No valid X-ONAP-RequestID header value. Checking X-RequestID header for requestId.");
95         requestId = headers.get(Constants.HttpHeaders.HEADER_REQUEST_ID);
96         if (requestId != null && !requestId.isEmpty() && isValidUUID(requestId)) {
97             return requestId;
98         }
99         if (requestId != null && !requestId.isEmpty()) {
100             // invalid
101             return UUID.randomUUID().toString();
102         }
103         logger.trace("No valid X-RequestID header value. Checking X-TransactionID header for requestId.");
104         requestId = headers.get(Constants.HttpHeaders.TRANSACTION_ID);
105         if (requestId != null && !requestId.isEmpty() && isValidUUID(requestId)) {
106             return requestId;
107         }
108         if (requestId != null && !requestId.isEmpty()) {
109             // invalid
110             return UUID.randomUUID().toString();
111         }
112         logger.trace("No valid X-TransactionID header value. Checking X-ECOMP-RequestID header for requestId.");
113         requestId = headers.get(Constants.HttpHeaders.ECOMP_REQUEST_ID);
114         if (requestId != null && !requestId.isEmpty() && isValidUUID(requestId)) {
115             return requestId;
116         }
117         if (requestId != null && !requestId.isEmpty()) {
118             // invalid
119             return UUID.randomUUID().toString();
120         }
121         return requestId;
122     }
123
124     protected boolean isValidUUID(String transId) {
125         try {
126             UUID.fromString(transId);
127         } catch (IllegalArgumentException e) {
128             return false;
129         }
130         return true;
131     }
132
133     public void setInvocationId(SimpleMap headers) {
134         String invocationId = headers.get(ONAPLogConstants.Headers.INVOCATION_ID);
135         if (invocationId == null || invocationId.isEmpty())
136             invocationId = UUID.randomUUID().toString();
137         MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
138     }
139
140     public void setInvocationIdFromMDC() {
141         String invocationId = MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID);
142         if (invocationId == null || invocationId.isEmpty())
143             invocationId = UUID.randomUUID().toString();
144         MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
145     }
146
147     public void setMDCPartnerName(SimpleMap headers) {
148         logger.trace("Checking X-ONAP-PartnerName header for partnerName.");
149         String partnerName = headers.get(ONAPLogConstants.Headers.PARTNER_NAME);
150         if (partnerName == null || partnerName.isEmpty()) {
151             logger.trace("No valid X-ONAP-PartnerName header value. Checking User-Agent header for partnerName.");
152             partnerName = headers.get(HttpHeaders.USER_AGENT);
153             if (partnerName == null || partnerName.isEmpty()) {
154                 logger.trace("No valid User-Agent header value. Checking X-ClientID header for partnerName.");
155                 partnerName = headers.get(Constants.HttpHeaders.CLIENT_ID);
156                 if (partnerName == null || partnerName.isEmpty()) {
157                     logger.trace("No valid partnerName headers. Defaulting partnerName to UNKNOWN.");
158                     partnerName = Constants.DefaultValues.UNKNOWN;
159                 }
160             }
161         }
162         MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, partnerName);
163     }
164
165     public void setLogTimestamp() {
166         MDC.put(ONAPLogConstants.MDCs.LOG_TIMESTAMP,
167                 ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
168     }
169
170     public void setElapsedTime() {
171         DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
172         ZonedDateTime entryTimestamp =
173                 ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP), timeFormatter);
174         ZonedDateTime endTimestamp = ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP), timeFormatter);
175
176         MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME,
177                 Long.toString(ChronoUnit.MILLIS.between(entryTimestamp, endTimestamp)));
178     }
179
180     public void setElapsedTimeInvokeTimestamp() {
181         DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
182         ZonedDateTime entryTimestamp =
183                 ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP), timeFormatter);
184         ZonedDateTime endTimestamp = ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP), timeFormatter);
185
186         MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME,
187                 Long.toString(ChronoUnit.MILLIS.between(entryTimestamp, endTimestamp)));
188     }
189
190     public void setResponseStatusCode(int code) {
191         String statusCode;
192         if (Response.Status.Family.familyOf(code).equals(Response.Status.Family.SUCCESSFUL)) {
193             statusCode = ONAPLogConstants.ResponseStatus.COMPLETE.toString();
194         } else {
195             statusCode = ONAPLogConstants.ResponseStatus.ERROR.toString();
196             setErrorCode(code);
197             setErrorDesc(code);
198         }
199         MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode);
200     }
201
202     public void setTargetEntity(ONAPComponentsList targetEntity) {
203         MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, targetEntity.toString());
204     }
205
206     public void clearClientMDCs() {
207         // MDC.remove(ONAPLogConstants.MDCs.INVOCATION_ID);
208         MDC.remove(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION);
209         MDC.remove(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE);
210         MDC.remove(ONAPLogConstants.MDCs.RESPONSE_CODE);
211         MDC.remove(ONAPLogConstants.MDCs.TARGET_ENTITY);
212         MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME);
213         MDC.remove(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP);
214         MDC.remove(ONAPLogConstants.MDCs.ERROR_CODE);
215         MDC.remove(ONAPLogConstants.MDCs.ERROR_DESC);
216     }
217
218     public void setResponseDescription(int statusCode) {
219         MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, Response.Status.fromStatusCode(statusCode).toString());
220     }
221
222     public void setErrorCode(int statusCode) {
223         MDC.put(ONAPLogConstants.MDCs.ERROR_CODE, String.valueOf(statusCode));
224     }
225
226     public void setErrorDesc(int statusCode) {
227         MDC.put(ONAPLogConstants.MDCs.ERROR_DESC, Response.Status.fromStatusCode(statusCode).toString());
228     }
229
230     public String getProperty(String property) {
231         logger.info("Checking for system property [{}]", property);
232         String propertyValue = System.getProperty(property);
233         if (propertyValue == null || propertyValue.isEmpty()) {
234             logger.info("System property was null or empty. Checking environment variable for: {}", property);
235             propertyValue = System.getenv(property);
236             if (propertyValue == null || propertyValue.isEmpty()) {
237                 logger.info("Environment variable: {} was null or empty", property);
238             }
239         }
240         return propertyValue;
241     }
242 }