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