diff options
-rw-r--r-- | extra/docker/clamp/config/org.onap.clamp.keyfile | 32 | ||||
-rw-r--r-- | extra/docker/clamp/config/org.onap.clamp.p12 | bin | 2611 -> 0 bytes | |||
-rw-r--r-- | extra/docker/clamp/config/truststoreONAPall.jks | bin | 2223 -> 0 bytes | |||
-rw-r--r-- | pom.xml | 6 | ||||
-rw-r--r-- | src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java | 4 | ||||
-rw-r--r-- | src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java | 21 | ||||
-rw-r--r-- | src/main/java/org/onap/clamp/clds/service/CldsService.java | 70 | ||||
-rw-r--r-- | src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java | 31 | ||||
-rw-r--r-- | src/main/java/org/onap/clamp/clds/util/LoggingUtils.java | 210 | ||||
-rw-r--r-- | src/main/resources/application-noaaf.properties | 2 | ||||
-rw-r--r-- | src/main/resources/application.properties | 2 | ||||
-rw-r--r-- | src/main/resources/logback-default.xml | 125 | ||||
-rw-r--r-- | src/test/java/org/onap/clamp/clds/it/CldsServiceItCase.java | 12 | ||||
-rw-r--r-- | src/test/java/org/onap/clamp/clds/it/CldsTemplateServiceItCase.java | 14 |
14 files changed, 372 insertions, 157 deletions
diff --git a/extra/docker/clamp/config/org.onap.clamp.keyfile b/extra/docker/clamp/config/org.onap.clamp.keyfile deleted file mode 100644 index 3e131ee77..000000000 --- a/extra/docker/clamp/config/org.onap.clamp.keyfile +++ /dev/null @@ -1,32 +0,0 @@ -Bag Attributes - friendlyName: clamp@clamp.onap.org - localKeyID: 54 69 6D 65 20 31 35 33 30 36 32 36 36 37 38 32 30 31 -Key Attributes: <No Attributes> ------BEGIN PRIVATE KEY----- -MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHXy3ZbCHGPhEe -hvmv44infMBmJv5UAz4cxI6zUJV4mDXyjJxMy0hbjSZx9x6sZSBDXeiWwz6pQafk -VKP06BfBmjvJz0d07pRugI5tczLyJIm8umPJ2igTPjAj/+NuO6Dwt0XeGPVF7otx -0IB96RFFSE8bsTIXrUW9Eg8/oKicjhCbvJnxv49aj6Po23o2+59t2t8SotccRt2A -bkMpAy1wh2qUcRveSkrXnT8IbvxwwgdYM/07OwcQTVIbKPiSDsdxO4bUdL8cAZ/3 -S4ulB33QzNAII2syzWAl6pY53Mjl8tJEIirt2OvNyKNjFYh3m+UcGuhoquVHm1Ev -ZH5DLtWJAgMBAAECggEAIxvywggVxohlkV+plrzV8tC4PQT+4qKTjJNcod0+BTeg -wG7ck3V075Jiw80F3MwOK27dJ7eIUFwcicwR923ryQ81GivjZIcjInaHHmUcAqJG -kzKrof9F8WWRKrXEQkRD6kAMELmKb987NTbHeeTSQsYiEDlbHepIjqwgfU74gmD+ -hJ/w4K9wcAEfbxLvo/Iks45Dx7+ruYNGt48xJ6Or2kyKmOAdmojvK3SlJXv+DzNv -CYzRE577oxw7eTw85XTz2R4BEE4U1PJOJ3J1gcGeI93Sv/nKkr3etEy1Ovqza/iR -zWOVhh/VreJSso4ejlv8U9lwcvYMIAo5P44JVMW/EQKBgQDt8PzTzNU6lewCF00Q -q6LthcCKozICQgzpP4s1IrgFxIYGuLVt2JRSKgZq56IkpH5OAJHducWu5NGmwrya -PU8j44Tuhw4qWT7QB/rx3AezMsOxZyNWOlXIpkis3qy2WL6Jth1/kfcuTpGp0Fqu -ENhdyulPyuTA3OYwQwOMfWPfRQKBgQDWgNC7X0TDd7NIYJOFOtTVAUH7wJJcHOeh -5WlIejKABcnfEaQoDVRVbwS53K1EJtJkV5HqnVbtbdTqduKji4TOVzdEeHPMZF/b -aIZTdtAaWaC37oN/L/TGoY+7n9Hbhp3OpQMeWxNGyUeZLH+DrqSXiSQxFcQ15OY1 -49rE8o3PdQKBgQCj8Q4SVKh6FEAndKyJlujMZQKzwxu6yI2izEB7HO/UMYLy8KM5 -CyeusPv4/p4ORzQrRGM8dTpKdagqETTnxORZYvL9chqFfTY1GbqCmErJ4mlJOzny -uIDQnhmm2kn/3Ydy1QLgGc9InaPpcAB6vGqHvT4h1zbj14/WouW4D9EXTQKBgDpA -xW79UmlbKp8vSyDVd1NZghfillzZpLY83TjHpstJxycDXXdbF1oUSk5Hde6aNGz3 -szLqA997AmWiX65Wh3yaBvJbW+dYIwgs/L3R+HYPfSw2ZBO4bFs9KRGlN5LMnjKu -cYhe539DzmP0x7R1S1Gz9tY1uRGB1lswRAtUa9q5AoGAb7bNvexDAmiHAKe96j0A -tjHAYInJvvont5vdUZipsoY+RbWitsDwv5UsjuRcMkZlMydzQpU0Glc1JcnuJGCf -AEFex2V9xru1CFJQtWxD7qeIqYlYUPLZuoLVNbgtAXBAFyUjcUeXIAEg4Ti2tlvc -86nrgb7/kSLXqHV4/Ykg15s= ------END PRIVATE KEY----- diff --git a/extra/docker/clamp/config/org.onap.clamp.p12 b/extra/docker/clamp/config/org.onap.clamp.p12 Binary files differdeleted file mode 100644 index fd151a94e..000000000 --- a/extra/docker/clamp/config/org.onap.clamp.p12 +++ /dev/null diff --git a/extra/docker/clamp/config/truststoreONAPall.jks b/extra/docker/clamp/config/truststoreONAPall.jks Binary files differdeleted file mode 100644 index 910f9b1ea..000000000 --- a/extra/docker/clamp/config/truststoreONAPall.jks +++ /dev/null @@ -68,6 +68,7 @@ <java.version>1.8</java.version> <eelf.core.version>1.0.0</eelf.core.version> + <logging.analytics.version>1.2.2-SNAPSHOT</logging.analytics.version> <camel.version>2.22.0</camel.version> <springboot.version>2.0.2.RELEASE</springboot.version> @@ -225,6 +226,11 @@ <version>${eelf.core.version}</version> </dependency> <dependency> + <groupId>org.onap.logging-analytics</groupId> + <artifactId>logging-library</artifactId> + <version>${logging.analytics.version}</version> + </dependency> + <dependency> <groupId>org.codehaus.janino</groupId> <artifactId>janino</artifactId> <version>3.0.8</version> diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java b/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java index 918a267d4..bebb6703d 100644 --- a/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java +++ b/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java @@ -88,8 +88,10 @@ public class DcaeHttpConnectionManager { private static String doHttpQuery(URL url, String requestMethod, String payload, String contentType) throws IOException { + LoggingUtils utils = new LoggingUtils (logger); logger.info("Using HTTP URL to contact DCAE:" + url); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection = utils.invoke(connection,"DCAE", requestMethod); connection.setRequestMethod(requestMethod); connection.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId()); if (payload != null && contentType != null) { @@ -106,6 +108,7 @@ public class DcaeHttpConnectionManager { try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String responseStr = IOUtils.toString(reader); logger.info("Response Content: " + responseStr); + utils.invokeReturn(); return responseStr; } } else { @@ -114,6 +117,7 @@ public class DcaeHttpConnectionManager { try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) { String responseStr = IOUtils.toString(reader); logger.error(DCAE_REQUEST_FAILED_LOG + responseStr); + utils.invokeReturn(); throw new BadRequestException(responseStr); } } diff --git a/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java b/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java index 240094e61..4422c92fe 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java +++ b/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java @@ -97,6 +97,7 @@ public class SdcCatalogServices { private static final String SDC_SERVICE_URL_PROPERTY_NAME = "sdc.serviceUrl";
private static final String SDC_INSTANCE_ID_CLAMP = "CLAMP-Tool";
private static final String RESOURCE_URL_PREFIX = "resources";
+ private static final LoggingUtils utils = new LoggingUtils (logger);
@Autowired
private ClampProperties refProp;
@@ -134,7 +135,6 @@ public class SdcCatalogServices { Date startTime = new Date();
String baseUrl = refProp.getStringValue(SDC_SERVICE_URL_PROPERTY_NAME);
String basicAuth = getSdcBasicAuth();
- LoggingUtils.setTargetContext("SDC", "getSdcServicesInformation");
try {
String url = baseUrl;
if (uuid != null && !uuid.isEmpty()) {
@@ -142,6 +142,7 @@ public class SdcCatalogServices { }
URL urlObj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
+ conn = utils.invoke(conn,"SDC", "getSdcServicesInformation");
conn.setRequestProperty(refProp.getStringValue(SDC_INSTANCE_ID_PROPERTY_NAME), SDC_INSTANCE_ID_CLAMP);
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, basicAuth);
conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
@@ -149,8 +150,7 @@ public class SdcCatalogServices { conn.setRequestMethod("GET");
String resp = getResponse(conn);
logger.debug("Services list received from SDC:" + resp);
- // metrics log
- LoggingUtils.setResponseContext("0", "Get sdc services success", this.getClass().getName());
+ utils.invokeReturn();
return resp;
} catch (IOException e) {
LoggingUtils.setResponseContext("900", "Get sdc services failed", this.getClass().getName());
@@ -160,6 +160,7 @@ public class SdcCatalogServices { LoggingUtils.setTimeContext(startTime, new Date());
metricsLogger.info("getSdcServicesInformation complete");
}
+ utils.invokeReturn();
return "";
}
@@ -346,6 +347,7 @@ public class SdcCatalogServices { byte[] postData = formattedSdcReq.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
HttpURLConnection conn = getSdcHttpUrlConnection(userid, postDataLength, url, formattedSdcReq);
+ conn = utils.invoke(conn,"SDC", "uploadArtifact");
try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postData);
}
@@ -358,11 +360,14 @@ public class SdcCatalogServices { String responseStr = getResponse(conn);
if (responseStr != null && requestFailed) {
logger.error("requestFailed - responseStr=" + responseStr);
+ utils.invokeReturn();
throw new BadRequestException(responseStr);
}
+ utils.invokeReturn();
return responseStr;
} catch (IOException e) {
logger.error("Exception when attempting to communicate with SDC", e);
+ utils.invokeReturn();
throw new SdcCommunicationException("Exception when attempting to communicate with SDC", e);
}
}
@@ -797,6 +802,7 @@ public class SdcCatalogServices { String urlReworked = removeUnwantedBracesFromString(url);
URL urlObj = new URL(urlReworked);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
+ conn = utils.invoke(conn,"SDC", "getSdcResources");
String basicAuth = getSdcBasicAuth();
conn.setRequestProperty(refProp.getStringValue(SDC_INSTANCE_ID_PROPERTY_NAME), SDC_INSTANCE_ID_CLAMP);
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, basicAuth);
@@ -807,27 +813,24 @@ public class SdcCatalogServices { logger.info("Sdc resource url - " + urlReworked + " , responseCode=" + responseCode);
try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String response = IOUtils.toString(in);
- LoggingUtils.setResponseContext("0", "Get sdc resources success", this.getClass().getName());
return response;
}
} catch (IOException e) {
- LoggingUtils.setResponseContext("900", "Get sdc resources failed", this.getClass().getName());
LoggingUtils.setErrorContext("900", "Get sdc resources error");
logger.error("Exception occurred during query to SDC", e);
return "";
} catch (DecoderException e) {
- LoggingUtils.setResponseContext("900", "Get sdc resources failed", this.getClass().getName());
LoggingUtils.setErrorContext("900", "Get sdc resources error");
logger.error("Exception when attempting to decode the Hex string", e);
throw new SdcCommunicationException("Exception when attempting to decode the Hex string", e);
} catch (GeneralSecurityException e) {
- LoggingUtils.setResponseContext("900", "Get sdc resources failed", this.getClass().getName());
LoggingUtils.setErrorContext("900", "Get sdc resources error");
logger.error("Exception when attempting to decrypt the encrypted password", e);
throw new SdcCommunicationException("Exception when attempting to decrypt the encrypted password", e);
} finally {
LoggingUtils.setTimeContext(startTime, new Date());
metricsLogger.info("getCldsServicesOrResourcesBasedOnURL completed");
+ utils.invokeReturn();
}
}
@@ -1275,6 +1278,7 @@ public class SdcCatalogServices { url = url + "/" + uploadedArtifactUuid;
URL urlObj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
+ conn = utils.invoke(conn,"SDC", "deleteArtifact");
conn.setDoOutput(true);
conn.setRequestProperty(refProp.getStringValue(SDC_INSTANCE_ID_PROPERTY_NAME), sdcXonapInstanceId);
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, basicAuth);
@@ -1293,12 +1297,15 @@ public class SdcCatalogServices { responseStr = getResponse(conn);
if (responseStr != null && requestFailed) {
logger.error("requestFailed - responseStr=" + responseStr);
+ utils.invokeReturn();
throw new BadRequestException(responseStr);
}
}
+ utils.invokeReturn();
return responseStr;
} catch (IOException | DecoderException | GeneralSecurityException e) {
logger.error("Exception when attempting to communicate with SDC", e);
+ utils.invokeReturn();
throw new SdcCommunicationException("Exception when attempting to communicate with SDC", e);
}
}
diff --git a/src/main/java/org/onap/clamp/clds/service/CldsService.java b/src/main/java/org/onap/clamp/clds/service/CldsService.java index 74c78aeed..2139b3d39 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsService.java @@ -37,6 +37,7 @@ import java.util.List; import java.util.Optional; import java.util.UUID; +import javax.servlet.http.HttpServletRequest; import javax.ws.rs.BadRequestException; import javax.ws.rs.NotAuthorizedException; import javax.xml.transform.TransformerException; @@ -73,6 +74,8 @@ import org.onap.clamp.clds.sdc.controller.installer.CsarInstallerImpl; import org.onap.clamp.clds.transform.XslTransformer; import org.onap.clamp.clds.util.JacksonUtils; import org.onap.clamp.clds.util.LoggingUtils; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.event.Level; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; @@ -89,6 +92,7 @@ public class CldsService extends SecureServiceBase { @Produce(uri = "direct:processSubmit") private CamelProxy camelProxy; protected static final EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger(); + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsService.class); public static final String GLOBAL_PROPERTIES_KEY = "files.globalProperties"; private final String cldsPersmissionTypeCl; @@ -108,8 +112,11 @@ public class CldsService extends SecureServiceBase { private final SdcCatalogServices sdcCatalogServices; private final DcaeDispatcherServices dcaeDispatcherServices; private final DcaeInventoryServices dcaeInventoryServices; + private LoggingUtils util = new LoggingUtils(logger); @Autowired + private HttpServletRequest request; + @Autowired public CldsService(CldsDao cldsDao, XslTransformer cldsBpmnTransformer, ClampProperties refProp, SdcCatalogServices sdcCatalogServices, DcaeDispatcherServices dcaeDispatcherServices, DcaeInventoryServices dcaeInventoryServices, @@ -150,13 +157,13 @@ public class CldsService extends SecureServiceBase { * ClosedLoop in CLDS application. */ public List<CldsMonitoringDetails> getCLDSDetails() { + util.entering(request, "CldsService: GET model details"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: GET model details", getPrincipalName()); List<CldsMonitoringDetails> cldsMonitoringDetailsList = cldsDao.getCLDSMonitoringDetails(); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get cldsDetails success", this.getClass().getName()); auditLogger.info("GET cldsDetails completed"); + util.exiting("200", "Get cldsDetails success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return cldsMonitoringDetailsList; } @@ -165,8 +172,8 @@ public class CldsService extends SecureServiceBase { * is currently installed from pom.xml file 3. User permissions */ public CldsInfo getCldsInfo() { + util.entering(request, "CldsService: GET cldsInfo"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: GET cldsInfo", getPrincipalName()); LoggingUtils.setTimeContext(startTime, new Date()); CldsInfoProvider cldsInfoProvider = new CldsInfoProvider(this); @@ -174,8 +181,8 @@ public class CldsService extends SecureServiceBase { // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get cldsInfo success", this.getClass().getName()); securityLogger.info("GET cldsInfo completed"); + util.exiting("200", "Get cldsInfo success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return cldsInfo; } @@ -188,15 +195,15 @@ public class CldsService extends SecureServiceBase { * @return bpmn xml text - content of bpmn given name */ public String getBpmnXml(String modelName) { + util.entering(request, "CldsService: GET model bpmn"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: GET model bpmn", getPrincipalName()); isAuthorized(permissionReadCl); logger.info("GET bpmnText for modelName={}", modelName); CldsModel model = CldsModel.retrieve(cldsDao, modelName, false); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get model bpmn success", this.getClass().getName()); auditLogger.info("GET model bpmn completed"); + util.exiting("200", "Get model bpmn success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return model.getBpmnText(); } @@ -209,15 +216,15 @@ public class CldsService extends SecureServiceBase { * @return image xml text - content of image given name */ public String getImageXml(String modelName) { + util.entering(request, "CldsService: GET model image"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: GET model image", getPrincipalName()); isAuthorized(permissionReadCl); logger.info("GET imageText for modelName={}", modelName); CldsModel model = CldsModel.retrieve(cldsDao, modelName, false); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get model image success", this.getClass().getName()); auditLogger.info("GET model image completed"); + util.exiting("200", "Get model image success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return model.getImageText(); } @@ -228,8 +235,8 @@ public class CldsService extends SecureServiceBase { * @return clds model - clds model for the given model name */ public CldsModel getModel(String modelName) { + util.entering(request, "CldsService: GET model"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: GET model", getPrincipalName()); isAuthorized(permissionReadCl); logger.debug("GET model for modelName={}", modelName); CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, false); @@ -246,8 +253,8 @@ public class CldsService extends SecureServiceBase { } // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get model success", this.getClass().getName()); auditLogger.info("GET model completed"); + util.exiting("200", "Get model success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return cldsModel; } @@ -257,8 +264,8 @@ public class CldsService extends SecureServiceBase { * @param modelName */ public CldsModel putModel(String modelName, CldsModel cldsModel) { + util.entering(request, "CldsService: PUT model"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: PUT model", getPrincipalName()); isAuthorized(permissionUpdateCl); isAuthorizedForVf(cldsModel); logger.info("PUT model for modelName={}", modelName); @@ -272,8 +279,8 @@ public class CldsService extends SecureServiceBase { cldsModel.save(cldsDao, getUserId()); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Put model success", this.getClass().getName()); auditLogger.info("PUT model completed"); + util.exiting("200", "Put model success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return cldsModel; } @@ -283,15 +290,15 @@ public class CldsService extends SecureServiceBase { * @return model names in JSON */ public List<ValueItem> getModelNames() { + util.entering(request, "CldsService: GET model names"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: GET model names", getPrincipalName()); isAuthorized(permissionReadCl); logger.info("GET list of model names"); List<ValueItem> names = cldsDao.getBpmnNames(); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get model names success", this.getClass().getName()); auditLogger.info("GET model names completed"); + util.exiting("200", "Get model names success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return names; } @@ -329,11 +336,11 @@ public class CldsService extends SecureServiceBase { public ResponseEntity<?> putModelAndProcessAction(String action, String modelName,String test, CldsModel model) throws TransformerException, ParseException { + util.entering(request, "CldsService: Process model action"); Date startTime = new Date(); CldsModel retrievedModel = null; Boolean errorCase = false; try { - LoggingUtils.setRequestContext("CldsService: Process model action", getPrincipalName()); String actionCd = action.toUpperCase(); SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage, cldsPermissionInstance, actionCd); @@ -416,10 +423,10 @@ public class CldsService extends SecureServiceBase { } // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Process model action success", this.getClass().getName()); auditLogger.info("Process model action completed"); } else { logger.error("CldsModel not found in database with modelName: " + modelName); + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "CldsModel not found in database with modelName " + "modelName", Level.INFO, ONAPLogConstants.ResponseStatus.ERROR); return new ResponseEntity<String>("CldsModel not found in database with modelName: \" + modelName", HttpStatus.INTERNAL_SERVER_ERROR); } } catch (Exception e) { @@ -427,8 +434,10 @@ public class CldsService extends SecureServiceBase { logger.error("Exception occured during putModelAndProcessAction", e); } if (errorCase) { + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "putModelAndProcessAction failed", Level.INFO, ONAPLogConstants.ResponseStatus.ERROR); return new ResponseEntity<>(retrievedModel, HttpStatus.INTERNAL_SERVER_ERROR); } + util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return new ResponseEntity<>(retrievedModel, HttpStatus.OK); } @@ -439,8 +448,8 @@ public class CldsService extends SecureServiceBase { * @param dcaeEvent */ public String postDcaeEvent(String test, DcaeEvent dcaeEvent) { + util.entering(request, "CldsService: Post dcae event"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: Post dcae event", getPrincipalName()); String userid = null; // TODO: allow auth checking to be turned off by removing the permission // type property @@ -473,8 +482,8 @@ public class CldsService extends SecureServiceBase { } // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Post dcae event success", this.getClass().getName()); auditLogger.info("Post dcae event completed"); + util.exiting("200", "Post dcae event success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return msgInfo; } @@ -487,8 +496,8 @@ public class CldsService extends SecureServiceBase { * In case of issues with the decoding of the Hex String */ public String getSdcServices() throws GeneralSecurityException, DecoderException { + util.entering(request, "CldsService: GET sdc services"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: GET sdc services", getPrincipalName()); String retStr; try { retStr = createUiServiceFormatJson(sdcCatalogServices.getSdcServicesInformation(null)); @@ -499,8 +508,8 @@ public class CldsService extends SecureServiceBase { logger.info("value of sdcServices : {}", retStr); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get sdc services success", this.getClass().getName()); auditLogger.info("GET sdc services completed"); + util.exiting("200", "Get sdc services success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return retStr; } @@ -528,8 +537,8 @@ public class CldsService extends SecureServiceBase { public String getSdcPropertiesByServiceUUIDForRefresh( String serviceInvariantUUID, Boolean refresh) throws GeneralSecurityException, DecoderException, IOException { + util.entering(request, "CldsService: GET sdc properties by uuid"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: GET sdc properties by uuid", getPrincipalName()); CldsServiceData cldsServiceData = new CldsServiceData(); cldsServiceData.setServiceInvariantUUID(serviceInvariantUUID); if (!Optional.ofNullable(refresh).orElse(false)) { @@ -545,8 +554,8 @@ public class CldsService extends SecureServiceBase { String sdcProperties = sdcCatalogServices.createPropertiesObjectByUUID(cldsServiceData); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get sdc properties by uuid success", this.getClass().getName()); auditLogger.info("GET sdc properties by uuid completed"); + util.exiting("200", "Get sdc properties by uuid success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return sdcProperties; } @@ -720,8 +729,8 @@ public class CldsService extends SecureServiceBase { } public ResponseEntity<CldsModel> deployModel(String modelName, CldsModel model) { + util.entering(request, "CldsService: Deploy model"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: Deploy model", getPrincipalName()); Boolean errorCase = false; try { fillInCldsModel(model); @@ -759,27 +768,29 @@ public class CldsService extends SecureServiceBase { model.save(cldsDao, getUserId()); } else { logger.info("Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus); + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "DeployModel failed", Level.INFO, ONAPLogConstants.ResponseStatus.ERROR); throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus); } logger.info("Deploy model (" + modelName + ") succeeded...Deployment Id is - " + deploymentId); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Deploy model success", this.getClass().getName()); auditLogger.info("Deploy model completed"); } catch (Exception e) { errorCase = true; logger.error("Exception occured during deployModel", e); } if (errorCase) { + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "DeployModel failed", Level.INFO, ONAPLogConstants.ResponseStatus.ERROR); return new ResponseEntity<>(model, HttpStatus.INTERNAL_SERVER_ERROR); } + util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return new ResponseEntity<>(model, HttpStatus.OK); } public ResponseEntity<CldsModel> unDeployModel(String modelName, CldsModel model) { + util.entering(request, "CldsService: Undeploy model"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: Undeploy model", getPrincipalName()); Boolean errorCase = false; try { SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage, @@ -804,21 +815,23 @@ public class CldsService extends SecureServiceBase { model.save(cldsDao, getUserId()); } else { logger.info("Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus); + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "UndeployModel failed", Level.INFO, ONAPLogConstants.ResponseStatus.ERROR); throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus); } logger.info("Undeploy model (" + modelName + ") succeeded."); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Undeploy model success", this.getClass().getName()); auditLogger.info("Undeploy model completed"); } catch (Exception e) { errorCase = true; logger.error("Exception occured during unDeployModel", e); } if (errorCase) { + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "UndeployModel failed", Level.INFO, ONAPLogConstants.ResponseStatus.ERROR); return new ResponseEntity<>(model, HttpStatus.INTERNAL_SERVER_ERROR); } + util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return new ResponseEntity<>(model, HttpStatus.OK); } @@ -858,4 +871,9 @@ public class CldsService extends SecureServiceBase { cldsDao.insEvent(cldsModelName, cldsControlNamePrfx, null, newEvent); } } + + // Created for the integration test + public void setLoggingUtil (LoggingUtils utilP) { + util = utilP; + } }
\ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java index 276670e2b..cca0afded 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java @@ -27,11 +27,14 @@ import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletRequest; import org.onap.clamp.clds.dao.CldsDao; import org.onap.clamp.clds.model.CldsTemplate; import org.onap.clamp.clds.model.ValueItem; import org.onap.clamp.clds.util.LoggingUtils; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.event.Level; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @@ -48,6 +51,8 @@ public class CldsTemplateService extends SecureServiceBase { private String cldsPermissionInstance; private SecureServicePermission permissionReadTemplate; private SecureServicePermission permissionUpdateTemplate; + @Autowired + private HttpServletRequest request; @PostConstruct private final void afterConstruction() { @@ -59,6 +64,7 @@ public class CldsTemplateService extends SecureServiceBase { @Autowired private CldsDao cldsDao; + private LoggingUtils util = new LoggingUtils(logger); /** * REST service that retrieves BPMN for a CLDS template name from the @@ -69,15 +75,15 @@ public class CldsTemplateService extends SecureServiceBase { * @return bpmn xml text - content of bpmn given name */ public String getBpmnTemplate(String templateName) { + util.entering(request, "CldsTemplateService: GET template bpmn"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsTemplateService: GET template bpmn", getPrincipalName()); isAuthorized(permissionReadTemplate); logger.info("GET bpmnText for templateName=" + templateName); CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get template bpmn success", this.getClass().getName()); auditLogger.info("GET template bpmn completed"); + util.exiting("200", "Get template bpmn success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return template.getBpmnText(); } @@ -90,15 +96,15 @@ public class CldsTemplateService extends SecureServiceBase { * @return image xml text - content of image given name */ public String getImageXml(String templateName) { + util.entering(request, "CldsTemplateService: GET template image"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsTemplateService: GET template image", getPrincipalName()); isAuthorized(permissionReadTemplate); logger.info("GET imageText for templateName=" + templateName); CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get template image success", this.getClass().getName()); auditLogger.info("GET template image completed"); + util.exiting("200", "Get template image success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return template.getImageText(); } @@ -109,16 +115,16 @@ public class CldsTemplateService extends SecureServiceBase { * @return clds template - clds template for the given template name */ public CldsTemplate getTemplate(String templateName) { + util.entering(request, "CldsTemplateService: GET template"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsTemplateService: GET template", getPrincipalName()); isAuthorized(permissionReadTemplate); logger.info("GET model for templateName=" + templateName); CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); template.setUserAuthorizedToUpdate(isAuthorizedNoException(permissionUpdateTemplate)); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get template success", this.getClass().getName()); auditLogger.info("GET template completed"); + util.exiting("200", "Get template success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return template; } @@ -130,8 +136,8 @@ public class CldsTemplateService extends SecureServiceBase { * @return The CldsTemplate modified and saved in DB */ public CldsTemplate putTemplate(String templateName, CldsTemplate cldsTemplate) { + util.entering(request, "CldsTemplateService: PUT template"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsTemplateService: PUT template", getPrincipalName()); isAuthorized(permissionUpdateTemplate); logger.info("PUT Template for templateName=" + templateName); logger.info("PUT bpmnText=" + cldsTemplate.getBpmnText()); @@ -141,8 +147,8 @@ public class CldsTemplateService extends SecureServiceBase { cldsTemplate.save(cldsDao, null); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Put template success", this.getClass().getName()); auditLogger.info("PUT template completed"); + util.exiting("200", "Put template success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return cldsTemplate; } @@ -152,15 +158,20 @@ public class CldsTemplateService extends SecureServiceBase { * @return template names in JSON */ public List<ValueItem> getTemplateNames() { + util.entering(request, "CldsTemplateService: GET template names"); Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsTemplateService: GET template names", getPrincipalName()); isAuthorized(permissionReadTemplate); logger.info("GET list of template names"); List<ValueItem> names = cldsDao.getTemplateNames(); // audit log LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Get template names success", this.getClass().getName()); auditLogger.info("GET template names completed"); + util.exiting("200", "Get template names success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); return names; } + + // Created for the integration test + public void setLoggingUtil (LoggingUtils utilP) { + util = utilP; + } } diff --git a/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java b/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java index 71835fa10..a20a70040 100644 --- a/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java +++ b/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java @@ -23,6 +23,10 @@ package org.onap.clamp.clds.util;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
+import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
@@ -30,26 +34,42 @@ import java.text.SimpleDateFormat; import java.util.Date;
import java.util.TimeZone;
import java.util.UUID;
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
import javax.validation.constraints.NotNull;
+import javax.servlet.http.HttpServletRequest;
+
import org.slf4j.MDC;
+import org.slf4j.event.Level;
+import org.springframework.security.core.context.SecurityContextHolder;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
+import org.onap.clamp.clds.service.DefaultUserNameHandler;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
/**
* This class handles the special info that appear in the log, like RequestID,
* time context, ...
*/
-public final class LoggingUtils {
-
- protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoggingUtils.class);
+public class LoggingUtils {
+ protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoggingUtils.class);
private static final DateFormat DATE_FORMAT = createDateFormat();
+ /** String constant for messages <tt>ENTERING</tt>, <tt>EXITING</tt>, etc. */
+ private static final String EMPTY_MESSAGE = "";
+ private static final String INVOCATIONID_OUT = "InvocationIDOut";
+ private static final String TARGET_ENTITY = "TargetEngity";
+
+ /** Logger delegate. */
+ private EELFLogger mLogger;
+ /** Automatic UUID, overrideable per adapter or per invocation. */
+ private static UUID sInstanceUUID = UUID.randomUUID();
/**
- * Private constructor to avoid creating instances of util class.
+ * Constructor
*/
- private LoggingUtils() {
+ public LoggingUtils(final EELFLogger loggerP) {
+ this.mLogger = checkNotNull(loggerP);
}
/**
@@ -65,10 +85,10 @@ public final class LoggingUtils { //Defaulting to HTTP/1.1 protocol
MDC.put("Protocol", "HTTP/1.1");
try {
- MDC.put("ServerFQDN", InetAddress.getLocalHost().getCanonicalHostName());
- MDC.put("ServerIPAddress", InetAddress.getLocalHost().getHostAddress());
+ MDC.put("ServerFQDN", InetAddress.getLocalHost().getCanonicalHostName());
+ MDC.put("ServerIPAddress", InetAddress.getLocalHost().getHostAddress());
} catch (UnknownHostException e) {
- logger.error("Failed to initiate setRequestContext", e);
+ logger.error("Failed to initiate setRequestContext", e);
}
}
@@ -132,12 +152,10 @@ public final class LoggingUtils { * @return A string with the request ID
*/
public static String getRequestId() {
- String requestId;
-
- requestId = (String) MDC.get("RequestID");
+ String requestId = (String) MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
if (requestId == null || requestId.isEmpty()) {
requestId = UUID.randomUUID().toString();
- MDC.put("RequestId", requestId);
+ MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId);
}
return requestId;
}
@@ -147,5 +165,169 @@ public final class LoggingUtils { dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return dateFormat;
}
+
+
+
+ /*********************************************************************************************
+ * Method for ONAP Application Logging Specification v1.2
+ ********************************************************************************************/
+
+ /**
+ * Report <tt>ENTERING</tt> marker.
+ *
+ * @param request non-null incoming request (wrapper).
+ * @return this.
+ */
+ public void entering(HttpServletRequest request, String serviceName) {
+ checkNotNull(request);
+ // Extract MDC values from standard HTTP headers.
+ final String requestID = defaultToUUID(request.getHeader(ONAPLogConstants.Headers.REQUEST_ID));
+ final String invocationID = defaultToUUID(request.getHeader(ONAPLogConstants.Headers.INVOCATION_ID));
+ final String partnerName = defaultToEmpty(request.getHeader(ONAPLogConstants.Headers.PARTNER_NAME));
+
+ // Default the partner name to the user name used to login to clamp
+ if (partnerName.equalsIgnoreCase(EMPTY_MESSAGE)) {
+ MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, new DefaultUserNameHandler().retrieveUserName(SecurityContextHolder.getContext()));
+ }
+
+ // Set standard MDCs. Override this entire method if you want to set
+ // others, OR set them BEFORE or AFTER the invocation of #entering,
+ // depending on where you need them to appear, OR extend the
+ // ServiceDescriptor to add them.
+ MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP,
+ ZonedDateTime.now(ZoneOffset.UTC)
+ .format(DateTimeFormatter.ISO_INSTANT));
+ MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestID);
+ MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationID);
+ MDC.put(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS, defaultToEmpty(request.getRemoteAddr()));
+ MDC.put(ONAPLogConstants.MDCs.SERVER_FQDN, defaultToEmpty(request.getServerName()));
+ MDC.put(ONAPLogConstants.MDCs.INSTANCE_UUID, defaultToEmpty(sInstanceUUID));
+
+ // Default the service name to the requestURI, in the event that
+ // no value has been provided.
+ if (serviceName == null ||
+ serviceName.equalsIgnoreCase(EMPTY_MESSAGE)) {
+ MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI());
+ }
+
+ this.mLogger.info("ENTRY");
+ }
+
+ /**
+ * Report <tt>EXITING</tt> marker.
+ *
+ * @return this.
+ */
+ public void exiting(String code, String descrption, Level severity, ONAPLogConstants.ResponseStatus status) {
+ try {
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, defaultToEmpty(code));
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, defaultToEmpty(descrption));
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_SEVERITY, defaultToEmpty(severity));
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, defaultToEmpty(status));
+ this.mLogger.info("EXIT");
+ }
+ finally {
+ MDC.clear();
+ }
+ }
+
+ /**
+ * Report pending invocation with <tt>INVOKE</tt> marker,
+ * setting standard ONAP logging headers automatically.
+ *
+ * @param builder request builder, for setting headers.
+ * @param sync whether synchronous, nullable.
+ * @return invocation ID to be passed with invocation.
+ */
+ public HttpURLConnection invoke(final HttpURLConnection con, String targetEntity, String targetServiceName) {
+ final String invocationID = UUID.randomUUID().toString();
+
+ // Set standard HTTP headers on (southbound request) builder.
+ con.setRequestProperty(ONAPLogConstants.Headers.REQUEST_ID,
+ defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)));
+ con.setRequestProperty(ONAPLogConstants.Headers.INVOCATION_ID,
+ invocationID);
+ con.setRequestProperty(ONAPLogConstants.Headers.PARTNER_NAME,
+ defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)));
+
+ invokeContext(targetEntity, targetServiceName, invocationID);
+
+ // Log INVOKE*, with the invocationID as the message body.
+ // (We didn't really want this kind of behavior in the standard,
+ // but is it worse than new, single-message MDC?)
+ this.mLogger.info("INVOKE");
+ this.mLogger.info("INVOKE-" + ONAPLogConstants.InvocationMode.SYNCHRONOUS.toString() + "{"+ invocationID +"}");
+ return con;
+ }
+ public void invokeReturn() {
+ // Add the Invoke-return marker and clear the needed MDC
+ this.mLogger.info("INVOKE-RETURN");
+ invokeReturnContext();
+ }
+
+ /**
+ * Dependency-free nullcheck.
+ *
+ * @param in to be checked.
+ * @param <T> argument (and return) type.
+ * @return input arg.
+ */
+ private static <T> T checkNotNull(final T in) {
+ if (in == null) {
+ throw new NullPointerException();
+ }
+ return in;
+ }
+
+ /**
+ * Dependency-free string default.
+ *
+ * @param in to be filtered.
+ * @return input string or null.
+ */
+ private static String defaultToEmpty(final Object in) {
+ if (in == null) {
+ return "";
+ }
+ return in.toString();
+ }
+
+ /**
+ * Dependency-free string default.
+ *
+ * @param in to be filtered.
+ * @return input string or null.
+ */
+ private static String defaultToUUID(final String in) {
+ if (in == null) {
+ return UUID.randomUUID().toString();
+ }
+ return in;
+ }
+
+ /**
+ * Set target related logging variables in thread local data via MDC
+ *
+ * @param targetEntity Target entity (an external/sub component, for ex. "sdc")
+ * @param targetServiceName Target service name (name of API invoked on target)
+ * @param invocationId The invocation ID
+ */
+ private void invokeContext (String targetEntity, String targetServiceName, String invocationID) {
+ MDC.put(TARGET_ENTITY, defaultToEmpty(targetEntity));
+ MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, defaultToEmpty(targetServiceName));
+ MDC.put(INVOCATIONID_OUT, invocationID);
+ MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP,
+ ZonedDateTime.now(ZoneOffset.UTC)
+ .format(DateTimeFormatter.ISO_INSTANT));
+ }
+ /**
+ * Clear target related logging variables in thread local data via MDC
+ *
+ */
+ private void invokeReturnContext () {
+ MDC.remove(TARGET_ENTITY);
+ MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME);
+ MDC.remove(INVOCATIONID_OUT);
+ }
}
diff --git a/src/main/resources/application-noaaf.properties b/src/main/resources/application-noaaf.properties index db817a0ea..35895539b 100644 --- a/src/main/resources/application-noaaf.properties +++ b/src/main/resources/application-noaaf.properties @@ -104,7 +104,7 @@ async.queue.capacity=500 #com.att.eelf.logging.path= com.att.eelf.logging.file=logback-default.xml #The log folder that will be used in logback.xml file -clamp.config.log.path=/var/log/onap +clamp.config.log.path=/var/log/ONAP/clamp clamp.config.files.systemProperties=classpath:/system.properties clamp.config.files.cldsUsers=classpath:/clds/clds-users.json clamp.config.files.globalProperties=classpath:/clds/templates/globalProperties.json diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 24ecc4f98..552efbc7c 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -117,7 +117,7 @@ async.queue.capacity=500 #com.att.eelf.logging.path= com.att.eelf.logging.file=logback-default.xml #The log folder that will be used in logback.xml file -clamp.config.log.path=/var/log/onap +clamp.config.log.path=/var/log/ONAP/clamp clamp.config.files.systemProperties=classpath:/system.properties clamp.config.files.cldsUsers=classpath:/clds/clds-users.json clamp.config.files.globalProperties=classpath:/clds/templates/globalProperties.json diff --git a/src/main/resources/logback-default.xml b/src/main/resources/logback-default.xml index 801e4e471..7e8eba5da 100644 --- a/src/main/resources/logback-default.xml +++ b/src/main/resources/logback-default.xml @@ -1,67 +1,70 @@ <included> <jmxConfigurator /> <!-- Example evaluator filter applied against console appender --> - <appender name="STDOUT" - class="ch.qos.logback.core.ConsoleAppender"> - <!-- filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> - <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter --> - <!-- deny all events with a level below INFO, that is TRACE and DEBUG --> - <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> - <level>INFO</level> - </filter> - <encoder> - <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} - %msg%n - </pattern> - </encoder> - </appender> +<property name="p_tim" value="%d{"yyyy-MM-dd'T'HH:mm:ss.SSSXXX", UTC}"/> + <property name="p_lvl" value="%level"/> + <property name="p_log" value="%logger"/> + <property name="p_mdc" value="%replace(%replace(%mdc){'\t','\\\\t'}){'\n', '\\\\n'}"/> + <property name="p_msg" value="%replace(%replace(%msg){'\t', '\\\\t'}){'\n','\\\\n'}"/> + <property name="p_exc" value="%replace(%replace(%rootException){'\t', '\\\\t'}){'\n','\\\\n'}"/> + <property name="p_mak" value="%replace(%replace(%marker){'\t', '\\\\t'}){'\n','\\\\n'}"/> + <property name="p_thr" value="%thread"/> + <property name="defaultPattern" value="%nopexception${p_tim}\t${p_thr}\t${p_lvl}\t${p_log}\t${p_mdc}\t${p_msg}\t${p_exc}\t${p_mak}\t%n"/> - <appender name="ERROR" - class="ch.qos.logback.core.rolling.RollingFileAppender"> - <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> - <level>INFO</level> - </filter> - <file>${logDirectory}/clamp/error.log</file> - <append>true</append> - <encoder> - <pattern>%date{"yyyy-MM-dd'T'HH:mm:ss,SSSXXX", - UTC}|%X{RequestId}|%.20thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%.-5level|%X{ErrorCode}|%X{ErrorDescription}|%msg%n - </pattern> - </encoder> - <rollingPolicy - class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> - <maxIndex>10</maxIndex> - <FileNamePattern>${logDirectory}/clamp/error.%i.log.zip - </FileNamePattern> - </rollingPolicy> - <triggeringPolicy - class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> - <maxFileSize>10MB</maxFileSize> - </triggeringPolicy> - </appender> + <!-- Example evaluator filter applied against console appender --> + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> + <!-- filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> + <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter --> + <!-- deny all events with a level below INFO, that is TRACE and DEBUG --> + <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> + <level>INFO</level> + </filter> + <encoder> + <pattern>${defaultPattern}</pattern> + </encoder> + </appender> + + <appender name="ERROR" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> + <level>INFO</level> + </filter> + <file>${logDirectory}/error.log</file> + <append>true</append> + <encoder> + <pattern>${defaultPattern}</pattern> + </encoder> + <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> + <fileNamePattern>${outputDirectory}/clamp/error.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern> + <maxFileSize>50MB</maxFileSize> + <maxHistory>30</maxHistory> + <totalSizeCap>10GB</totalSizeCap> + </rollingPolicy> + <triggeringPolicy + class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> + <maxFileSize>10MB</maxFileSize> + </triggeringPolicy> + </appender> + + <appender name="DEBUG" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${logDirectory}/debug.log</file> + <append>true</append> + <encoder> + <pattern>${defaultPattern}</pattern> + </encoder> + <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> + <fileNamePattern>${outputDirectory}/clamp/debug.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern> + <maxFileSize>50MB</maxFileSize> + <maxHistory>30</maxHistory> + <totalSizeCap>10GB</totalSizeCap> + </rollingPolicy> + </appender> - <appender name="DEBUG" - class="ch.qos.logback.core.rolling.RollingFileAppender"> - <file>${logDirectory}/clamp/debug.log</file> - <append>true</append> - <encoder> - <pattern>%date{"yyyy-MM-dd'T'HH:mm:ss,SSSXXX",UTC}|%X{RequestId}|%.20thread|%.-5level|%logger{36}|%msg%n - </pattern> - </encoder> - <rollingPolicy - class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> - <fileNamePattern>${logDirectory}/clamp/debug.%d{yyyy-MM-dd}.%i.log.zip - </fileNamePattern> - <timeBasedFileNamingAndTriggeringPolicy - class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> - <maxFileSize>10MB</maxFileSize> - </timeBasedFileNamingAndTriggeringPolicy> - <maxHistory>5</maxHistory> - </rollingPolicy> - </appender> <appender name="AUDIT" class="ch.qos.logback.core.rolling.RollingFileAppender"> - <file>${logDirectory}/clamp/audit.log</file> + <file>${logDirectory}/audit.log</file> <append>true</append> <encoder> <pattern>%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%.20thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n @@ -70,7 +73,7 @@ <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <maxIndex>10</maxIndex> - <FileNamePattern>${logDirectory}/clamp/audit.%i.log.zip + <FileNamePattern>${logDirectory}/audit.%i.log.zip </FileNamePattern> </rollingPolicy> <triggeringPolicy @@ -86,7 +89,7 @@ <appender name="METRIC" class="ch.qos.logback.core.rolling.RollingFileAppender"> - <file>${logDirectory}/clamp/metric.log</file> + <file>${logDirectory}/metric.log</file> <append>true</append> <encoder> <pattern>%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%.20thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| @@ -95,7 +98,7 @@ <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <maxIndex>10</maxIndex> - <FileNamePattern>${logDirectory}/clamp/metric.%i.log.zip + <FileNamePattern>${logDirectory}/metric.%i.log.zip </FileNamePattern> </rollingPolicy> <triggeringPolicy @@ -112,7 +115,7 @@ <!-- SECURITY related loggers --> <appender name="SECURITY" class="ch.qos.logback.core.rolling.RollingFileAppender"> - <file>${logDirectory}/clamp/security.log</file> + <file>${logDirectory}/security.log</file> <append>true</append> <encoder> <pattern>%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%.20thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n @@ -121,7 +124,7 @@ <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <maxIndex>10</maxIndex> - <FileNamePattern>${logDirectory}/clamp/security.%i.log.zip + <FileNamePattern>${logDirectory}/security.%i.log.zip </FileNamePattern> </rollingPolicy> <triggeringPolicy diff --git a/src/test/java/org/onap/clamp/clds/it/CldsServiceItCase.java b/src/test/java/org/onap/clamp/clds/it/CldsServiceItCase.java index f61a33e3e..8e7e70d89 100644 --- a/src/test/java/org/onap/clamp/clds/it/CldsServiceItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/CldsServiceItCase.java @@ -39,11 +39,14 @@ import java.util.LinkedList; import java.util.List; import java.util.Properties; +import javax.servlet.http.HttpServletRequest; + import org.apache.commons.codec.DecoderException; import org.json.JSONException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Matchers; import org.mockito.Mockito; import org.onap.clamp.clds.dao.CldsDao; import org.onap.clamp.clds.model.CldsHealthCheck; @@ -52,6 +55,7 @@ import org.onap.clamp.clds.model.CldsModel; import org.onap.clamp.clds.model.CldsServiceData; import org.onap.clamp.clds.model.CldsTemplate; import org.onap.clamp.clds.service.CldsService; +import org.onap.clamp.clds.util.LoggingUtils; import org.onap.clamp.clds.util.ResourceFileUtil; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.beans.factory.annotation.Autowired; @@ -62,7 +66,6 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -83,7 +86,7 @@ public class CldsServiceItCase { private CldsDao cldsDao; private Authentication authentication; private List<GrantedAuthority> authList = new LinkedList<GrantedAuthority>(); - + private LoggingUtils util; /** * Setup the variable before the tests execution. * @@ -102,6 +105,10 @@ public class CldsServiceItCase { authList.add(new SimpleGrantedAuthority("permission-type-template|dev|update")); authList.add(new SimpleGrantedAuthority("permission-type-filter-vf|dev|*")); authentication = new UsernamePasswordAuthenticationToken(new User("admin", "", authList), "", authList); + + util = Mockito.mock(LoggingUtils.class); + Mockito.doNothing().when(util).entering(Matchers.any(HttpServletRequest.class), Matchers.any(String.class)); + cldsService.setLoggingUtil(util); } @Test @@ -144,6 +151,7 @@ public class CldsServiceItCase { public void testPutModel() { SecurityContext securityContext = Mockito.mock(SecurityContext.class); Mockito.when(securityContext.getAuthentication()).thenReturn(authentication); + cldsService.setSecurityContext(securityContext); // Add the template first CldsTemplate newTemplate = new CldsTemplate(); diff --git a/src/test/java/org/onap/clamp/clds/it/CldsTemplateServiceItCase.java b/src/test/java/org/onap/clamp/clds/it/CldsTemplateServiceItCase.java index 913e49a45..ba8b0b79d 100644 --- a/src/test/java/org/onap/clamp/clds/it/CldsTemplateServiceItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/CldsTemplateServiceItCase.java @@ -35,14 +35,18 @@ import java.security.Principal; import java.util.LinkedList; import java.util.List; +import javax.servlet.http.HttpServletRequest; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Matchers; import org.mockito.Mockito; import org.onap.clamp.clds.dao.CldsDao; import org.onap.clamp.clds.model.CldsTemplate; import org.onap.clamp.clds.model.ValueItem; import org.onap.clamp.clds.service.CldsTemplateService; +import org.onap.clamp.clds.util.LoggingUtils; import org.onap.clamp.clds.util.ResourceFileUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -74,6 +78,7 @@ public class CldsTemplateServiceItCase { private CldsTemplate cldsTemplate; private Authentication authentication; private List<GrantedAuthority> authList = new LinkedList<GrantedAuthority>(); + private LoggingUtils util; /** * Setup the variable before the tests execution. @@ -89,11 +94,14 @@ public class CldsTemplateServiceItCase { authList.add(new SimpleGrantedAuthority("permission-type-template|dev|update")); authList.add(new SimpleGrantedAuthority("permission-type-filter-vf|dev|*")); authentication = new UsernamePasswordAuthenticationToken(new User("admin", "", authList), "", authList); - + SecurityContext securityContext = Mockito.mock(SecurityContext.class); Mockito.when(securityContext.getAuthentication()).thenReturn(authentication); - - + + util = Mockito.mock(LoggingUtils.class); + Mockito.doNothing().when(util).entering(Matchers.any(HttpServletRequest.class), Matchers.any(String.class)); + cldsTemplateService.setLoggingUtil(util); + cldsTemplateService.setSecurityContext(securityContext); bpmnText = ResourceFileUtil.getResourceAsString("example/dao/bpmn-template.xml"); imageText = ResourceFileUtil.getResourceAsString("example/dao/image-template.xml"); |