diff options
Diffstat (limited to 'adapters')
11 files changed, 709 insertions, 618 deletions
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java index 4479a7f6c2..9212fbcc6c 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java @@ -6,6 +6,8 @@ * ================================================================================ * Copyright (C) 2018 Nokia. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -84,7 +86,6 @@ import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.db.catalog.beans.CloudifyManager; import org.onap.so.db.catalog.beans.HeatTemplateParam; import org.onap.so.logger.MessageEnum; - import org.onap.so.logger.MsoLogger; import org.onap.so.openstack.exceptions.MsoAdapterException; import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; @@ -94,13 +95,15 @@ import org.onap.so.openstack.exceptions.MsoIOException; import org.onap.so.openstack.exceptions.MsoOpenstackException; import org.onap.so.openstack.utils.MsoCommonUtils; import org.onap.so.utils.CryptoUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ - + private static final String CLOUDIFY_ERROR = "CloudifyError"; private static final String CLOUDIFY = "Cloudify"; private static final String CREATE_DEPLOYMENT = "CreateDeployment"; @@ -111,14 +114,14 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Fetch cloud configuration each time (may be cached in CloudConfig class) @Autowired protected CloudConfig cloudConfig; - + @Autowired private Environment environment; - + @Autowired private PoConfig poConfig; - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoCloudifyUtils.class); + private static final Logger logger = LoggerFactory.getLogger(MsoCloudifyUtils.class); // Properties names and variables (with default values) protected String createPollIntervalProp = "org.onap.so.adapters.po.pollInterval"; @@ -126,7 +129,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ protected String createPollIntervalDefault = "15"; private String deletePollIntervalDefault = "15"; - + private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); /** @@ -134,7 +137,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ * cloud location and tenant. The blueprint identifier and parameter map are passed in * as arguments, along with the cloud access credentials. The blueprint should have been * previously uploaded to Cloudify. - * + * * It is expected that parameters have been validated and contain at minimum the required * parameters for the given template with no extra (undefined) parameters.. * @@ -176,17 +179,17 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ if (!cloudSite.isPresent()) { throw new MsoCloudSiteNotFound (cloudSiteId); } - + Cloudify cloudify = getCloudifyClient (cloudSite.get()); - LOGGER.debug ("Ready to Create Deployment (" + deploymentId + ") with input params: " + inputs); + logger.debug("Ready to Create Deployment ({}) with input params: {}", deploymentId, inputs); // Build up the inputs, including: // - from provided "environment" file // - passed in by caller // - special input for cloud-specific Credentials Map<String,Object> expandedInputs = new HashMap<> (inputs); - + String platform = cloudSite.get().getPlatform(); if (platform == null || platform.equals("") || platform.equalsIgnoreCase("OPENSTACK")) { // Create the Cloudify OpenstackConfig with the credentials @@ -197,7 +200,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ AzureConfig azureConfig = getAzureConfig (cloudSite.get(), tenantId); expandedInputs.put("azure_config", azureConfig); } - + // Build up the parameters to create a new deployment CreateDeploymentParams deploymentParams = new CreateDeploymentParams(); deploymentParams.setBlueprintId(blueprintId); @@ -206,8 +209,8 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ Deployment deployment = null; try { CreateDeployment createDeploymentRequest = cloudify.deployments().create(deploymentId, deploymentParams); - LOGGER.debug (createDeploymentRequest.toString()); - + logger.debug(createDeploymentRequest.toString()); + deployment = executeAndRecordCloudifyRequest (createDeploymentRequest); } catch (CloudifyResponseException e) { @@ -220,7 +223,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ throw me; } else { // Convert the CloudifyResponseException to an MsoException - LOGGER.debug("ERROR STATUS = " + e.getStatus() + ",\n" + e.getMessage() + "\n" + e.getLocalizedMessage()); + logger.debug("ERROR STATUS = {},\n{}\n{}", e.getStatus(), e.getMessage(), e.getLocalizedMessage()); MsoException me = cloudifyExceptionToMsoException (e, CREATE_DEPLOYMENT); me.setCategory (MsoExceptionCategory.OPENSTACK); throw me; @@ -246,9 +249,9 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ */ int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault)); int pollTimeout = (timeoutMinutes * 60) + createPollInterval; - + Execution installWorkflow = null; - + try { installWorkflow = executeWorkflow (cloudify, deploymentId, "install", null, pollForCompletion, pollTimeout, createPollInterval); @@ -267,17 +270,19 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // The workflow completed with errors. Must try to back it out. if (!backout) { - LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Deployment installation failed, backout deletion suppressed", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in Deployment Installation, backout suppressed"); - } + logger.warn("{} Deployment installation failed, backout deletion suppressed {} {}", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue(), + "Exception in Deployment Installation, backout suppressed"); + } else { // Poll on delete if we rollback - use same values for now int deletePollInterval = createPollInterval; int deletePollTimeout = pollTimeout; - + try { // Run the uninstall to undo the install Execution uninstallWorkflow = executeWorkflow (cloudify, deploymentId, "uninstall", null, pollForCompletion, deletePollTimeout, deletePollInterval); - + if (uninstallWorkflow.getStatus().equals(TERMINATED)) { // The uninstall completed. Delete the deployment itself @@ -286,16 +291,19 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ } else { // Didn't uninstall successfully. Log this error - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Deployment: Cloudify error rolling back deployment install: " + installWorkflow.getError(), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack: Cloudify error rolling back deployment installation"); - } + logger.error("{} Create Deployment: Cloudify error rolling back deployment install: {} {}", + MessageEnum.RA_CREATE_STACK_ERR, installWorkflow.getError(), + MsoLogger.ErrorCode.BusinessProcesssError.getValue()); + } } catch (Exception e) { // Catch-all for backout errors trying to uninstall/delete // Log this error, and return the original exception - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack: Nested exception rolling back deployment install: " + e, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack: Nested exception rolling back deployment installation"); - } + logger.error("{} Create Stack: Nested exception rolling back deployment install: {}", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue(), e); + } } - + MsoCloudifyException me = new MsoCloudifyException (0, "Workflow Execution Failed", installWorkflow.getError()); me.addContext (CREATE_DEPLOYMENT); @@ -307,18 +315,19 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ if (!backout) { - LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Deployment installation failed, backout deletion suppressed", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in Deployment Installation, backout suppressed"); - } + logger.warn("{} Deployment installation failed, backout deletion suppressed {}", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue()); + } else { // Poll on delete if we rollback - use same values for now int deletePollInterval = createPollInterval; int deletePollTimeout = pollTimeout; - + try { // Run the uninstall to undo the install. // Always try to run it, as it should be idempotent executeWorkflow (cloudify, deploymentId, "uninstall", null, pollForCompletion, deletePollTimeout, deletePollInterval); - + // Delete the deployment itself DeleteDeployment deleteRequest = cloudify.deployments().deleteByName(deploymentId); executeAndRecordCloudifyRequest (deleteRequest); @@ -326,9 +335,9 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ catch (Exception e) { // Catch-all for backout errors trying to uninstall/delete // Log this error, and return the original exception - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack: Nested exception rolling back deployment install: " + e, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack: Nested exception rolling back deployment installation"); - - } + logger.error("{} Create Stack: Nested exception rolling back deployment install: {} ", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue(), e); + } } // Propagate the original exception from Stack Query. @@ -350,14 +359,15 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ DeploymentOutputs deploymentOutputs = null; try { GetDeploymentOutputs queryDeploymentOutputs = cloudify.deployments().outputsById(deploymentId); - LOGGER.debug (queryDeploymentOutputs.toString()); - + logger.debug(queryDeploymentOutputs.toString()); + deploymentOutputs = executeAndRecordCloudifyRequest(queryDeploymentOutputs); } catch (CloudifyConnectException ce) { // Couldn't connect to Cloudify - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "QueryDeploymentOutputs: Cloudify connection failure: " + ce, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "QueryDeploymentOutputs: Cloudify connection failure"); - throw new MsoIOException (ce.getMessage(), ce); + logger.error("{} QueryDeploymentOutputs: Cloudify connection failure: {} ", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue(), ce); + throw new MsoIOException (ce.getMessage(), ce); } catch (CloudifyResponseException re) { if (re.getStatus () == 404) { @@ -370,10 +380,10 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Catch-all throw new MsoAdapterException (e.getMessage(), e); } - + return deploymentOutputs; } - + /* * Execute a workflow on a deployment. Handle polling for completion with timeout. * Return the final Execution object with status. @@ -383,22 +393,22 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ private Execution executeWorkflow (Cloudify cloudify, String deploymentId, String workflowId, Map<String,Object> workflowParams, boolean pollForCompletion, int timeout, int pollInterval) throws MsoCloudifyException { - LOGGER.debug("Executing '" + workflowId + "' workflow on deployment '" + deploymentId + "'"); + logger.debug("Executing '{}' workflow on deployment '{}'", workflowId, deploymentId); StartExecutionParams executeParams = new StartExecutionParams(); executeParams.setWorkflowId(workflowId); executeParams.setDeploymentId(deploymentId); executeParams.setParameters(workflowParams); - + Execution execution = null; String executionId = null; String command = "start"; Exception savedException = null; - + try { StartExecution executionRequest = cloudify.executions().start(executeParams); - LOGGER.debug (executionRequest.toString()); - execution = executeAndRecordCloudifyRequest (executionRequest); + logger.debug(executionRequest.toString()); + execution = executeAndRecordCloudifyRequest (executionRequest); executionId = execution.getId(); if (!pollForCompletion) { @@ -409,27 +419,28 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Enter polling loop boolean timedOut = false; int pollTimeout = timeout; - + String status = execution.getStatus(); - + // Create a reusable cloudify query request GetExecution queryExecution = cloudify.executions().byId(executionId); command = "query"; - + while (!timedOut && !(status.equals(TERMINATED) || status.equals("failed") || status.equals(CANCELLED))) { // workflow is still running; check for timeout if (pollTimeout <= 0) { - LOGGER.debug ("workflow " + execution.getWorkflowId() + " timed out on deployment " + execution.getDeploymentId()); - timedOut = true; + logger.debug("workflow {} timed out on deployment {}", execution.getWorkflowId(), + execution.getDeploymentId()); + timedOut = true; continue; } - + sleep(pollInterval * 1000L); pollTimeout -= pollInterval; - LOGGER.debug("pollTimeout remaining: " + pollTimeout); - + logger.debug("pollTimeout remaining: " + pollTimeout); + execution = queryExecution.execute(); status = execution.getStatus(); } @@ -437,105 +448,112 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Broke the loop. Check again for a terminal state if (status.equals(TERMINATED)){ // Success! - LOGGER.debug ("Workflow '" + workflowId + "' completed successfully on deployment '" + deploymentId + "'"); - return execution; + logger.debug("Workflow '{}' completed successfully on deployment '{}'", workflowId, deploymentId); + return execution; } else if (status.equals("failed")){ // Workflow failed. Log it and return the execution object (don't throw exception here) - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Cloudify workflow failure: " + execution.getError(), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Execute Workflow: Failed: " + execution.getError()); - return execution; + logger.error("{} Cloudify workflow failure: {} {} Execute Workflow: Failed: {}", + MessageEnum.RA_CREATE_STACK_ERR, execution.getError(), + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), execution.getError()); + return execution; } else if (status.equals(CANCELLED)){ // Workflow was cancelled, leaving the deployment in an indeterminate state. Log it and return the execution object (don't throw exception here) - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Cloudify workflow cancelled. Deployment is in an indeterminate state", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Execute Workflow cancelled: " + workflowId); - return execution; + logger.error("{} Cloudify workflow cancelled. Deployment is in an indeterminate state {} {} {}", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue(), + "Execute Workflow cancelled: ", workflowId); + return execution; } else { // Can only get here after a timeout - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Cloudify workflow timeout", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Execute Workflow: Timed Out"); - } + logger.error("{} Cloudify workflow timeout {} Execute Workflow: Timed Out", MessageEnum.RA_CREATE_STACK_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue()); + } } catch (CloudifyConnectException ce) { - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Execute Workflow (" + command + "): Cloudify connection failure: " + ce, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Execute Workflow (" + command + "): Cloudify connection failure"); - savedException = ce; + logger.error("{} {} Execute Workflow ({} {}): Cloudify connection failure {} ", MessageEnum.RA_CREATE_STACK_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), command, ce); + savedException = ce; } catch (CloudifyResponseException re) { - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Execute Workflow (" + command + "): Cloudify response error: " + re, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Execute Workflow (" + command + "): Cloudify error" + re.getMessage()); - savedException = re; + logger.error("{} {} Execute Workflow ({}): Cloudify response error {} ", MessageEnum.RA_CREATE_STACK_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), command, re.getMessage(), re); + savedException = re; } catch (RuntimeException e) { // Catch-all - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Execute Workflow (" + command + "): Unexpected error: " + e, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Execute Workflow (" + command + "): Internal error" + e.getMessage()); - savedException = e; + logger.error("{} {} Execute Workflow ({}): Internal error {}", MessageEnum.RA_CREATE_STACK_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), command, e.getMessage(), e); + savedException = e; } - + // Get to this point ONLY on an error or timeout // The cloudify execution is still running (we've not received a terminal status), // so try to Cancel it. CancelExecutionParams cancelParams = new CancelExecutionParams(); cancelParams.setAction("cancel"); // TODO: Use force_cancel? - + Execution cancelExecution = null; - + try { CancelExecution cancelRequest = cloudify.executions().cancel(executionId, cancelParams); - LOGGER.debug (cancelRequest.toString()); - cancelExecution = cancelRequest.execute(); + logger.debug(cancelRequest.toString()); + cancelExecution = cancelRequest.execute(); // Enter polling loop boolean timedOut = false; int cancelTimeout = timeout; // TODO: For now, just use same timeout - + String status = cancelExecution.getStatus(); - + // Poll for completion. Create a reusable cloudify query request GetExecution queryExecution = cloudify.executions().byId(executionId); - + while (!timedOut && !status.equals(CANCELLED)) { // workflow is still running; check for timeout if (cancelTimeout <= 0) { - LOGGER.debug ("Cancel timeout for workflow " + workflowId + " on deployment " + deploymentId); - timedOut = true; + logger.debug("Cancel timeout for workflow {} on deployment {}", workflowId, deploymentId); + timedOut = true; continue; } - + sleep(pollInterval * 1000L); cancelTimeout -= pollInterval; - LOGGER.debug("pollTimeout remaining: " + cancelTimeout); - - execution = queryExecution.execute(); + logger.debug("pollTimeout remaining: {}", cancelTimeout); + + execution = queryExecution.execute(); status = execution.getStatus(); } // Broke the loop. Check again for a terminal state if (status.equals(CANCELLED)){ // Finished cancelling. Return the original exception - LOGGER.debug ("Cancel workflow " + workflowId + " completed on deployment " + deploymentId); - throw new MsoCloudifyException (-1, "", "", savedException); + logger.debug("Cancel workflow {} completed on deployment {}", workflowId, deploymentId); + throw new MsoCloudifyException (-1, "", "", savedException); } else { // Can only get here after a timeout - LOGGER.debug ("Cancel workflow " + workflowId + " timeout out on deployment " + deploymentId); - MsoCloudifyException exception = new MsoCloudifyException (-1, "", "", savedException); + logger.debug("Cancel workflow {} timeout out on deployment {}", workflowId, deploymentId); + MsoCloudifyException exception = new MsoCloudifyException (-1, "", "", savedException); exception.setPendingWorkflow(true); throw exception; } } catch (Exception e) { // Catch-all. Log the message and throw the original exception -// LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Execute Workflow (" + command + "): Unexpected error: " + e, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Execute Workflow (" + command + "): Internal error" + e.getMessage()); - LOGGER.debug ("Cancel workflow " + workflowId + " failed for deployment " + deploymentId + ": " + e.getMessage()); - MsoCloudifyException exception = new MsoCloudifyException (-1, "", "", savedException); + logger.debug("Cancel workflow {} failed for deployment : {} {}", workflowId, deploymentId, e); + MsoCloudifyException exception = new MsoCloudifyException (-1, "", "", savedException); exception.setPendingWorkflow(true); throw exception; } - } - + } + + - /** * Query for a Cloudify Deployment (by Name). This call will always return a * DeploymentInfo object. If the deployment does not exist, an "empty" DeploymentInfo will be @@ -549,23 +567,23 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ public DeploymentInfo queryDeployment (String cloudSiteId, String tenantId, String deploymentId) throws MsoException { - LOGGER.debug ("Query Cloudify Deployment: " + deploymentId + " in tenant " + tenantId); + logger.debug ("Query Cloudify Deployment: {} in tenant {}", deploymentId, tenantId); // Obtain the cloud site information where we will create the stack Optional<CloudSite> cloudSite = cloudConfig.getCloudSite (cloudSiteId); if (!cloudSite.isPresent()) { throw new MsoCloudSiteNotFound (cloudSiteId); } - + Cloudify cloudify = getCloudifyClient (cloudSite.get()); - + // Build and send the Cloudify request Deployment deployment = new Deployment(); DeploymentOutputs outputs = null; try { GetDeployment queryDeployment = cloudify.deployments().byId(deploymentId); - LOGGER.debug (queryDeployment.toString()); - + logger.debug(queryDeployment.toString()); + // deployment = queryDeployment.execute(); deployment = executeAndRecordCloudifyRequest(queryDeployment); @@ -574,7 +592,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Next look for the latest execution ListExecutions listExecutions = cloudify.executions().listFiltered ("deployment_id=" + deploymentId, "-created_at"); Executions executions = listExecutions.execute(); - + // If no executions, does this give NOT_FOUND or empty set? if (executions.getItems().isEmpty()) { return new DeploymentInfoBuilder() @@ -593,8 +611,9 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ } catch (CloudifyConnectException ce) { // Couldn't connect to Cloudify - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "QueryDeployment: Cloudify connection failure: " + ce, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "QueryDeployment: Cloudify connection failure"); - throw new MsoIOException (ce.getMessage(), ce); + logger.error("{} QueryDeployment: Cloudify connection failure: {} ", MessageEnum.RA_CREATE_STACK_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), ce); + throw new MsoIOException (ce.getMessage(), ce); } catch (CloudifyResponseException re) { if (re.getStatus () == 404) { @@ -618,7 +637,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ throw new MsoAdapterException (e.getMessage(), e); } } - + /** * Delete a Cloudify deployment (by ID). If the deployment is not found, it will be @@ -645,17 +664,17 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ if (!cloudSite.isPresent()) { throw new MsoCloudSiteNotFound (cloudSiteId); } - + Cloudify cloudify = getCloudifyClient (cloudSite.get()); - LOGGER.debug ("Ready to Uninstall/Delete Deployment (" + deploymentId + ")"); + logger.debug ("Ready to Uninstall/Delete Deployment ({})", deploymentId); // Query first to save the trouble if deployment not found Deployment deployment = null; try { GetDeployment queryDeploymentRequest = cloudify.deployments().byId(deploymentId); - LOGGER.debug (queryDeploymentRequest.toString()); - + logger.debug(queryDeploymentRequest.toString()); + deployment = executeAndRecordCloudifyRequest (queryDeploymentRequest); } catch (CloudifyResponseException e) { @@ -664,15 +683,16 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ if (e.getStatus () == 404) { // Deployment doesn't exist. Return a "NOTFOUND" DeploymentInfo object // TODO: Should return NULL? - LOGGER.debug("Deployment requested for deletion does not exist: " + deploymentId); - return new DeploymentInfoBuilder() + logger.debug("Deployment requested for deletion does not exist: {}", deploymentId); + return new DeploymentInfoBuilder() .withId(deploymentId) .withStatus(DeploymentStatus.NOTFOUND) .build(); } else { // Convert the CloudifyResponseException to an MsoOpenstackException - LOGGER.debug("ERROR STATUS = " + e.getStatus() + ",\n" + e.getMessage() + "\n" + e.getLocalizedMessage()); - MsoException me = cloudifyExceptionToMsoException (e, DELETE_DEPLOYMENT); + logger.debug("ERROR STATUS = {}, \n {}\n {}\n {}", e.getStatus(), e.getMessage(), + e.getLocalizedMessage(), e); + MsoException me = cloudifyExceptionToMsoException (e, DELETE_DEPLOYMENT); me.setCategory (MsoExceptionCategory.INTERNAL); throw me; } @@ -696,16 +716,16 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // TODO: No deletePollInterval that I'm aware of. Use the create interval int deletePollInterval = Integer.parseInt(this.environment.getProperty (deletePollIntervalProp, deletePollIntervalDefault)); int pollTimeout = (timeoutMinutes * 60) + deletePollInterval; - + Execution uninstallWorkflow = null; - + try { uninstallWorkflow = executeWorkflow (cloudify, deploymentId, "uninstall", null, true, pollTimeout, deletePollInterval); if (uninstallWorkflow.getStatus().equals(TERMINATED)) { // Successful uninstall. - LOGGER.debug("Uninstall successful for deployment " + deploymentId); - } + logger.debug("Uninstall successful for deployment {}", deploymentId); + } else { // The uninstall workflow completed with an error. Must fail the request, but will // leave the deployment in an indeterminate state, as cloud resources may still exist. @@ -727,11 +747,11 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Next step is to delete the deployment itself try { DeleteDeployment deleteRequest = cloudify.deployments().deleteByName(deploymentId); - LOGGER.debug(deleteRequest.toString()); - + logger.debug(deleteRequest.toString()); + // The delete request returns the deleted deployment deployment = deleteRequest.execute(); - + } catch (CloudifyConnectException ce) { // Failed to delete. Must fail the request, but will leave the (uninstalled) @@ -766,12 +786,12 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ .build(); } - + /** * Check if a blueprint is available for use at a targeted cloud site. * This requires checking the Cloudify Manager which is servicing that * cloud site to see if the specified blueprint has been loaded. - * + * * @param cloudSiteId The cloud site where the blueprint is needed * @param blueprintId The ID for the blueprint in Cloudify */ @@ -783,14 +803,14 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ if (!cloudSite.isPresent()) { throw new MsoCloudSiteNotFound (cloudSiteId); } - + Cloudify cloudify = getCloudifyClient (cloudSite.get()); GetBlueprint getRequest = cloudify.blueprints().getMetadataById(blueprintId); try { Blueprint bp = getRequest.execute(); - LOGGER.debug("Blueprint exists: " + bp.getId()); - return true; + logger.debug("Blueprint exists: {}", bp.getId()); + return true; } catch (CloudifyResponseException ce) { if (ce.getStatus() == 404) { @@ -802,14 +822,14 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ throw e; } } - + /** * Upload a blueprint to the Cloudify Manager that is servicing a Cloud Site. * The blueprint currently must be structured as a single directory with all * of the required files. One of those files is designated the "main file" * for the blueprint. Files are provided as byte arrays, though expect only * text files will be distributed from ASDC and stored by MSO. - * + * * Cloudify requires a single root directory in its blueprint zip files. * The requested blueprint ID will also be used as the directory. * All of the files will be added to this directory in the zip file. @@ -826,16 +846,16 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ if (!cloudSite.isPresent()) { throw new MsoCloudSiteNotFound (cloudSiteId); } - + Cloudify cloudify = getCloudifyClient (cloudSite.get()); boolean blueprintUploaded = uploadBlueprint (cloudify, blueprintId, mainFileName, blueprintFiles); - + if (!blueprintUploaded && failIfExists) { throw new MsoAdapterException ("Blueprint already exists"); } } - + /* * Common method to load a blueprint. May be called from */ @@ -846,20 +866,20 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ GetBlueprint getRequest = cloudify.blueprints().getMetadataById(blueprintId); try { Blueprint bp = getRequest.execute(); - LOGGER.debug("Blueprint " + bp.getId() + " already exists."); - return false; + logger.debug("Blueprint {} already exists.", bp.getId()); + return false; } catch (CloudifyResponseException ce) { if (ce.getStatus() == 404) { // This is the expected result. - LOGGER.debug("Verified that Blueprint doesn't exist yet"); - } else { + logger.debug("Verified that Blueprint doesn't exist yet"); + } else { throw ce; } } catch (Exception e) { throw e; } - + // Create a blueprint ZIP file in memory ByteArrayOutputStream zipBuffer = new ByteArrayOutputStream(); ZipOutputStream zipOut = new ZipOutputStream(zipBuffer); @@ -869,7 +889,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ String rootDir = blueprintId + ((blueprintId.endsWith("/") ? "" : "/")); zipOut.putNextEntry(new ZipEntry (rootDir)); zipOut.closeEntry(); - + for (String fileName : blueprintFiles.keySet()) { ZipEntry ze = new ZipEntry (rootDir + fileName); zipOut.putNextEntry (ze); @@ -881,15 +901,15 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ catch (IOException e) { // Since we're writing to a byte array, this should never happen } - LOGGER.debug ("Blueprint zip file size: " + zipBuffer.size()); - - // Ready to upload the blueprint zip - + logger.debug("Blueprint zip file size: {}", zipBuffer.size()); + + // Ready to upload the blueprint zip + try (InputStream blueprintStream = new ByteArrayInputStream (zipBuffer.toByteArray())) { UploadBlueprint uploadRequest = cloudify.blueprints().uploadFromStream(blueprintId, mainFileName, blueprintStream); Blueprint blueprint = uploadRequest.execute(); - System.out.println("Successfully uploaded blueprint " + blueprint.getId()); - } + logger.debug("Successfully uploaded blueprint {}", blueprint.getId()); + } catch (CloudifyResponseException | CloudifyConnectException e) { throw cloudifyExceptionToMsoException (e, "UPLOAD_BLUEPRINT"); } @@ -903,8 +923,8 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ return true; } - - + + // --------------------------------------------------------------- // PRIVATE FUNCTIONS FOR USE WITHIN THIS CLASS @@ -957,7 +977,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ return executeAndRecordCloudifyRequest (request); } catch (CloudifyResponseException e) { if (e.getStatus () == 404) { - LOGGER.debug ("queryDeployment - not found: " + deploymentId); + logger.debug ("queryDeployment - not found: {}", deploymentId); return null; } else { // Convert the CloudifyResponseException to an MsoCloudifyException @@ -974,34 +994,34 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ Map<String, Object> otherStackOutputs, boolean overWrite) { if (inputs == null || otherStackOutputs == null) return; - + for (Map.Entry<String, Object> entry : otherStackOutputs.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); - + if (value instanceof JsonNode) { // This is a bit of mess - but I think it's the least impacting // let's convert it BACK to a string - then it will get converted back later try { inputs.put(key, this.convertNode((JsonNode) value)); } catch (Exception e) { - LOGGER.debug("WARNING: unable to convert JsonNode output value for "+ key); - //effect here is this value will not have been copied to the inputs - and therefore will error out downstream + logger.debug("WARNING: unable to convert JsonNode output value for {}", key); + //effect here is this value will not have been copied to the inputs - and therefore will error out downstream } } else if (value instanceof java.util.LinkedHashMap) { - LOGGER.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode"); - try { + logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode"); + try { inputs.put(key, JSON_MAPPER.writeValueAsString(value)); } catch (Exception e) { - LOGGER.debug("WARNING: unable to convert LinkedHashMap output value for "+ key); - } + logger.debug("WARNING: unable to convert LinkedHashMap output value for {}", key); + } } else { // just try to cast it - could be an integer or some such try { inputs.put(key, (String) value); } catch (Exception e) { - LOGGER.debug("WARNING: unable to convert output value for "+ key); - //effect here is this value will not have been copied to the inputs - and therefore will error out downstream + logger.debug("WARNING: unable to convert output value for {}", key); + //effect here is this value will not have been copied to the inputs - and therefore will error out downstream } } } @@ -1015,42 +1035,42 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ public Object convertInputValue (String inputValue, HeatTemplateParam templateParam) { String type = templateParam.getParamType(); - LOGGER.debug("Parameter: " + templateParam.getParamName() + " is of type " + type); - - if (type.equalsIgnoreCase("number")) { + logger.debug("Parameter: {} is of type {}", templateParam.getParamName(), type); + + if (type.equalsIgnoreCase("number")) { try { return Integer.valueOf(inputValue); } catch (Exception e) { - LOGGER.debug("Unable to convert " + inputValue + " to an integer!"); - return null; + logger.debug("Unable to convert {} to an integer!", inputValue); + return null; } } else if (type.equalsIgnoreCase("json")) { try { return new ObjectMapper().readTree(inputValue); } catch (Exception e) { - LOGGER.debug("Unable to convert " + inputValue + " to a JsonNode!"); - return null; + logger.debug("Unable to convert {} to a JsonNode!", inputValue); + return null; } } else if (type.equalsIgnoreCase("boolean")) { return new Boolean(inputValue); } - + // Nothing else matched. Return the original string return inputValue; } - - + + private String convertNode(final JsonNode node) { try { final Object obj = JSON_MAPPER.treeToValue(node, Object.class); return JSON_MAPPER.writeValueAsString(obj); } catch (JsonParseException jpe) { - LOGGER.debug("Error converting json to string " + jpe.getMessage()); - } catch (Exception e) { - LOGGER.debug("Error converting json to string " + e.getMessage()); - } + logger.debug("Error converting json to string {}", jpe); + } catch (Exception e) { + logger.debug("Error converting json to string {}", e); + } return "[Error converting json to string]"; } @@ -1061,7 +1081,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ * sub-category that identifies the specific call (using the real * cloudify-client classname of the CloudifyRequest<T> parameter). */ - + protected <T> T executeAndRecordCloudifyRequest (CloudifyRequest <T> request) { @@ -1072,11 +1092,11 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ } else { requestType = request.getClass ().getSimpleName (); } - + int retryDelay = poConfig.getRetryDelay(); int retryCount = poConfig.getRetryCount(); String retryCodes = poConfig.getRetryCodes(); - + // Run the actual command. All exceptions will be propagated while (true) { @@ -1087,19 +1107,23 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ boolean retry = false; if (retryCodes != null ) { int code = e.getStatus(); - LOGGER.debug ("Config values RetryDelay:" + retryDelay + " RetryCount:" + retryCount + " RetryCodes:" + retryCodes + " ResponseCode:" + code); - for (String rCode : retryCodes.split (",")) { + logger.debug("Config values RetryDelay: {} RetryCount:{} RetryCodes:{} ResponseCode:{}", retryDelay, + retryCount, retryCodes, code); + for (String rCode : retryCodes.split (",")) { try { if (retryCount > 0 && code == Integer.parseInt (rCode)) { retryCount--; retry = true; - LOGGER.debug ("CloudifyResponseException ResponseCode:" + code + " request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); - break; + logger.debug( + "CloudifyResponseException ResponseCode:{} request:{} Retry indicated. Attempts remaining:{}", + code, requestType, retryCount); + break; } } catch (NumberFormatException e1) { - LOGGER.error (MessageEnum.RA_CONFIG_EXC, "No retries. Exception in parsing retry code in config:" + rCode, "", "", MsoLogger.ErrorCode.SchemaError, "Exception in parsing retry code in config"); - throw e; + logger.error("{} No retries. Exception in parsing retry code in config:{} {}", + MessageEnum.RA_CONFIG_EXC, rCode, MsoLogger.ErrorCode.SchemaError.getValue()); + throw e; } } } @@ -1115,12 +1139,12 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ if (retryCount > 0) { retryCount--; - LOGGER.debug (" request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); - sleep(retryDelay * 1000L); + logger.debug(" request: {} Retry indicated. Attempts remaining:{}", requestType, retryCount); + sleep(retryDelay * 1000L); } else throw e; - + } } } @@ -1137,16 +1161,18 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ try { // Failed Cloudify calls return an error entity body. CloudifyError error = re.getResponse ().getErrorEntity (CloudifyError.class); - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, CLOUDIFY, "Cloudify Error on " + context + ": " + error.getErrorCode(), CLOUDIFY, "", MsoLogger.ErrorCode.DataError, "Exception - Cloudify Error on " + context); + logger.error("{} {} {} Exception - Cloudify Error on {}: {}", MessageEnum.RA_CONNECTION_EXCEPTION, + CLOUDIFY, MsoLogger.ErrorCode.DataError.getValue(), context, error.getErrorCode()); String fullError = error.getErrorCode() + ": " + error.getMessage(); - LOGGER.debug(fullError); + logger.debug(fullError); me = new MsoCloudifyException (re.getStatus(), re.getMessage(), fullError); } catch (Exception e2) { // Couldn't parse the body as a "CloudifyError". Report the original HTTP error. - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, CLOUDIFY, "HTTP Error on " + context + ": " + re.getStatus() + "," + e.getMessage(), CLOUDIFY, "", MsoLogger.ErrorCode.DataError, "Exception - HTTP Error on " + context, e2); - me = new MsoCloudifyException (re.getStatus (), re.getMessage (), ""); + logger.error("{} {} {} Exception - HTTP Error on {}: {}, {} ", MessageEnum.RA_CONNECTION_EXCEPTION, + CLOUDIFY, MsoLogger.ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2); + me = new MsoCloudifyException (re.getStatus (), re.getMessage (), ""); } // Add the context of the error @@ -1164,8 +1190,9 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ // Generate an alarm for all connection errors. - LOGGER.error(MessageEnum.RA_CONNECTION_EXCEPTION, CLOUDIFY, "Cloudify connection error on " + context + ": " + e, CLOUDIFY, "", MsoLogger.ErrorCode.DataError, "Cloudify connection error on " + context); - } + logger.error("{} {} {} Cloudify connection error on {}: ", MessageEnum.RA_CONNECTION_EXCEPTION, CLOUDIFY, + MsoLogger.ErrorCode.DataError.getValue(), context, e); + } return me; } @@ -1173,17 +1200,17 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ /******************************************************************************* - * + * * Methods (and associated utilities) to implement the VduPlugin interface - * + * *******************************************************************************/ - + /** * VduPlugin interface for instantiate function. - * + * * This one is a bit more complex, in that it will first upload the blueprint if needed, * then create the Cloudify deployment and execute the install workflow. - * + * * This implementation also merges any parameters defined in the ENV file with the other * other input parameters for any undefined parameters). * The basic MsoCloudifyUtils separates blueprint management from deploument actions, @@ -1200,40 +1227,40 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ { String cloudSiteId = cloudInfo.getCloudSiteId(); String tenantId = cloudInfo.getTenantId(); - + // Translate the VDU ModelInformation structure to that which is needed for // creating and uploading a blueprint. Use the model customization UUID as // the blueprint identifier. - + String blueprintId = vduModel.getModelCustomizationUUID(); - + try { - + if (! isBlueprintLoaded (cloudSiteId, blueprintId)) { - LOGGER.debug ("Blueprint " + blueprintId + " is not loaded. Will upload it now."); - + logger.debug("Blueprint {} is not loaded. Will upload it now.", blueprintId); + // Prepare the blueprint inputs. Need the set of blueprint templates and files, // plus the main blueprint name. Map<String,byte[]> blueprintFiles = new HashMap<>(); String mainTemplate = ""; - + // Add all of the blueprint artifacts from the VDU model List<VduArtifact> vduArtifacts = vduModel.getArtifacts(); for (VduArtifact vduArtifact: vduArtifacts) { // Add all artifacts to the blueprint, with one exception. // ENVIRONMENT files will be processed later as additional parameters. - + ArtifactType artifactType = vduArtifact.getType(); if (artifactType != ArtifactType.ENVIRONMENT) { blueprintFiles.put(vduArtifact.getName(), vduArtifact.getContent()); - + if (artifactType == ArtifactType.MAIN_TEMPLATE) { mainTemplate = vduArtifact.getName(); } } } - + // Upload the blueprint package uploadBlueprint(cloudSiteId, blueprintId, mainTemplate, blueprintFiles, false); } @@ -1241,12 +1268,12 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ catch (Exception e) { throw new VduException ("CloudifyUtils (instantiateVDU): blueprint Exception", e); } - - + + // Next, create and install a new deployment based on the blueprint. // For Cloudify, the deploymentId is specified by the client. Just use the instance name // as the ID. - + try { // Query the Cloudify Deployment object and populate a VduInstance DeploymentInfo deployment = createAndInstallDeployment (cloudSiteId, @@ -1257,15 +1284,15 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ true, // (poll for completion) vduModel.getTimeoutMinutes(), rollbackOnFailure); - + return deploymentInfoToVduInstance(deployment); } catch (Exception e) { throw new VduException ("CloudifyUtils (instantiateVDU): Create-and-install-deployment Exception", e); } } - - + + /** * VduPlugin interface for query function. */ @@ -1275,19 +1302,19 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ { String cloudSiteId = cloudInfo.getCloudSiteId(); String tenantId = cloudInfo.getTenantId(); - + try { // Query the Cloudify Deployment object and populate a VduInstance DeploymentInfo deployment = queryDeployment (cloudSiteId, tenantId, instanceId); - + return deploymentInfoToVduInstance(deployment); } catch (Exception e) { throw new VduException ("Query VDU Exception", e); } } - - + + /** * VduPlugin interface for delete function. */ @@ -1297,11 +1324,11 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ { String cloudSiteId = cloudInfo.getCloudSiteId(); String tenantId = cloudInfo.getTenantId(); - + try { // Uninstall and delete the Cloudify Deployment DeploymentInfo deployment = uninstallAndDeleteDeployment (cloudSiteId, tenantId, instanceId, timeoutMinutes); - + // Populate a VduInstance based on the deleted Cloudify Deployment object return deploymentInfoToVduInstance(deployment); } @@ -1309,14 +1336,14 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ throw new VduException ("Delete VDU Exception", e); } } - - + + /** * VduPlugin interface for update function. - * + * * Update is currently not supported in the MsoCloudifyUtils implementation. * Just return a VduException. - * + * */ @Override public VduInstance updateVdu ( @@ -1329,37 +1356,37 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ { throw new VduException ("CloudifyUtils: updateVDU interface not supported"); } - - + + /* * Convert the local DeploymentInfo object (Cloudify-specific) to a generic VduInstance object */ protected VduInstance deploymentInfoToVduInstance (DeploymentInfo deployment) { VduInstance vduInstance = new VduInstance(); - + // only one ID in Cloudify, use for both VDU name and ID vduInstance.setVduInstanceId(deployment.getId()); vduInstance.setVduInstanceName(deployment.getId()); - + // Copy inputs and outputs vduInstance.setInputs(deployment.getInputs()); vduInstance.setOutputs(deployment.getOutputs()); - + // Translate the status elements vduInstance.setStatus(deploymentStatusToVduStatus (deployment)); - + return vduInstance; } - + protected VduStatus deploymentStatusToVduStatus (DeploymentInfo deployment) { VduStatus vduStatus = new VduStatus(); - + // Determine the status based on last action & status // DeploymentInfo object should be enhanced to report a better status internally. DeploymentStatus status = deployment.getStatus(); - + if (status == null) { vduStatus.setState(VduStateType.UNKNOWN); } @@ -1384,13 +1411,13 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ } else { vduStatus.setState(VduStateType.UNKNOWN); } - + vduStatus.setErrorMessage(deployment.getErrorMessage()); vduStatus.setLastAction(new PluginAction(deployment.getLastAction(), deployment.getActionStatus(), deployment.getErrorMessage())); - + return vduStatus; } - + /* * Return an OpenstackConfig object as expected by Cloudify Openstack Plug-in. * Base the values on the CloudSite definition. @@ -1404,7 +1431,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ openstackConfig.setTenantName (tenantId); return openstackConfig; } - + /* * Return an Azure object as expected by Cloudify Azure Plug-in. * Base the values on the CloudSite definition. @@ -1418,13 +1445,13 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin{ azureConfig.setClientSecret (cloudSite.getIdentityService().getMsoPass()); return azureConfig; } - + private void sleep(long time) { try { Thread.sleep(time); } catch (InterruptedException e) { - LOGGER.debug("Thread interrupted while sleeping!", e); - Thread.currentThread().interrupt(); + logger.debug("Thread interrupted while sleeping!", e); + Thread.currentThread().interrupt(); } } } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java index 75b9fc94f6..8cd6b0f65e 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java @@ -5,6 +5,8 @@ * Copyright (C) 2018 Intel Corp. All rights reserved. * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -22,38 +24,37 @@ package org.onap.so.openstack.utils; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.woorea.openstack.base.client.OpenStackBaseException; +import com.woorea.openstack.base.client.OpenStackConnectException; +import com.woorea.openstack.base.client.OpenStackRequest; +import com.woorea.openstack.base.client.OpenStackResponseException; +import com.woorea.openstack.heat.model.CreateStackParam; +import com.woorea.openstack.heat.model.Explanation; +import com.woorea.openstack.keystone.model.Error; +import com.woorea.openstack.quantum.model.NeutronError; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; - import org.onap.so.config.beans.PoConfig; import org.onap.so.logger.MessageEnum; - import org.onap.so.logger.MsoLogger; import org.onap.so.openstack.exceptions.MsoAdapterException; import org.onap.so.openstack.exceptions.MsoException; import org.onap.so.openstack.exceptions.MsoExceptionCategory; import org.onap.so.openstack.exceptions.MsoIOException; import org.onap.so.openstack.exceptions.MsoOpenstackException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.woorea.openstack.base.client.OpenStackBaseException; -import com.woorea.openstack.base.client.OpenStackConnectException; -import com.woorea.openstack.base.client.OpenStackRequest; -import com.woorea.openstack.base.client.OpenStackResponseException; -import com.woorea.openstack.heat.model.CreateStackParam; -import com.woorea.openstack.heat.model.Explanation; -import com.woorea.openstack.keystone.model.Error; -import com.woorea.openstack.quantum.model.NeutronError; - @Component("CommonUtils") public class MsoCommonUtils { - private static MsoLogger logger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, MsoCommonUtils.class); + private static Logger logger = LoggerFactory.getLogger(MsoCommonUtils.class); @Autowired @@ -92,19 +93,24 @@ public class MsoCommonUtils { boolean retry = false; if (retryCodes != null ) { int code = e.getStatus(); - logger.debug ("Config values RetryDelay:" + retryDelay + " RetryCount:" + retryCount + " RetryCodes:" + retryCodes + " ResponseCode:" + code); - for (String rCode : retryCodes.split (",")) { + logger.debug("Config values RetryDelay:{} RetryCount:{} RetryCodes:{} ResponseCode:{}", retryDelay, + retryCount, retryCodes, code); + for (String rCode : retryCodes.split (",")) { try { if (retryCount > 0 && code == Integer.parseInt (rCode)) { retryCount--; retry = true; - logger.debug ("OpenStackResponseException ResponseCode:" + code + " request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); - break; + logger.debug( + "OpenStackResponseException ResponseCode: {} request:{} Retry indicated. Attempts remaining:{}", + code, requestType, retryCount); + break; } } catch (NumberFormatException e1) { - logger.error (MessageEnum.RA_CONFIG_EXC, "No retries. Exception in parsing retry code in config:" + rCode, "", "", MsoLogger.ErrorCode.SchemaError, "Exception in parsing retry code in config"); - throw e; + logger.error("{} No retries. Exception in parsing retry code in config:{} {} {}", + MessageEnum.RA_CONFIG_EXC, rCode, MsoLogger.ErrorCode.SchemaError.getValue(), + "Exception in parsing retry code in config"); + throw e; } } } @@ -125,7 +131,7 @@ public class MsoCommonUtils { if (retryCount > 0) { retryCount--; - logger.debug (" request:" + requestType + " Retry indicated. Attempts remaining:" + retryCount); + logger.debug (" request: {} Retry indicated. Attempts remaining:{}", requestType, retryCount); try { Thread.sleep (retryDelay * 1000L); } catch (InterruptedException e1) { @@ -153,12 +159,14 @@ public class MsoCommonUtils { try { // Failed Keystone calls return an Error entity body. Error error = re.getResponse ().getErrorEntity (Error.class); - logger.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack Keystone Error on " + context + ": " + error, "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack Keystone Error on " + context); - me = new MsoOpenstackException (error.getCode (), error.getTitle (), error.getMessage ()); + logger.error("{} {} Openstack Keystone Error on {}: {}", + MessageEnum.RA_CONNECTION_EXCEPTION, MsoLogger.ErrorCode.DataError.getValue(), context, error); + me = new MsoOpenstackException (error.getCode (), error.getTitle (), error.getMessage ()); } catch (Exception e2) { // Can't parse the body as an "Error". Report the HTTP error - logger.error (MessageEnum.RA_CONNECTION_EXCEPTION, "HTTP Error on " + context + ": " + re.getStatus() + "," + re.getMessage(), "Openstack", "", MsoLogger.ErrorCode.DataError, "HTTP Error on " + context, e2); - me = new MsoOpenstackException (re.getStatus (), re.getMessage (), ""); + logger.error("{} {} HTTP Error on {}: {}, {}", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), context, re.getStatus(), re.getMessage(), e2); + me = new MsoOpenstackException (re.getStatus (), re.getMessage (), ""); } // Add the context of the error @@ -175,8 +183,8 @@ public class MsoCommonUtils { me.addContext (context); // Generate an alarm for all connection errors. - logger.error(MessageEnum.RA_GENERAL_EXCEPTION_ARG, "Openstack Keystone connection error on " + context + ": " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack Keystone connection error on " + context); - + logger.error("{} {} Openstack Keystone connection error on {}: ", MessageEnum.RA_GENERAL_EXCEPTION_ARG, + MsoLogger.ErrorCode.DataError.getValue(), context, e); } return me; @@ -195,7 +203,8 @@ public class MsoCommonUtils { try { // Failed Heat calls return an Explanation entity body. Explanation explanation = re.getResponse ().getErrorEntity (Explanation.class); - logger.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Error on " + context + ": " + explanation.toString(), "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception - Openstack Error on " + context); + logger.error("{} {} Exception - Openstack Error on {} : {}", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), context, explanation.toString()); String fullError = explanation.getExplanation() + ", error.type=" + explanation.getError().getType() + ", error.message=" + explanation.getError().getMessage(); logger.debug(fullError); me = new MsoOpenstackException (explanation.getCode (), @@ -204,8 +213,9 @@ public class MsoCommonUtils { fullError); } catch (Exception e2) { // Couldn't parse the body as an "Explanation". Report the original HTTP error. - logger.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "HTTP Error on " + context + ": " + re.getStatus() + "," + e.getMessage(), "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception - HTTP Error on " + context, e2); - me = new MsoOpenstackException (re.getStatus (), re.getMessage (), ""); + logger.error("{} {} Exception - HTTP Error on {}: {}, ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2); + me = new MsoOpenstackException (re.getStatus (), re.getMessage (), ""); } // Add the context of the error @@ -223,8 +233,9 @@ public class MsoCommonUtils { // Generate an alarm for all connection errors. - logger.error(MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Heat connection error on " + context + ": " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack Heat connection error on " + context); - } + logger.error("{} {} Openstack Heat connection error on {}: ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), context, e); + } return me; } @@ -242,12 +253,14 @@ public class MsoCommonUtils { try { // Failed Neutron calls return an NeutronError entity body NeutronError error = re.getResponse ().getErrorEntity (NeutronError.class); - logger.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Neutron Error on " + context + ": " + error, "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack Neutron Error on " + context); - me = new MsoOpenstackException (re.getStatus (), error.getType (), error.getMessage ()); + logger.error("{} {} Openstack Neutron Error on {} {}", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), context, error); + me = new MsoOpenstackException (re.getStatus (), error.getType (), error.getMessage ()); } catch (Exception e2) { // Couldn't parse body as a NeutronError. Report the HTTP error. - logger.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "HTTP Error on " + context + ": " + re.getStatus() + "," + e.getMessage(), "Openstack", "", MsoLogger.ErrorCode.DataError, "Openstack HTTP Error on " + context, e2); - me = new MsoOpenstackException (re.getStatus (), re.getMessage (), null); + logger.error("{} {} Openstack HTTP Error on {}: {}, {}", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), context, re.getStatus(), e.getMessage(), e2); + me = new MsoOpenstackException (re.getStatus (), re.getMessage (), null); } // Add the context of the error @@ -265,8 +278,9 @@ public class MsoCommonUtils { // Generate an alarm for all connection errors. - logger.error(MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Neutron Connection error on "+ context + ": " + e, "OpenStack", "", MsoLogger.ErrorCode.DataError, "Openstack Neutron Connection error on "+ context); - } + logger.error("{} {} Openstack Neutron Connection error on {}: ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), context, e); + } return me; } @@ -283,8 +297,8 @@ public class MsoCommonUtils { me.setCategory (MsoExceptionCategory.INTERNAL); // Always generate an alarm for internal exceptions - logger.error(MessageEnum.RA_GENERAL_EXCEPTION_ARG, "An exception occured on "+ context + ": " + e, "OpenStack", "", MsoLogger.ErrorCode.DataError, "An exception occured on "+ context); - + logger.error("{} {} An exception occured on {}: ", MessageEnum.RA_GENERAL_EXCEPTION_ARG, + MsoLogger.ErrorCode.DataError.getValue(), context, e); return me; } @@ -295,8 +309,8 @@ public class MsoCommonUtils { me.setCategory (MsoExceptionCategory.INTERNAL); // Always generate an alarm for internal exceptions - logger.error(MessageEnum.RA_GENERAL_EXCEPTION_ARG, "An exception occured on "+ context + ": " + e, "OpenStack", "", MsoLogger.ErrorCode.DataError, "An exception occured on "+ context); - + logger.error("{} {} An exception occured on {}: ", MessageEnum.RA_GENERAL_EXCEPTION_ARG, + MsoLogger.ErrorCode.DataError.getValue(), context, e); return me; } @@ -321,7 +335,7 @@ public class MsoCommonUtils { haveEnvtVariable = false; logger.debug ("createStackParam called with no environment variable"); } else { - logger.debug ("createStackParam called with an environment variable: " + environment); + logger.debug("createStackParam called with an environment variable: {}", environment); } boolean haveFiles = true; @@ -329,7 +343,7 @@ public class MsoCommonUtils { haveFiles = false; logger.debug ("createStackParam called with no files / child template ids"); } else { - logger.debug ("createStackParam called with " + files.size () + " files / child template ids"); + logger.debug("createStackParam called with {} files / child template ids", files.size()); } boolean haveHeatFiles = true; @@ -337,7 +351,7 @@ public class MsoCommonUtils { haveHeatFiles = false; logger.debug ("createStackParam called with no heatFiles"); } else { - logger.debug ("createStackParam called with " + heatFiles.size () + " heatFiles"); + logger.debug("createStackParam called with {} heatFiles", heatFiles.size()); } //force entire stackInput object to generic Map<String, Object> for openstack compatibility @@ -359,8 +373,8 @@ public class MsoCommonUtils { stack.setDisableRollback (true); // TJM New for PO Adapter - add envt variable if (haveEnvtVariable) { - logger.debug ("Found an environment variable - value: " + environment); - stack.setEnvironment (environment); + logger.debug("Found an environment variable - value: {}", environment); + stack.setEnvironment (environment); } // Now handle nested templates or get_files - have to combine if we have both // as they're both treated as "files:" on the stack. @@ -396,11 +410,11 @@ public class MsoCommonUtils { inputs.put(entry.getKey(), entry.getValue()); } } - logger.debug("stack request:" + stack.toString()); - } catch (Exception e) { + logger.debug("stack request: {}", stack.toString()); + } catch (Exception e) { // that's okay - this is a nice-to-have - logger.debug("(had an issue printing nicely formatted request to debuglog) " + e.getMessage()); - } + logger.debug("(had an issue printing nicely formatted request to debuglog) {}", e.getMessage()); + } return stack; } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java index c95e62dad0..4b53006c21 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java @@ -5,6 +5,8 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -22,17 +24,16 @@ package org.onap.so.openstack.utils; - import java.util.ArrayList; import java.util.HashSet; import java.util.Set; - import org.onap.so.db.catalog.beans.HeatTemplateParam; -import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class MsoHeatEnvironmentEntry { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoHeatEnvironmentEntry.class); + private static final Logger logger = LoggerFactory.getLogger(MsoHeatEnvironmentEntry.class); private Set<MsoHeatEnvironmentParameter> parameters = null; private Set<MsoHeatEnvironmentResource> resources = null; @@ -66,8 +67,8 @@ public class MsoHeatEnvironmentEntry { this.resourceRegistryEntryRaw = sb; } } catch (Exception e) { - LOGGER.debug("Exception:", e); - this.valid = false; + logger.debug("Exception:", e); + this.valid = false; this.errorString = e.getMessage(); //e.printStackTrace(); } @@ -249,7 +250,7 @@ public class MsoHeatEnvironmentEntry { } } } catch (Exception e) { - LOGGER.debug("Exception:", e); + logger.debug("Exception:", e); this.errorString = e.getMessage(); //e.printStackTrace(); } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java index c174b58f95..56bab31880 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentResource.java @@ -5,6 +5,8 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,11 +23,12 @@ package org.onap.so.openstack.utils; -import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class MsoHeatEnvironmentResource { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoHeatEnvironmentResource.class); + private static final Logger logger = LoggerFactory.getLogger(MsoHeatEnvironmentResource.class); private String name; private String value; @@ -87,8 +90,8 @@ public class MsoHeatEnvironmentResource { try { result = this.name.hashCode(); } catch (Exception e) { - LOGGER.debug("Exception:", e); - } + logger.debug("Exception:", e); + } return result; } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java index ddc725188f..efc232e79e 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java @@ -23,6 +23,21 @@ package org.onap.so.openstack.utils; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.woorea.openstack.base.client.OpenStackConnectException; +import com.woorea.openstack.base.client.OpenStackRequest; +import com.woorea.openstack.base.client.OpenStackResponseException; +import com.woorea.openstack.heat.Heat; +import com.woorea.openstack.heat.model.CreateStackParam; +import com.woorea.openstack.heat.model.Resources; +import com.woorea.openstack.heat.model.Stack; +import com.woorea.openstack.heat.model.Stack.Output; +import com.woorea.openstack.heat.model.Stacks; +import com.woorea.openstack.keystone.Keystone; +import com.woorea.openstack.keystone.model.Access; +import com.woorea.openstack.keystone.model.Authentication; +import com.woorea.openstack.keystone.utils.KeystoneUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; @@ -31,7 +46,6 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; - import org.onap.so.adapters.vdu.CloudInfo; import org.onap.so.adapters.vdu.PluginAction; import org.onap.so.adapters.vdu.VduArtifact; @@ -53,7 +67,6 @@ import org.onap.so.db.catalog.beans.HeatTemplate; import org.onap.so.db.catalog.beans.HeatTemplateParam; import org.onap.so.db.catalog.beans.ServerType; import org.onap.so.logger.MessageEnum; - import org.onap.so.logger.MsoLogger; import org.onap.so.openstack.beans.HeatStatus; import org.onap.so.openstack.beans.StackInfo; @@ -66,27 +79,13 @@ import org.onap.so.openstack.exceptions.MsoStackAlreadyExists; import org.onap.so.openstack.exceptions.MsoTenantNotFound; import org.onap.so.openstack.mappers.StackInfoMapper; import org.onap.so.utils.CryptoUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.woorea.openstack.base.client.OpenStackConnectException; -import com.woorea.openstack.base.client.OpenStackRequest; -import com.woorea.openstack.base.client.OpenStackResponseException; -import com.woorea.openstack.heat.Heat; -import com.woorea.openstack.heat.model.CreateStackParam; -import com.woorea.openstack.heat.model.Resources; -import com.woorea.openstack.heat.model.Stack; -import com.woorea.openstack.heat.model.Stack.Output; -import com.woorea.openstack.heat.model.Stacks; -import com.woorea.openstack.keystone.Keystone; -import com.woorea.openstack.keystone.model.Access; -import com.woorea.openstack.keystone.model.Authentication; -import com.woorea.openstack.keystone.utils.KeystoneUtils; - @Primary @Component public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ @@ -117,7 +116,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ @Autowired private KeystoneV3Authentication keystoneV3Authentication; - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoHeatUtils.class); + private static final Logger logger = LoggerFactory.getLogger(MsoHeatUtils.class); // Properties names and variables (with default values) protected String createPollIntervalProp = "org.onap.so.adapters.po.pollInterval"; @@ -292,13 +291,13 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ // Obtain the cloud site information where we will create the stack CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( () -> new MsoCloudSiteNotFound(cloudSiteId)); - LOGGER.debug("Found: " + cloudSite.toString()); + logger.debug("Found: {}", cloudSite); // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId) // This could throw MsoTenantNotFound or MsoOpenstackException (both propagated) Heat heatClient = getHeatClient (cloudSite, tenantId); - LOGGER.debug("Found: " + heatClient.toString()); + logger.debug("Found: {}", heatClient); - LOGGER.debug ("Ready to Create Stack (" + heatTemplate + ") with input params: " + stackInputs); + logger.debug ("Ready to Create Stack ({}) with input params: {}", heatTemplate, stackInputs); Stack heatStack = null; try { @@ -313,7 +312,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ me.addContext (CREATE_STACK); throw me; } else { - LOGGER.debug("ERROR STATUS = " + e.getStatus() + ",\n" + e.getMessage() + "\n" + e.getLocalizedMessage()); + logger.debug("ERROR STATUS = {},\n{}\n{}", e.getStatus(), e.getMessage(), e.getLocalizedMessage()); throw heatExceptionToMsoException (e, CREATE_STACK); } } catch (OpenStackConnectException e) { @@ -333,7 +332,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } else { // Get initial status, since it will have been null after the create. heatStack = queryHeatStack (heatClient, canonicalName); - LOGGER.debug (heatStack.getStackStatus ()); + logger.debug (heatStack.getStackStatus ()); } return new StackInfoMapper(heatStack).map(); } @@ -347,28 +346,30 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ int deletePollTimeout = pollTimeout; boolean createTimedOut = false; StringBuilder stackErrorStatusReason = new StringBuilder(""); - LOGGER.debug("createPollInterval=" + createPollInterval + ", pollTimeout=" + pollTimeout); + logger.debug("createPollInterval={}, pollTimeout={}", createPollInterval, pollTimeout); while (true) { try { heatStack = queryHeatStack (heatClient, canonicalName); - LOGGER.debug (heatStack.getStackStatus () + " (" + canonicalName + ")"); - try { - LOGGER.debug("Current stack " + this.getOutputsAsStringBuilder(heatStack).toString()); - } catch (Exception e) { - LOGGER.debug("an error occurred trying to print out the current outputs of the stack", e); + logger.debug("{} ({})", heatStack.getStackStatus(), canonicalName); + try { + logger.debug("Current stack {}", this.getOutputsAsStringBuilder(heatStack).toString()); + } catch (Exception e) { + logger.debug("an error occurred trying to print out the current outputs of the stack", e); } if ("CREATE_IN_PROGRESS".equals (heatStack.getStackStatus ())) { if (pollTimeout <= 0) { - LOGGER.error (MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, heatStack.getStackStatus (), "", "", MsoLogger.ErrorCode.AvailabilityError, "Create stack timeout"); - createTimedOut = true; + logger.error("{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Create stack timeout", + MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, + heatStack.getStackStatus(), MsoLogger.ErrorCode.AvailabilityError.getValue()); + createTimedOut = true; break; } sleep(createPollInterval * 1000L); pollTimeout -= createPollInterval; - LOGGER.debug("pollTimeout remaining: " + pollTimeout); - } else { + logger.debug("pollTimeout remaining: {}", pollTimeout); + } else { stackErrorStatusReason.append("Stack error (" + heatStack.getStackStatus() + "): " + heatStack.getStackStatusReason()); break; } @@ -377,33 +378,38 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ // Try to roll back the stack if (!backout) { - LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, stack deletion suppressed", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in Create Stack, stack deletion suppressed"); - } + logger.warn("{} Exception in Create Stack, stack deletion suppressed {}", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue()); + } else { try { - LOGGER.debug("Create Stack error - unable to query for stack status - attempting to delete stack: " + canonicalName + " - This will likely fail and/or we won't be able to query to see if delete worked"); - OpenStackRequest <Void> request = heatClient.getStacks ().deleteByName (canonicalName); + logger.debug( + "Create Stack error - unable to query for stack status - attempting to delete stack: {}" + + " - This will likely fail and/or we won't be able to query to see if delete worked", + canonicalName); + OpenStackRequest <Void> request = heatClient.getStacks ().deleteByName (canonicalName); executeAndRecordOpenstackRequest (request); boolean deleted = false; while (!deleted) { try { heatStack = queryHeatStack(heatClient, canonicalName); if (heatStack != null) { - LOGGER.debug(heatStack.getStackStatus()); - if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) { + logger.debug(heatStack.getStackStatus()); + if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) { if (deletePollTimeout <= 0) { - LOGGER.error (MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, - heatStack.getStackStatus (), "", "", MsoLogger.ErrorCode.AvailabilityError, - "Rollback: DELETE stack timeout"); - break; + logger.error( + "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Rollback: DELETE stack timeout", + MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, + heatStack.getStackStatus(), MsoLogger.ErrorCode.AvailabilityError.getValue()); + break; } else { sleep(deletePollInterval * 1000L); deletePollTimeout -= deletePollInterval; } } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())){ - LOGGER.debug("DELETE_COMPLETE for " + canonicalName); - deleted = true; + logger.debug("DELETE_COMPLETE for {}", canonicalName); + deleted = true; continue; } else { //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate @@ -411,21 +417,22 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } } else { // assume if we can't find it - it's deleted - LOGGER.debug("heatStack returned null - assume the stack " + canonicalName + " has been deleted"); - deleted = true; + logger.debug("heatStack returned null - assume the stack {} has been deleted", canonicalName); + deleted = true; continue; } } catch (Exception e3) { // Just log this one. We will report the original exception. - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack: Nested exception rolling back stack: " + e3, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack: Nested exception rolling back stack on error on query"); - + logger.error("{} Create Stack: Nested exception rolling back stack: {} ", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue(), e3); } } } catch (Exception e2) { // Just log this one. We will report the original exception. - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack: Nested exception rolling back stack: " + e2, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack: Nested exception rolling back stack"); - } + logger.error("{} Create Stack: Nested exception rolling back stack: {} ", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue(), e2); + } } // Propagate the original exception from Stack Query. @@ -435,63 +442,73 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } if (!"CREATE_COMPLETE".equals (heatStack.getStackStatus ())) { - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack error: Polling complete with non-success status: " - + heatStack.getStackStatus () + ", " + heatStack.getStackStatusReason (), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack error"); + logger.error("{} Create Stack error: Polling complete with non-success status: {}, {} {} ", + MessageEnum.RA_CREATE_STACK_ERR, heatStack.getStackStatus(), heatStack.getStackStatusReason(), + MsoLogger.ErrorCode.BusinessProcesssError.getValue()); // Rollback the stack creation, since it is in an indeterminate state. if (!backout) { - LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, stack deletion suppressed", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack error, stack deletion suppressed"); - } + logger.warn( + "{} Create Stack errored, stack deletion suppressed {} Create Stack error, stack deletion suppressed", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue()); + } else { try { - LOGGER.debug("Create Stack errored - attempting to DELETE stack: " + canonicalName); - LOGGER.debug("deletePollInterval=" + deletePollInterval + ", deletePollTimeout=" + deletePollTimeout); - OpenStackRequest <Void> request = heatClient.getStacks ().deleteByName (canonicalName); + logger.debug("Create Stack errored - attempting to DELETE stack: {}", canonicalName); + logger.debug("deletePollInterval={}, deletePollTimeout={}", deletePollInterval, deletePollTimeout); + OpenStackRequest <Void> request = heatClient.getStacks ().deleteByName (canonicalName); executeAndRecordOpenstackRequest (request); boolean deleted = false; while (!deleted) { try { heatStack = queryHeatStack(heatClient, canonicalName); if (heatStack != null) { - LOGGER.debug(heatStack.getStackStatus() + " (" + canonicalName + ")"); - if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) { + logger.debug("{} ({})", heatStack.getStackStatus(), canonicalName); + if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) { if (deletePollTimeout <= 0) { - LOGGER.error (MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, - heatStack.getStackStatus (), "", "", MsoLogger.ErrorCode.AvailabilityError, - "Rollback: DELETE stack timeout"); - break; + logger.error( + "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Rollback: DELETE stack timeout", + MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, + heatStack.getStackStatus(), MsoLogger.ErrorCode.AvailabilityError.getValue()); + break; } else { sleep(deletePollInterval * 1000L); deletePollTimeout -= deletePollInterval; - LOGGER.debug("deletePollTimeout remaining: " + deletePollTimeout); - } + logger.debug("deletePollTimeout remaining: {}", deletePollTimeout); + } } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())){ - LOGGER.debug("DELETE_COMPLETE for " + canonicalName); - deleted = true; + logger.debug("DELETE_COMPLETE for {}", canonicalName); + deleted = true; continue; } else if ("DELETE_FAILED".equals(heatStack.getStackStatus())) { // Warn about this (?) - but still throw the original exception - LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, stack deletion FAILED", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack error, stack deletion FAILED"); - LOGGER.debug("Stack deletion FAILED on a rollback of a create - " + canonicalName + ", status=" + heatStack.getStackStatus() + ", reason=" + heatStack.getStackStatusReason()); - break; + logger.warn( + "{} Create Stack errored, stack deletion FAILED {} Create Stack error, stack deletion FAILED", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue()); + logger.debug("Stack deletion FAILED on a rollback of a create - {}, status={}, reason={}", + canonicalName, heatStack.getStackStatus(), heatStack.getStackStatusReason()); + break; } else { //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate break; } } else { // assume if we can't find it - it's deleted - LOGGER.debug("heatStack returned null - assume the stack " + canonicalName + " has been deleted"); - deleted = true; + logger.debug("heatStack returned null - assume the stack {} has been deleted", canonicalName); + deleted = true; continue; } } catch (MsoException me2) { // We got an exception on the delete - don't throw this exception - throw the original - just log. - LOGGER.debug("Exception thrown trying to delete " + canonicalName + " on a create->rollback: " + me2.getContextMessage(), me2); - LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, then stack deletion FAILED - exception thrown", "", "", MsoLogger.ErrorCode.BusinessProcesssError, me2.getContextMessage()); - } + logger.debug("Exception thrown trying to delete {} on a create->rollback: {} ", canonicalName, + me2.getContextMessage(), me2); + logger.warn("{} Create Stack errored, then stack deletion FAILED - exception thrown {} {}", + MessageEnum.RA_CREATE_STACK_ERR, MsoLogger.ErrorCode.BusinessProcesssError.getValue(), + me2.getContextMessage()); + } } // end while !deleted StringBuilder errorContextMessage; @@ -507,8 +524,9 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } } catch (Exception e2) { // shouldn't happen - but handle - LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack: Nested exception rolling back stack: " + e2, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in Create Stack: rolling back stack"); - } + logger.error("{} Create Stack: Nested exception rolling back stack: {} ", MessageEnum.RA_CREATE_STACK_ERR, + MsoLogger.ErrorCode.BusinessProcesssError.getValue(), e2); + } } MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString()); me.addContext(CREATE_STACK); @@ -529,27 +547,28 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception. */ public StackInfo queryStack (String cloudSiteId, String tenantId, String stackName) throws MsoException { - LOGGER.debug ("Query HEAT stack: " + stackName + " in tenant " + tenantId); + logger.debug ("Query HEAT stack: {} in tenant {}", stackName, tenantId); // Obtain the cloud site information where we will create the stack CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( () -> new MsoCloudSiteNotFound(cloudSiteId)); - LOGGER.debug("Found: " + cloudSite.toString()); + logger.debug("Found: {}", cloudSite.toString()); // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId) Heat heatClient = null; try { heatClient = getHeatClient (cloudSite, tenantId); if (heatClient != null) { - LOGGER.debug("Found: " + heatClient.toString()); + logger.debug("Found: {}", heatClient.toString()); } } catch (MsoTenantNotFound e) { // Tenant doesn't exist, so stack doesn't either - LOGGER.debug ("Tenant with id " + tenantId + "not found.", e); + logger.debug ("Tenant with id " + tenantId + "not found.", e); return new StackInfo (stackName, HeatStatus.NOTFOUND); } catch (MsoException me) { // Got an Openstack error. Propagate it - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Exception on Token request: " + me, "Openstack", "", MsoLogger.ErrorCode.AvailabilityError, "Connection Exception"); + logger.error("{} {} Openstack Exception on Token request: ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.AvailabilityError.getValue(), me); me.addContext ("QueryStack"); throw me; } @@ -595,22 +614,23 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ // Obtain the cloud site information where we will create the stack CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( () -> new MsoCloudSiteNotFound(cloudSiteId)); - LOGGER.debug("Found: " + cloudSite.toString()); + logger.debug("Found: {}", cloudSite.toString()); // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId) Heat heatClient = null; try { heatClient = getHeatClient (cloudSite, tenantId); if (heatClient != null) { - LOGGER.debug("Found: " + heatClient.toString()); + logger.debug("Found: {}", heatClient.toString()); } } catch (MsoTenantNotFound e) { // Tenant doesn't exist, so stack doesn't either - LOGGER.debug ("Tenant with id " + tenantId + "not found.", e); + logger.debug ("Tenant with id " + tenantId + "not found.", e); return new StackInfo (stackName, HeatStatus.NOTFOUND); } catch (MsoException me) { // Got an Openstack error. Propagate it - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack", "Openstack Exception on Token request: " + me, "Openstack", "", MsoLogger.ErrorCode.AvailabilityError, "Connection Exception"); + logger.error("{} {} Openstack Exception on Token request: ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.AvailabilityError.getValue(), me); me.addContext (DELETE_STACK); throw me; } @@ -635,7 +655,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ request = heatClient.getStacks ().deleteByName (canonicalName); } else { - LOGGER.debug ("Heat Client is NULL" ); + logger.debug ("Heat Client is NULL" ); } executeAndRecordOpenstackRequest (request); @@ -668,7 +688,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ // When querying by canonical name, Openstack returns DELETE_COMPLETE status // instead of "404" (which would result from query by stack name). while (heatStack != null && !"DELETE_COMPLETE".equals (heatStack.getStackStatus ())) { - LOGGER.debug ("Stack status: " + heatStack.getStackStatus ()); + logger.debug ("Stack status: {}", heatStack.getStackStatus ()); if ("DELETE_FAILED".equals (heatStack.getStackStatus ())) { // Throw a 'special case' of MsoOpenstackException to report the Heat status @@ -685,7 +705,9 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } if (pollTimeout <= 0) { - LOGGER.error (MessageEnum.RA_DELETE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, heatStack.getStackStatus (), "", "", MsoLogger.ErrorCode.AvailabilityError, "Delete Stack Timeout"); + logger.error("{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Delete Stack Timeout", + MessageEnum.RA_DELETE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, + heatStack.getStackStatus(), MsoLogger.ErrorCode.AvailabilityError.getValue()); // Throw a 'special case' of MsoOpenstackException to report the Heat status MsoOpenstackException me = new MsoOpenstackException (0, "", "Stack Deletion Timeout"); @@ -700,7 +722,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ sleep(pollInterval * 1000L); pollTimeout -= pollInterval; - LOGGER.debug("pollTimeout remaining: " + pollTimeout); + logger.debug("pollTimeout remaining: {}", pollTimeout); heatStack = queryHeatStack (heatClient, canonicalName); } @@ -753,7 +775,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } catch (OpenStackResponseException e) { if (e.getStatus () == 404) { // Not sure if this can happen, but return an empty list - LOGGER.debug ("queryAllStacks - stack not found: "); + logger.debug ("queryAllStacks - stack not found: "); return new ArrayList <> (); } else { // Convert the OpenStackResponseException to an MsoOpenstackException @@ -803,7 +825,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ if (missingParams != null) { // Problem - missing one or more required parameters String error = "Missing Required inputs for HEAT Template: " + missingParams; - LOGGER.error (MessageEnum.RA_MISSING_PARAM, missingParams + " for HEAT Template", "", "", MsoLogger.ErrorCode.SchemaError, "Missing Required inputs for HEAT Template: " + missingParams); + logger.error("{} for HEAT Template {} Missing Required inputs for HEAT Template: {}", + MessageEnum.RA_MISSING_PARAM, MsoLogger.ErrorCode.SchemaError.getValue(), missingParams); throw new IllegalArgumentException (error); } @@ -821,9 +844,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } if (!extraParams.isEmpty ()) { - LOGGER.warn (MessageEnum.RA_GENERAL_WARNING, "Heat Stack (" + heatTemplate.getTemplateName () - + ") extra input params received: " - + extraParams, "", "", MsoLogger.ErrorCode.DataError, "Heat Stack (" + heatTemplate.getTemplateName () + ") extra input params received: "+ extraParams); + logger.warn("{} Heat Stack ({}) extra input params received: {} {}", MessageEnum.RA_GENERAL_WARNING, + heatTemplate.getTemplateName(), extraParams, MsoLogger.ErrorCode.DataError.getValue()); } return updatedParams; @@ -851,10 +873,10 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ // Obtain an MSO token for the tenant CloudIdentity cloudIdentity = cloudSite.getIdentityService(); - LOGGER.debug("Found: " + cloudIdentity.toString()); + logger.debug("Found: {}", cloudIdentity.toString()); MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType()); String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity); - LOGGER.debug("keystoneUrl=" + keystoneUrl); + logger.debug("keystoneUrl={}", keystoneUrl); String heatUrl = null; String tokenId = null; Calendar expiration = null; @@ -873,19 +895,20 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ try { // Isolate trying to printout the region IDs try { - LOGGER.debug("access=" + access.toString()); - for (Access.Service service : access.getServiceCatalog()) { + logger.debug("access={}", access.toString()); + for (Access.Service service : access.getServiceCatalog()) { List<Access.Service.Endpoint> endpoints = service.getEndpoints(); for (Access.Service.Endpoint endpoint : endpoints) { - LOGGER.debug("AIC returned region=" + endpoint.getRegion()); - } + logger.debug("AIC returned region={}", endpoint.getRegion()); + } } } catch (Exception e) { - LOGGER.debug("Encountered an error trying to printout Access object returned from AIC. " + e.getMessage()); - } + logger.debug("Encountered an error trying to printout Access object returned from AIC. {}", + e.getMessage(), e); + } heatUrl = KeystoneUtils.findEndpointURL (access.getServiceCatalog (), "orchestration", region, "public"); - LOGGER.debug("heatUrl=" + heatUrl + ", region=" + region); - } catch (RuntimeException e) { + logger.debug("heatUrl={}, region={}", heatUrl, region); + } catch (RuntimeException e) { // This comes back for not found (probably an incorrect region ID) String error = "AIC did not match an orchestration service for: region=" + region + ",cloud=" + cloudIdentity.getIdentityUrl(); throw new MsoAdapterException (error, e); @@ -959,7 +982,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ return executeAndRecordOpenstackRequest (request); } catch (OpenStackResponseException e) { if (e.getStatus () == 404) { - LOGGER.debug ("queryHeatStack - stack not found: " + stackName); + logger.debug ("queryHeatStack - stack not found: {}", stackName); return null; } else { // Convert the OpenStackResponseException to an MsoOpenstackException @@ -974,8 +997,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ public Map<String, Object> queryStackForOutputs(String cloudSiteId, String tenantId, String stackName) throws MsoException { - LOGGER.debug("MsoHeatUtils.queryStackForOutputs)"); - StackInfo heatStack = this.queryStack(cloudSiteId, tenantId, stackName); + logger.debug("MsoHeatUtils.queryStackForOutputs)"); + StackInfo heatStack = this.queryStack(cloudSiteId, tenantId, stackName); if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) { return null; } @@ -998,31 +1021,31 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ String str = this.convertNode((JsonNode) obj); inputs.put(key, str); } catch (Exception e) { - LOGGER.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode "+ key, e); - //effect here is this value will not have been copied to the inputs - and therefore will error out downstream + logger.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode {} ", key, e); + //effect here is this value will not have been copied to the inputs - and therefore will error out downstream } } else if (obj instanceof java.util.LinkedHashMap) { - LOGGER.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode"); - try { + logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode"); + try { String str = JSON_MAPPER.writeValueAsString(obj); inputs.put(key, str); } catch (Exception e) { - LOGGER.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap "+ key, e); - } + logger.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap {} ", key, e); + } } else if (obj instanceof Integer) { try { String str = "" + obj; inputs.put(key, str); } catch (Exception e) { - LOGGER.debug("DANGER WILL ROBINSON: unable to convert value for Integer "+ key, e); - } + logger.debug("DANGER WILL ROBINSON: unable to convert value for Integer {} ", key, e); + } } else { try { String str = obj.toString(); inputs.put(key, str); } catch (Exception e) { - LOGGER.debug("DANGER WILL ROBINSON: unable to convert value for Other "+ key +" (" + e.getMessage() + ")", e); - //effect here is this value will not have been copied to the inputs - and therefore will error out downstream + logger.debug("DANGER WILL ROBINSON: unable to convert value for Other {} ({}) ", key, e.getMessage(), e); + //effect here is this value will not have been copied to the inputs - and therefore will error out downstream } } } @@ -1057,8 +1080,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ String str = params.get(key).toString(); sb.append("\n").append(key).append("=").append(str); } catch (Exception e) { - LOGGER.debug("Exception :",e); - } + logger.debug("Exception :", e); + } } } } @@ -1071,8 +1094,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ final String json = JSON_MAPPER.writeValueAsString(obj); return json; } catch (Exception e) { - LOGGER.debug("Error converting json to string " + e.getMessage(), e); - } + logger.debug("Error converting json to string {} ", e.getMessage(), e); + } return "[Error converting json to string]"; } @@ -1108,7 +1131,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ String str = JSON_MAPPER.writeValueAsString(obj); sb.append(str).append(" (a java.util.LinkedHashMap)"); } catch (Exception e) { - LOGGER.debug("Exception :",e); + logger.debug("Exception :", e); sb.append("(a LinkedHashMap value that would not convert nicely)"); } } else if (obj instanceof Integer) { @@ -1116,8 +1139,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ try { str = obj.toString() + " (an Integer)\n"; } catch (Exception e) { - LOGGER.debug("Exception :",e); - str = "(an Integer unable to call .toString() on)"; + logger.debug("Exception :", e); + str = "(an Integer unable to call .toString() on)"; } sb.append(str); } else if (obj instanceof ArrayList) { @@ -1125,8 +1148,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ try { str = obj.toString() + " (an ArrayList)"; } catch (Exception e) { - LOGGER.debug("Exception :",e); - str = "(an ArrayList unable to call .toString() on?)"; + logger.debug("Exception :", e); + str = "(an ArrayList unable to call .toString() on?)"; } sb.append(str); } else if (obj instanceof Boolean) { @@ -1134,8 +1157,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ try { str = obj.toString() + " (a Boolean)"; } catch (Exception e) { - LOGGER.debug("Exception :",e); - str = "(an Boolean unable to call .toString() on?)"; + logger.debug("Exception :", e); + str = "(an Boolean unable to call .toString() on?)"; } sb.append(str); } @@ -1144,8 +1167,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ try { str = obj.toString() + " (unknown Object type)"; } catch (Exception e) { - LOGGER.debug("Exception :",e); - str = "(a value unable to call .toString() on?)"; + logger.debug("Exception :", e); + str = "(a value unable to call .toString() on?)"; } sb.append(str); } @@ -1163,44 +1186,44 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ for (String key : otherStackOutputs.keySet()) { if (paramNames != null) { if (!paramNames.contains(key) && !aliases.containsKey(key)) { - LOGGER.debug("\tParameter " + key + " is NOT defined to be in the template - do not copy to inputs"); - continue; + logger.debug("\tParameter {} is NOT defined to be in the template - do not copy to inputs", key); + continue; } if (aliases.containsKey(key)) { - LOGGER.debug("Found an alias! Will move " + key + " to " + aliases.get(key)); - Object obj = otherStackOutputs.get(key); + logger.debug("Found an alias! Will move {} to {}", key, aliases.get(key)); + Object obj = otherStackOutputs.get(key); key = aliases.get(key); otherStackOutputs.put(key, obj); } } if (!inputs.containsKey(key)) { Object obj = otherStackOutputs.get(key); - LOGGER.debug("\t**Adding " + key + " to inputs (.toString()=" + obj.toString()); - if (obj instanceof String) { - LOGGER.debug("\t\t**A String"); - inputs.put(key, obj); + logger.debug("\t**Adding {} to inputs (.toString()={}", key, obj.toString()); + if (obj instanceof String) { + logger.debug("\t\t**A String"); + inputs.put(key, obj); } else if (obj instanceof Integer) { - LOGGER.debug("\t\t**An Integer"); - inputs.put(key, obj); + logger.debug("\t\t**An Integer"); + inputs.put(key, obj); } else if (obj instanceof JsonNode) { - LOGGER.debug("\t\t**A JsonNode"); - inputs.put(key, obj); + logger.debug("\t\t**A JsonNode"); + inputs.put(key, obj); } else if (obj instanceof Boolean) { - LOGGER.debug("\t\t**A Boolean"); - inputs.put(key, obj); + logger.debug("\t\t**A Boolean"); + inputs.put(key, obj); } else if (obj instanceof java.util.LinkedHashMap) { - LOGGER.debug("\t\t**A java.util.LinkedHashMap **"); - inputs.put(key, obj); + logger.debug("\t\t**A java.util.LinkedHashMap **"); + inputs.put(key, obj); } else if (obj instanceof java.util.ArrayList) { - LOGGER.debug("\t\t**An ArrayList"); - inputs.put(key, obj); + logger.debug("\t\t**An ArrayList"); + inputs.put(key, obj); } else { - LOGGER.debug("\t\t**UNKNOWN OBJECT TYPE"); - inputs.put(key, obj); + logger.debug("\t\t**UNKNOWN OBJECT TYPE"); + inputs.put(key, obj); } } else { - LOGGER.debug("key=" + key + " is already in the inputs - will not overwrite"); - } + logger.debug("key={} is already in the inputs - will not overwrite", key); + } } return; } @@ -1239,51 +1262,52 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ HashMap<String, HeatTemplateParam> paramAliases = new HashMap<>(); if (inputs == null) { - LOGGER.debug("convertInputMap - inputs is null - nothing to do here"); - return new HashMap<>(); + logger.debug("convertInputMap - inputs is null - nothing to do here"); + return new HashMap<>(); } - LOGGER.debug("convertInputMap in MsoHeatUtils called, with " + inputs.size() + " inputs, and template " + template.getArtifactUuid()); - try { - LOGGER.debug(template.toString()); - Set<HeatTemplateParam> paramSet = template.getParameters(); - LOGGER.debug("paramSet has " + paramSet.size() + " entries"); - } catch (Exception e) { - LOGGER.debug("Exception occurred in convertInputMap:" + e.getMessage(), e); - } + logger.debug("convertInputMap in MsoHeatUtils called, with {} inputs, and template {}", inputs.size(), + template.getArtifactUuid()); + try { + logger.debug(template.toString()); + Set<HeatTemplateParam> paramSet = template.getParameters(); + logger.debug("paramSet has {} entries", paramSet.size()); + } catch (Exception e) { + logger.debug("Exception occurred in convertInputMap:" + e.getMessage(), e); + } for (HeatTemplateParam htp : template.getParameters()) { - LOGGER.debug("Adding " + htp.getParamName()); - params.put(htp.getParamName(), htp); + logger.debug("Adding {}", htp.getParamName()); + params.put(htp.getParamName(), htp); if (htp.getParamAlias() != null && !"".equals(htp.getParamAlias())) { - LOGGER.debug("\tFound ALIAS " + htp.getParamName() + "->" + htp.getParamAlias()); - paramAliases.put(htp.getParamAlias(), htp); + logger.debug("\tFound ALIAS {} -> {}", htp.getParamName(), htp.getParamAlias()); + paramAliases.put(htp.getParamAlias(), htp); } } - LOGGER.debug("Now iterate through the inputs..."); - for (String key : inputs.keySet()) { - LOGGER.debug("key=" + key); - boolean alias = false; + logger.debug("Now iterate through the inputs..."); + for (String key : inputs.keySet()) { + logger.debug("key={}", key); + boolean alias = false; String realName = null; if (!params.containsKey(key)) { - LOGGER.debug(key + " is not a parameter in the template! - check for an alias"); - // add check here for an alias + logger.debug("{} is not a parameter in the template! - check for an alias", key); + // add check here for an alias if (!paramAliases.containsKey(key)) { - LOGGER.debug("The parameter " + key + " is in the inputs, but it's not a parameter for this template - omit"); - continue; + logger.debug("The parameter {} is in the inputs, but it's not a parameter for this template - omit", key); + continue; } else { alias = true; realName = paramAliases.get(key).getParamName(); - LOGGER.debug("FOUND AN ALIAS! Will use " + realName + " in lieu of give key/alias " + key); - } + logger.debug("FOUND AN ALIAS! Will use {} in lieu of give key/alias {}", realName, key); + } } String type = params.get(key).getParamType(); if (type == null || "".equals(type)) { - LOGGER.debug("**PARAM_TYPE is null/empty for " + key + ", will default to string"); - type = "string"; + logger.debug("**PARAM_TYPE is null/empty for {}, will default to string", key); + type = "string"; } - LOGGER.debug("Parameter: " + key + " is of type " + type); - if ("string".equalsIgnoreCase(type)) { + logger.debug("Parameter: {} is of type {}", key, type); + if ("string".equalsIgnoreCase(type)) { // Easiest! String str = inputs.get(key); if (alias) @@ -1296,8 +1320,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ try { anInteger = Integer.parseInt(integerString); } catch (Exception e) { - LOGGER.debug("Unable to convert " + integerString + " to an integer!!", e); - anInteger = null; + logger.debug("Unable to convert {} to an integer!!", integerString, e); + anInteger = null; } if (anInteger != null) { if (alias) @@ -1314,8 +1338,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ } else if ("json".equalsIgnoreCase(type)) { // MSO-1475 - Leave this as a string now String jsonString = inputs.get(key); - LOGGER.debug("Skipping conversion to jsonNode..."); - if (alias) + logger.debug("Skipping conversion to jsonNode..."); + if (alias) newInputs.put(realName, jsonString); else newInputs.put(key, jsonString); @@ -1329,8 +1353,8 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ else newInputs.put(key, anArrayList); } catch (Exception e) { - LOGGER.debug("Unable to convert " + commaSeparated + " to an ArrayList!!", e); - if (alias) + logger.debug("Unable to convert {} to an ArrayList!!", commaSeparated, e); + if (alias) newInputs.put(realName, commaSeparated); else newInputs.put(key, commaSeparated); @@ -1671,7 +1695,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ try { Thread.sleep(time); } catch (InterruptedException e) { - LOGGER.debug ("Thread interrupted while sleeping", e); + logger.debug ("Thread interrupted while sleeping", e); Thread.currentThread().interrupt(); } } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java index e68a8e764a..cbbabc79b3 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtilsWithUpdate.java @@ -5,6 +5,8 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -22,12 +24,20 @@ package org.onap.so.openstack.utils; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.woorea.openstack.base.client.OpenStackBaseException; +import com.woorea.openstack.base.client.OpenStackRequest; +import com.woorea.openstack.heat.Heat; +import com.woorea.openstack.heat.model.Stack; +import com.woorea.openstack.heat.model.Stack.Output; +import com.woorea.openstack.heat.model.UpdateStackParam; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; @@ -37,28 +47,20 @@ import org.onap.so.openstack.exceptions.MsoException; import org.onap.so.openstack.exceptions.MsoOpenstackException; import org.onap.so.openstack.exceptions.MsoStackNotFound; import org.onap.so.openstack.mappers.StackInfoMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.woorea.openstack.base.client.OpenStackBaseException; -import com.woorea.openstack.base.client.OpenStackRequest; -import com.woorea.openstack.heat.Heat; -import com.woorea.openstack.heat.model.Stack; -import com.woorea.openstack.heat.model.Stack.Output; -import com.woorea.openstack.heat.model.UpdateStackParam; - @Component public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { private static final String UPDATE_STACK = "UpdateStack"; - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoHeatUtilsWithUpdate.class); + private static final Logger logger = LoggerFactory.getLogger(MsoHeatUtilsWithUpdate.class); private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); - + @Autowired private Environment environment; /* @@ -204,15 +206,15 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { // NOTE: This is specific to the v1 Orchestration API. String canonicalName = heatStack.getStackName () + "/" + heatStack.getId (); - LOGGER.debug ("Ready to Update Stack (" + canonicalName + ") with input params: " + stackInputs); + logger.debug ("Ready to Update Stack ({}) with input params: {}", canonicalName, stackInputs); //force entire stackInput object to generic Map<String, Object> for openstack compatibility ObjectMapper mapper = new ObjectMapper(); Map<String, Object> normalized = new HashMap<>(); try { normalized = mapper.readValue(mapper.writeValueAsString(stackInputs), new TypeReference<HashMap<String,Object>>() {}); } catch (IOException e1) { - LOGGER.debug("could not map json", e1); - } + logger.debug("could not map json", e1); + } // Build up the stack update parameters // Disable auto-rollback, because error reason is lost. Always rollback in the code. UpdateStackParam stack = new UpdateStackParam (); @@ -229,7 +231,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { // and then add to stack (both are part of "files:" being added to stack) if (haveFiles && haveHeatFiles) { // Let's do this here - not in the bean - LOGGER.debug ("Found files AND heatFiles - combine and add!"); + logger.debug ("Found files AND heatFiles - combine and add!"); Map <String, Object> combinedFiles = new HashMap<>(); for (String keyString : files.keySet ()) { combinedFiles.put (keyString, files.get (keyString)); @@ -275,11 +277,12 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { while (loopAgain) { try { updateStack = queryHeatStack (heatClient, canonicalName); - LOGGER.debug (updateStack.getStackStatus () + " (" + canonicalName + ")"); + logger.debug("{} ({}) ", updateStack.getStackStatus(), canonicalName); try { - LOGGER.debug("Current stack " + this.getOutputsAsStringBuilderWithUpdate(heatStack).toString()); + logger + .debug("Current stack {}" + this.getOutputsAsStringBuilderWithUpdate(heatStack).toString()); } catch (Exception e) { - LOGGER.debug("an error occurred trying to print out the current outputs of the stack", e); + logger.debug("an error occurred trying to print out the current outputs of the stack", e); } @@ -289,7 +292,10 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { if (pollTimeout <= 0) { // Note that this should not occur, since there is a timeout specified // in the Openstack call. - LOGGER.error (MessageEnum.RA_UPDATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, updateStack.getStackStatus(), "", "", MsoLogger.ErrorCode.AvailabilityError, "Update stack timeout"); + logger.error( + "{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Update stack timeout", + MessageEnum.RA_UPDATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, + updateStack.getStackStatus(), MsoLogger.ErrorCode.AvailabilityError.getValue()); loopAgain = false; } else { try { @@ -302,7 +308,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { } } pollTimeout -= createPollInterval; - LOGGER.debug("pollTimeout remaining: " + pollTimeout); + logger.debug("pollTimeout remaining: {}", pollTimeout); } else { loopAgain = false; } @@ -316,7 +322,9 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { } if (!"UPDATE_COMPLETE".equals (updateStack.getStackStatus ())) { - LOGGER.error (MessageEnum.RA_UPDATE_STACK_ERR, updateStack.getStackStatus(), updateStack.getStackStatusReason(), "", "", MsoLogger.ErrorCode.DataError, "Update Stack error"); + logger.error("{} Stack status: {} Stack status reason: {} {} Update Stack error", + MessageEnum.RA_UPDATE_STACK_ERR, updateStack.getStackStatus(), updateStack.getStackStatusReason(), + MsoLogger.ErrorCode.DataError.getValue()); // TODO: No way to roll back the stack at this point. What to do? // Throw a 'special case' of MsoOpenstackException to report the Heat status @@ -337,14 +345,14 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { // Return the current status. updateStack = queryHeatStack (heatClient, canonicalName); if (updateStack != null) { - LOGGER.debug ("UpdateStack, status = " + updateStack.getStackStatus ()); + logger.debug("UpdateStack, status = {}", updateStack.getStackStatus()); } else { - LOGGER.debug ("UpdateStack, stack not found"); + logger.debug("UpdateStack, stack not found"); } } return new StackInfoMapper(updateStack).map(); } - + private StringBuilder getOutputsAsStringBuilderWithUpdate(Stack heatStack) { // This should only be used as a utility to print out the stack outputs // to the log @@ -376,16 +384,16 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { String str = JSON_MAPPER.writeValueAsString(obj); sb.append(str).append(" (a java.util.LinkedHashMap)"); } catch (Exception e) { - LOGGER.debug("Exception :", e); - sb.append("(a LinkedHashMap value that would not convert nicely)"); - } + logger.debug("Exception :", e); + sb.append("(a LinkedHashMap value that would not convert nicely)"); + } } else if (obj instanceof Integer) { String str = ""; try { str = obj.toString() + " (an Integer)\n"; } catch (Exception e) { - LOGGER.debug("Exception :", e); - str = "(an Integer unable to call .toString() on)"; + logger.debug("Exception :", e); + str = "(an Integer unable to call .toString() on)"; } sb.append(str); } else if (obj instanceof ArrayList) { @@ -393,8 +401,8 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { try { str = obj.toString() + " (an ArrayList)"; } catch (Exception e) { - LOGGER.debug("Exception :", e); - str = "(an ArrayList unable to call .toString() on?)"; + logger.debug("Exception :", e); + str = "(an ArrayList unable to call .toString() on?)"; } sb.append(str); } else if (obj instanceof Boolean) { @@ -402,8 +410,8 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { try { str = obj.toString() + " (a Boolean)"; } catch (Exception e) { - LOGGER.debug("Exception :", e); - str = "(an Boolean unable to call .toString() on?)"; + logger.debug("Exception :", e); + str = "(an Boolean unable to call .toString() on?)"; } sb.append(str); } @@ -412,8 +420,8 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { try { str = obj.toString() + " (unknown Object type)"; } catch (Exception e) { - LOGGER.debug("Exception :", e); - str = "(a value unable to call .toString() on?)"; + logger.debug("Exception :", e); + str = "(a value unable to call .toString() on?)"; } sb.append(str); } @@ -422,16 +430,16 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { sb.append("[END]"); return sb; } - + private String convertNodeWithUpdate(final JsonNode node) { try { final Object obj = JSON_MAPPER.treeToValue(node, Object.class); final String json = JSON_MAPPER.writeValueAsString(obj); return json; } catch (Exception e) { - LOGGER.debug("Error converting json to string " + e.getMessage(), e); - } + logger.debug("Error converting json to string {} ", e.getMessage(), e); + } return "[Error converting json to string]"; } - + } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java index 0bd2a3931f..56a42e986f 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneUtils.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,17 +23,26 @@ package org.onap.so.openstack.utils; -import java.io.Serializable; -import java.util.Calendar; +import com.woorea.openstack.base.client.OpenStackBaseException; +import com.woorea.openstack.base.client.OpenStackConnectException; +import com.woorea.openstack.base.client.OpenStackRequest; +import com.woorea.openstack.base.client.OpenStackResponseException; +import com.woorea.openstack.keystone.Keystone; +import com.woorea.openstack.keystone.model.Access; +import com.woorea.openstack.keystone.model.Authentication; +import com.woorea.openstack.keystone.model.Metadata; +import com.woorea.openstack.keystone.model.Role; +import com.woorea.openstack.keystone.model.Roles; +import com.woorea.openstack.keystone.model.Tenant; +import com.woorea.openstack.keystone.model.User; +import com.woorea.openstack.keystone.utils.KeystoneUtils; import java.util.HashMap; import java.util.Map; import java.util.Optional; - +import org.onap.so.cloud.authentication.AuthenticationMethodFactory; import org.onap.so.db.catalog.beans.CloudIdentity; import org.onap.so.db.catalog.beans.CloudSite; -import org.onap.so.cloud.authentication.AuthenticationMethodFactory; import org.onap.so.logger.MessageEnum; - import org.onap.so.logger.MsoLogger; import org.onap.so.openstack.beans.MsoTenant; import org.onap.so.openstack.exceptions.MsoAdapterException; @@ -39,30 +50,17 @@ import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; import org.onap.so.openstack.exceptions.MsoException; import org.onap.so.openstack.exceptions.MsoOpenstackException; import org.onap.so.openstack.exceptions.MsoTenantAlreadyExists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import com.woorea.openstack.base.client.OpenStackBaseException; -import com.woorea.openstack.base.client.OpenStackConnectException; -import com.woorea.openstack.base.client.OpenStackRequest; -import com.woorea.openstack.base.client.OpenStackResponseException; -import com.woorea.openstack.keystone.Keystone; -import com.woorea.openstack.keystone.model.Access; -import com.woorea.openstack.keystone.model.Authentication; -import com.woorea.openstack.keystone.model.Metadata; -import com.woorea.openstack.keystone.model.Role; -import com.woorea.openstack.keystone.model.Roles; -import com.woorea.openstack.keystone.model.Tenant; -import com.woorea.openstack.keystone.model.User; -import com.woorea.openstack.keystone.utils.KeystoneUtils; - @Component public class MsoKeystoneUtils extends MsoTenantUtils { + private static Logger logger = LoggerFactory.getLogger(MsoKeystoneUtils.class); - private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoKeystoneUtils.class); - - @Autowired + @Autowired private AuthenticationMethodFactory authenticationMethodFactory; @Autowired @@ -98,7 +96,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils { // Obtain the cloud site information where we will create the tenant Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId); if (!cloudSiteOpt.isPresent()) { - LOGGER.error(MessageEnum.RA_CREATE_TENANT_ERR, "MSOCloudSite not found", "", "", MsoLogger.ErrorCode.DataError, "MSOCloudSite not found"); + logger.error("{} MSOCloudSite {} not found {} ", MessageEnum.RA_CREATE_TENANT_ERR, cloudSiteId, + MsoLogger.ErrorCode.DataError.getValue()); throw new MsoCloudSiteNotFound (cloudSiteId); } Keystone keystoneAdminClient = getKeystoneAdminClient(cloudSiteOpt.get()); @@ -109,7 +108,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils { if (tenant != null) { // Tenant already exists. Throw an exception - LOGGER.error(MessageEnum.RA_TENANT_ALREADY_EXIST, tenantName, cloudSiteId, "", "", MsoLogger.ErrorCode.DataError, "Tenant already exists"); + logger.error("{} Tenant name {} already exists on Cloud site id {}, {}", + MessageEnum.RA_TENANT_ALREADY_EXIST, tenantName, cloudSiteId, MsoLogger.ErrorCode.DataError.getValue()); throw new MsoTenantAlreadyExists (tenantName, cloudSiteId); } @@ -158,8 +158,9 @@ public class MsoKeystoneUtils extends MsoTenantUtils { // so roll back the tenant. if (!backout) { - LOGGER.warn(MessageEnum.RA_CREATE_TENANT_ERR, "Create Tenant errored, Tenant deletion suppressed", "Openstack", "", MsoLogger.ErrorCode.DataError, "Create Tenant error, Tenant deletion suppressed"); - } + logger.warn("{} Create Tenant errored, Tenant deletion suppressed {} ", MessageEnum.RA_CREATE_TENANT_ERR, + MsoLogger.ErrorCode.DataError.getValue()); + } else { try { @@ -167,8 +168,9 @@ public class MsoKeystoneUtils extends MsoTenantUtils { executeAndRecordOpenstackRequest (request); } catch (Exception e2) { // Just log this one. We will report the original exception. - LOGGER.error (MessageEnum.RA_CREATE_TENANT_ERR, "Nested exception rolling back tenant", "Openstack", "", MsoLogger.ErrorCode.DataError, "Create Tenant error, Nested exception rolling back tenant", e2); - } + logger.error("{} Nested exception rolling back tenant {} ", MessageEnum.RA_CREATE_TENANT_ERR, + MsoLogger.ErrorCode.DataError.getValue(), e2); + } } @@ -303,13 +305,14 @@ public class MsoKeystoneUtils extends MsoTenantUtils { // Check that the tenant exists. Also, need the ID to delete Tenant tenant = findTenantById (keystoneAdminClient, tenantId); if (tenant == null) { - LOGGER.error(MessageEnum.RA_TENANT_NOT_FOUND, tenantId, cloudSiteId, "", "", MsoLogger.ErrorCode.DataError, "Tenant not found"); + logger.error("{} Tenant id {} not found on cloud site id {}, {}", MessageEnum.RA_TENANT_NOT_FOUND, + tenantId, cloudSiteId, MsoLogger.ErrorCode.DataError.getValue()); return false; } OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ()); executeAndRecordOpenstackRequest (request); - LOGGER.debug ("Deleted Tenant " + tenant.getId () + " (" + tenant.getName () + ")"); + logger.debug ("Deleted Tenant {} ({})", tenant.getId(), tenant.getName()); } catch (OpenStackBaseException e) { // Convert Keystone OpenStackResponseException to MsoOpenstackException throw keystoneErrorToMsoException (e, "Delete Tenant"); @@ -349,7 +352,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils { Tenant tenant = findTenantByName (keystoneAdminClient, tenantName); if (tenant == null) { // OK if tenant already doesn't exist. - LOGGER.error(MessageEnum.RA_TENANT_NOT_FOUND, tenantName, cloudSiteId, "", "", MsoLogger.ErrorCode.DataError, "Tenant not found"); + logger.error("{} Tenant {} not found on Cloud site id {}, {}", MessageEnum.RA_TENANT_NOT_FOUND, + tenantName, cloudSiteId, MsoLogger.ErrorCode.DataError.getValue()); return false; } @@ -357,7 +361,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ()); executeAndRecordOpenstackRequest (request); - LOGGER.debug ("Deleted Tenant " + tenant.getId () + " (" + tenant.getName () + ")"); + logger.debug("Deleted Tenant {} ({})", tenant.getId(), tenant.getName()); } catch (OpenStackBaseException e) { // Note: It doesn't seem to matter if tenant doesn't exist, no exception is thrown. @@ -431,7 +435,9 @@ public class MsoKeystoneUtils extends MsoTenantUtils { } catch (RuntimeException e) { String error = "Identity service not found: region=" + region + ",cloud=" + cloudIdentity.getId (); - LOGGER.error(MessageEnum.IDENTITY_SERVICE_NOT_FOUND, region, cloudIdentity.getId(), "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception in findEndpointURL"); + logger.error("{} Region: {} Cloud identity {} {} Exception in findEndpointURL ", + MessageEnum.IDENTITY_SERVICE_NOT_FOUND, region, cloudIdentity.getId(), + MsoLogger.ErrorCode.DataError.getValue(), e); throw new MsoAdapterException (error, e); } @@ -486,7 +492,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils { if (e.getStatus () == 404) { return null; } else { - LOGGER.error(MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack Error, GET Tenant by Id (" + tenantId + "): " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception in Openstack GET tenant by Id"); + logger.error("{} {} Openstack Error, GET Tenant by Id ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), tenantId, e); throw e; } } @@ -514,7 +521,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils { if (e.getStatus () == 404) { return null; } else { - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack Error, GET Tenant By Name (" + tenantName + "): " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception in Openstack GET Tenant By Name"); + logger.error("{} {} Openstack Error, GET Tenant By Name ({}) ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), tenantName, e); throw e; } } @@ -543,7 +551,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils { // Not found by ID. Search for name return findUserByName (adminClient, userNameOrId); } else { - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack Error, GET User (" + userNameOrId + "): " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception in Openstack GET User"); + logger.error("{} {} Openstack Error, GET User ({}) ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), userNameOrId, e); throw e; } } @@ -571,7 +580,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils { if (e.getStatus () == 404) { return null; } else { - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack Error, GET User By Name (" + userName + "): " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception in Openstack GET User By Name"); + logger.error("{} {} Openstack Error, GET User By Name ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), userName, e); throw e; } } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java index 785e8606d3..b904a59ee1 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,12 +23,21 @@ package org.onap.so.openstack.utils; +import com.woorea.openstack.base.client.OpenStackBaseException; +import com.woorea.openstack.base.client.OpenStackConnectException; +import com.woorea.openstack.base.client.OpenStackRequest; +import com.woorea.openstack.base.client.OpenStackResponseException; +import com.woorea.openstack.keystone.Keystone; +import com.woorea.openstack.keystone.model.Access; +import com.woorea.openstack.keystone.model.Authentication; +import com.woorea.openstack.keystone.utils.KeystoneUtils; +import com.woorea.openstack.quantum.Quantum; +import com.woorea.openstack.quantum.model.Network; +import com.woorea.openstack.quantum.model.Networks; +import com.woorea.openstack.quantum.model.Segment; import java.util.ArrayList; import java.util.Calendar; -import java.util.HashMap; import java.util.List; -import java.util.Map; - import org.onap.so.cloud.CloudConfig; import org.onap.so.cloud.authentication.AuthenticationMethodFactory; import org.onap.so.cloud.authentication.KeystoneAuthHolder; @@ -36,10 +47,8 @@ import org.onap.so.db.catalog.beans.CloudIdentity; import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.db.catalog.beans.ServerType; import org.onap.so.logger.MessageEnum; - import org.onap.so.logger.MsoLogger; import org.onap.so.openstack.beans.NetworkInfo; -import org.onap.so.openstack.beans.NeutronCacheEntry; import org.onap.so.openstack.exceptions.MsoAdapterException; import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; import org.onap.so.openstack.exceptions.MsoException; @@ -48,22 +57,11 @@ import org.onap.so.openstack.exceptions.MsoNetworkAlreadyExists; import org.onap.so.openstack.exceptions.MsoNetworkNotFound; import org.onap.so.openstack.exceptions.MsoOpenstackException; import org.onap.so.openstack.mappers.NetworkInfoMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import com.woorea.openstack.base.client.OpenStackBaseException; -import com.woorea.openstack.base.client.OpenStackConnectException; -import com.woorea.openstack.base.client.OpenStackRequest; -import com.woorea.openstack.base.client.OpenStackResponseException; -import com.woorea.openstack.keystone.Keystone; -import com.woorea.openstack.keystone.model.Access; -import com.woorea.openstack.keystone.model.Authentication; -import com.woorea.openstack.keystone.utils.KeystoneUtils; -import com.woorea.openstack.quantum.Quantum; -import com.woorea.openstack.quantum.model.Network; -import com.woorea.openstack.quantum.model.Networks; -import com.woorea.openstack.quantum.model.Segment; - @Component public class MsoNeutronUtils extends MsoCommonUtils { @@ -80,10 +78,10 @@ public class MsoNeutronUtils extends MsoCommonUtils @Autowired private KeystoneV3Authentication keystoneV3Authentication; - - private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoNeutronUtils.class); - - public enum NetworkType { + + private static Logger logger = LoggerFactory.getLogger(MsoNeutronUtils.class); + + public enum NetworkType { BASIC, PROVIDER, MULTI_PROVIDER }; @@ -119,8 +117,10 @@ public class MsoNeutronUtils extends MsoCommonUtils if (network != null) { // Network already exists. Throw an exception - LOGGER.error(MessageEnum.RA_NETWORK_ALREADY_EXIST, networkName, cloudSiteId, tenantId, "Openstack", "", MsoLogger.ErrorCode.DataError, "Network already exists"); - throw new MsoNetworkAlreadyExists (networkName, tenantId, cloudSiteId); + logger.error("{} Network {} on Cloud site {} for tenant {} already exists {}", + MessageEnum.RA_NETWORK_ALREADY_EXIST, networkName, cloudSiteId, tenantId, + MsoLogger.ErrorCode.DataError.getValue()); + throw new MsoNetworkAlreadyExists (networkName, tenantId, cloudSiteId); } // Does not exist, create a new one @@ -183,7 +183,7 @@ public class MsoNeutronUtils extends MsoCommonUtils */ public NetworkInfo queryNetwork(String networkNameOrId, String tenantId, String cloudSiteId) throws MsoException { - LOGGER.debug("In queryNetwork"); + logger.debug("In queryNetwork"); // Obtain the cloud site information CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( @@ -195,8 +195,8 @@ public class MsoNeutronUtils extends MsoCommonUtils try { Network network = findNetworkByNameOrId (neutronClient, networkNameOrId); if (network == null) { - LOGGER.debug ("Query Network: " + networkNameOrId + " not found in tenant " + tenantId); - return null; + logger.debug("Query Network: {} not found in tenant {}", networkNameOrId, tenantId); + return null; } return new NetworkInfoMapper(network).map(); } @@ -235,15 +235,16 @@ public class MsoNeutronUtils extends MsoCommonUtils // Check that the network exists. Network network = findNetworkById (neutronClient, networkId); if (network == null) { - LOGGER.info(MessageEnum.RA_DELETE_NETWORK_EXC, networkId, cloudSiteId, tenantId, "Openstack", ""); - return false; + logger.info("{} Network not found! Network id: {} Cloud site: {} Tenant: {} ", + MessageEnum.RA_DELETE_NETWORK_EXC, networkId, cloudSiteId, tenantId); + return false; } OpenStackRequest<Void> request = neutronClient.networks().delete(network.getId()); executeAndRecordOpenstackRequest(request); - LOGGER.debug ("Deleted Network " + network.getId() + " (" + network.getName() + ")"); - } + logger.debug("Deleted Network {} ({})", network.getId(), network.getName()); + } catch (OpenStackBaseException e) { // Convert Neutron exception to an MsoOpenstackException MsoException me = neutronExceptionToMsoException (e, "Delete Network"); @@ -294,7 +295,8 @@ public class MsoNeutronUtils extends MsoCommonUtils if (network == null) { // Network not found. Throw an exception - LOGGER.error(MessageEnum.RA_NETWORK_NOT_FOUND, networkId, cloudSiteId, tenantId, "Openstack", "", MsoLogger.ErrorCode.DataError, "Network not found"); + logger.error("{} Network {} on Cloud site {} for Tenant {} not found {}", MessageEnum.RA_NETWORK_NOT_FOUND, + networkId, cloudSiteId, tenantId, MsoLogger.ErrorCode.DataError.getValue()); throw new MsoNetworkNotFound (networkId, tenantId, cloudSiteId); } @@ -480,8 +482,9 @@ public class MsoNeutronUtils extends MsoCommonUtils if (e.getStatus() == 404) { return null; } else { - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Error, GET Network By ID (" + networkId + "): " + e, "Openstack", "", MsoLogger.ErrorCode.DataError, "Exception in Openstack"); - throw e; + logger.error("{} {} Openstack Error, GET Network By ID ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), networkId, e); + throw e; } } } @@ -515,19 +518,20 @@ public class MsoNeutronUtils extends MsoCommonUtils Networks networks = executeAndRecordOpenstackRequest(request); for (Network network : networks.getList()) { if (network.getName().equals(networkName)) { - LOGGER.debug ("Found match on network name: " + networkName); - return network; + logger.debug("Found match on network name: {}", networkName); + return network; } } - LOGGER.debug ("findNetworkByName - no match found for " + networkName); - return null; + logger.debug("findNetworkByName - no match found for {}", networkName); + return null; } catch (OpenStackResponseException e) { if (e.getStatus() == 404) { return null; } else { - LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Error, GET Network By Name (" + networkName + "): " + e, "OpenStack", "", MsoLogger.ErrorCode.DataError, "Exception in OpenStack"); - throw e; + logger.error("{} {} Openstack Error, GET Network By Name ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION, + MsoLogger.ErrorCode.DataError.getValue(), networkName, e); + throw e; } } } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java index 383409f810..7cf41dbac9 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtils.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -22,10 +24,8 @@ package org.onap.so.openstack.utils; import java.util.Map; - import org.onap.so.cloud.CloudConfig; import org.onap.so.db.catalog.beans.CloudIdentity; -import org.onap.so.logger.MsoLogger; import org.onap.so.openstack.beans.MsoTenant; import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; import org.onap.so.openstack.exceptions.MsoException; @@ -35,9 +35,7 @@ import org.springframework.stereotype.Component; @Component public abstract class MsoTenantUtils extends MsoCommonUtils { - protected static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoTenantUtils.class); - - @Autowired + @Autowired protected CloudConfig cloudConfig; public abstract String createTenant (String tenantName, String cloudSiteId, Map <String, String> metadata, boolean backout) diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java index 08c98f3167..c5b93d9fbe 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoTenantUtilsFactory.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -23,16 +25,17 @@ package org.onap.so.openstack.utils; import org.onap.so.cloud.CloudConfig; import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.db.catalog.beans.ServerType; -import org.onap.so.logger.MsoLogger; import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MsoTenantUtilsFactory { - protected static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, MsoTenantUtilsFactory.class); - @Autowired + protected static Logger logger = LoggerFactory.getLogger(MsoTenantUtilsFactory.class); + @Autowired protected CloudConfig cloudConfig; @Autowired protected MsoKeystoneUtils keystoneUtils; diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java index 649eb6b07c..5f26449f0f 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoYamlEditorWithEnvt.java @@ -5,6 +5,8 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -22,25 +24,22 @@ package org.onap.so.openstack.utils; - +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; - import org.onap.so.db.catalog.beans.HeatTemplateParam; -import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Yaml; -import com.fasterxml.jackson.databind.ObjectMapper; - public class MsoYamlEditorWithEnvt { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoYamlEditorWithEnvt.class); + private static final Logger logger = LoggerFactory.getLogger(MsoYamlEditorWithEnvt.class); private Map <String, Object> yml; private Yaml yaml = new Yaml (); @@ -68,8 +67,8 @@ public class MsoYamlEditorWithEnvt { try { resourceMap = (Map<String,Object>) yml.get("parameters"); } catch (Exception e) { - LOGGER.debug("Exception:", e); - return paramSet; + logger.debug("Exception:", e); + return paramSet; } if (resourceMap == null) { return paramSet; @@ -89,7 +88,7 @@ public class MsoYamlEditorWithEnvt { try { value = JSON_MAPPER.writeValueAsString(obj); } catch (Exception e) { - LOGGER.debug("Exception:", e); + logger.debug("Exception:", e); value = "_BAD_JSON_MAPPING"; } } else { @@ -117,8 +116,8 @@ public class MsoYamlEditorWithEnvt { } return resourceList; } catch (Exception e) { - LOGGER.debug("Exception:", e); - } + logger.debug("Exception:", e); + } return null; } public synchronized Set <HeatTemplateParam> getParameterList () { @@ -135,7 +134,7 @@ public class MsoYamlEditorWithEnvt { try { value = resourceEntry.get("default"); } catch (ClassCastException cce) { - LOGGER.debug("Exception:", cce); + logger.debug("Exception:", cce); // This exception only - the value is an integer. For what we're doing // here - we don't care - so set value to something - and it will // get marked as not being required - which is correct. |