Set InvocationID value from server and client invocationIds
[logging-analytics.git] / reference / logging-filter / logging-filter-base / src / main / java / org / onap / logging / filter / base / MDCSetup.java
index 93c16a8..d600a2c 100644 (file)
@@ -26,6 +26,7 @@ import java.time.ZoneOffset;
 import java.time.ZonedDateTime;
 import java.time.format.DateTimeFormatter;
 import java.time.temporal.ChronoUnit;
+import java.util.Base64;
 import java.util.UUID;
 import javax.servlet.http.HttpServletRequest;
 import javax.ws.rs.core.HttpHeaders;
@@ -112,32 +113,45 @@ public class MDCSetup {
         String invocationId = headers.get(ONAPLogConstants.Headers.INVOCATION_ID);
         if (invocationId == null || invocationId.isEmpty())
             invocationId = UUID.randomUUID().toString();
+        MDC.put(ONAPLogConstants.MDCs.SERVER_INVOCATION_ID, invocationId);
         MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
     }
 
-    public void setInvocationIdFromMDC() {
-        String invocationId = MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID);
-        if (invocationId == null || invocationId.isEmpty())
-            invocationId = UUID.randomUUID().toString();
-        MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
+    public void setMDCPartnerName(SimpleMap headers) {
+        String partnerName = getMDCPartnerName(headers);
+        MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, partnerName);
     }
 
-    public void setMDCPartnerName(SimpleMap headers) {
-        logger.trace("Checking X-ONAP-PartnerName header for partnerName.");
-        String partnerName = headers.get(ONAPLogConstants.Headers.PARTNER_NAME);
-        if (partnerName == null || partnerName.isEmpty()) {
-            logger.trace("No valid X-ONAP-PartnerName header value. Checking User-Agent header for partnerName.");
-            partnerName = headers.get(HttpHeaders.USER_AGENT);
-            if (partnerName == null || partnerName.isEmpty()) {
-                logger.trace("No valid User-Agent header value. Checking X-ClientID header for partnerName.");
-                partnerName = headers.get(Constants.HttpHeaders.CLIENT_ID);
-                if (partnerName == null || partnerName.isEmpty()) {
-                    logger.trace("No valid partnerName headers. Defaulting partnerName to UNKNOWN.");
-                    partnerName = Constants.DefaultValues.UNKNOWN;
-                }
-            }
+    protected String getMDCPartnerName(SimpleMap headers) {
+        String checkHeaderLogPattern = "Checking {} header to determine the value of {}";
+
+        logger.trace(checkHeaderLogPattern, HttpHeaders.AUTHORIZATION, ONAPLogConstants.MDCs.PARTNER_NAME);
+        String partnerName = getBasicAuthUserName(headers);
+        if (partnerName != null && !partnerName.isEmpty()) {
+            return partnerName;
         }
-        MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, partnerName);
+
+        logger.trace(checkHeaderLogPattern, ONAPLogConstants.Headers.PARTNER_NAME, ONAPLogConstants.MDCs.PARTNER_NAME);
+        partnerName = headers.get(ONAPLogConstants.Headers.PARTNER_NAME);
+        if (partnerName != null && !partnerName.isEmpty()) {
+            return partnerName;
+        }
+
+        logger.trace(checkHeaderLogPattern, HttpHeaders.USER_AGENT, ONAPLogConstants.MDCs.PARTNER_NAME);
+        partnerName = headers.get(HttpHeaders.USER_AGENT);
+        if (partnerName != null && !partnerName.isEmpty()) {
+            return partnerName;
+        }
+
+        logger.trace(checkHeaderLogPattern, Constants.HttpHeaders.CLIENT_ID, ONAPLogConstants.MDCs.PARTNER_NAME);
+        partnerName = headers.get(Constants.HttpHeaders.CLIENT_ID);
+        if (partnerName != null && !partnerName.isEmpty()) {
+            return partnerName;
+        }
+
+        logger.trace("{} value could not be determined, defaulting partnerName to {}.",
+                ONAPLogConstants.MDCs.PARTNER_NAME, Constants.DefaultValues.UNKNOWN);
+        return Constants.DefaultValues.UNKNOWN;
     }
 
     public void setLogTimestamp() {
@@ -146,23 +160,33 @@ public class MDCSetup {
     }
 
     public void setElapsedTime() {
-        DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
-        ZonedDateTime entryTimestamp =
-                ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP), timeFormatter);
-        ZonedDateTime endTimestamp = ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP), timeFormatter);
+        try {
+            DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
+            ZonedDateTime entryTimestamp =
+                    ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP), timeFormatter);
+            ZonedDateTime endTimestamp =
+                    ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP), timeFormatter);
 
-        MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME,
-                Long.toString(ChronoUnit.MILLIS.between(entryTimestamp, endTimestamp)));
+            MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME,
+                    Long.toString(ChronoUnit.MILLIS.between(entryTimestamp, endTimestamp)));
+        } catch (Exception e) {
+            logger.warn("Unable to calculate elapsed time due to error: {}", e.getMessage());
+        }
     }
 
     public void setElapsedTimeInvokeTimestamp() {
-        DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
-        ZonedDateTime entryTimestamp =
-                ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP), timeFormatter);
-        ZonedDateTime endTimestamp = ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP), timeFormatter);
+        try {
+            DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
+            ZonedDateTime entryTimestamp =
+                    ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP), timeFormatter);
+            ZonedDateTime endTimestamp =
+                    ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP), timeFormatter);
 
-        MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME,
-                Long.toString(ChronoUnit.MILLIS.between(entryTimestamp, endTimestamp)));
+            MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME,
+                    Long.toString(ChronoUnit.MILLIS.between(entryTimestamp, endTimestamp)));
+        } catch (Exception e) {
+            logger.warn("Unable to calculate elapsed time due to error: {}", e.getMessage());
+        }
     }
 
     public void setResponseStatusCode(int code) {
@@ -182,7 +206,7 @@ public class MDCSetup {
     }
 
     public void clearClientMDCs() {
-        MDC.remove(ONAPLogConstants.MDCs.INVOCATION_ID);
+        MDC.remove(ONAPLogConstants.MDCs.CLIENT_INVOCATION_ID);
         MDC.remove(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION);
         MDC.remove(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE);
         MDC.remove(ONAPLogConstants.MDCs.RESPONSE_CODE);
@@ -206,17 +230,30 @@ public class MDCSetup {
     }
 
     public String getProperty(String property) {
-        logger.info("Checking for system property [{}]", property);
         String propertyValue = System.getProperty(property);
         if (propertyValue == null || propertyValue.isEmpty()) {
-            logger.info("System property was null or empty. Checking environment variable for: {}", property);
             propertyValue = System.getenv(property);
             if (propertyValue == null || propertyValue.isEmpty()) {
-                logger.info("Environment variable: {} was null or empty. Returning value: {}", property,
-                        Constants.DefaultValues.UNKNOWN);
                 propertyValue = Constants.DefaultValues.UNKNOWN;
             }
         }
         return propertyValue;
     }
+
+    protected String getBasicAuthUserName(SimpleMap headers) {
+        String encodedAuthorizationValue = headers.get(HttpHeaders.AUTHORIZATION);
+        if (encodedAuthorizationValue != null && encodedAuthorizationValue.startsWith("Basic")) {
+            try {
+                // This will strip the word Basic and single space
+                encodedAuthorizationValue = encodedAuthorizationValue.substring(6);
+                byte[] decodedBytes = Base64.getDecoder().decode(encodedAuthorizationValue);
+                String decodedString = new String(decodedBytes);
+                int idx = decodedString.indexOf(':');
+                return decodedString.substring(0, idx);
+            } catch (IllegalArgumentException e) {
+                logger.error("could not decode basic auth value " + encodedAuthorizationValue, e);
+            }
+        }
+        return null;
+    }
 }