From 7a58af870eb9934dfec4b5353672d7c428208116 Mon Sep 17 00:00:00 2001 From: "Determe, Sebastien (sd378r)" Date: Wed, 6 Jun 2018 13:47:21 +0200 Subject: [PATCH] Minor Improvement Code rework postponed to Casablanca to not impact Bejing release + Update version to 3.0.0 Issue-ID: CLAMP-177 Change-Id: I3e2cb22c1158df0cf5d4cf8369f9c469004d68c0 Signed-off-by: Determe, Sebastien (sd378r) --- extra/sql/bulkload/clds-stored-procedures.sql | 11 ++ pom.xml | 51 +++++- .../java/org/onap/clamp/clds/camel/CamelProxy.java | 6 +- .../clamp/clds/client/DcaeDispatcherServices.java | 72 ++++---- .../clamp/clds/client/DcaeInventoryServices.java | 40 ++++- .../clamp/clds/client/ModelDeleteDelegate.java | 57 +++++++ .../client/OperationalPolicyDeleteDelegate.java | 4 +- .../client/req/policy/OperationalPolicyReq.java | 42 +++-- .../clamp/clds/client/req/policy/PolicyClient.java | 32 +++- .../clds/client/req/sdc/SdcCatalogServices.java | 75 +++++++++ .../clamp/clds/client/req/sdc/SdcRequests.java | 2 + src/main/java/org/onap/clamp/clds/dao/CldsDao.java | 92 ++++++----- .../onap/clamp/clds/dao/CldsServiceDataMapper.java | 4 +- .../clds/exception/CldsDelegateException.java | 18 +- .../java/org/onap/clamp/clds/model/CldsEvent.java | 1 + .../java/org/onap/clamp/clds/model/CldsModel.java | 46 +++--- .../clamp/clds/model/properties/PolicyItem.java | 38 ++++- .../clamp/clds/model/properties/ResourceGroup.java | 114 ------------- .../model/properties/ServiceConfiguration.java | 181 --------------------- .../clamp/clds/service/CldsHealthcheckService.java | 90 ++++++++++ .../org/onap/clamp/clds/service/CldsService.java | 26 ++- .../onap/clamp/clds/service/SecureServiceBase.java | 120 ++++++-------- .../java/org/onap/clamp/clds/util/CryptoUtils.java | 17 +- .../org/onap/clamp/clds/util/LoggingUtils.java | 2 + src/main/resources/clds/camel/flexible-flow.xml | 6 +- .../clds/it/CldsHealthcheckServiceItCase.java | 58 +++++++ .../clamp/clds/it/OperationPolicyReqItCase.java | 4 +- .../org/onap/clamp/clds/model/CldsModelTest.java | 17 -- .../org/onap/clamp/clds/swagger/SwaggerConfig.java | 15 +- .../clamp/clds/swagger/SwaggerGenerationTest.java | 13 +- src/test/resources/clds/key.properties | 1 - version.properties | 4 +- 32 files changed, 714 insertions(+), 545 deletions(-) create mode 100644 src/main/java/org/onap/clamp/clds/client/ModelDeleteDelegate.java delete mode 100644 src/main/java/org/onap/clamp/clds/model/properties/ResourceGroup.java delete mode 100644 src/main/java/org/onap/clamp/clds/model/properties/ServiceConfiguration.java create mode 100644 src/main/java/org/onap/clamp/clds/service/CldsHealthcheckService.java create mode 100644 src/test/java/org/onap/clamp/clds/it/CldsHealthcheckServiceItCase.java delete mode 100644 src/test/resources/clds/key.properties diff --git a/extra/sql/bulkload/clds-stored-procedures.sql b/extra/sql/bulkload/clds-stored-procedures.sql index 112cb2b5..d09d3fc8 100644 --- a/extra/sql/bulkload/clds-stored-procedures.sql +++ b/extra/sql/bulkload/clds-stored-procedures.sql @@ -14,6 +14,7 @@ DROP PROCEDURE IF EXISTS get_model; DROP PROCEDURE IF EXISTS get_model_template; DROP PROCEDURE IF EXISTS set_template; DROP PROCEDURE IF EXISTS get_template; +DROP PROCEDURE IF EXISTS del_model; DELIMITER // CREATE PROCEDURE get_template (IN v_template_name VARCHAR(80), @@ -444,6 +445,16 @@ BEGIN UPDATE event SET process_instance_id = v_process_instance_id WHERE event_id = v_event_id; +END; +CREATE PROCEDURE del_model (IN v_model_name VARCHAR(80)) +BEGIN + DECLARE v_model_id VARCHAR(36); + SELECT model_id INTO v_model_id from model where model_name = v_model_name; + UPDATE model set event_id = null, model_blueprint_id = null, model_prop_id = null where model_id = v_model_id; + DELETE from event where model_id = v_model_id; + DELETE from model_blueprint where model_id = v_model_id; + DELETE from model_properties where model_id = v_model_id; + DELETE from model where model_id = v_model_id; END // DELIMITER ; diff --git a/pom.xml b/pom.xml index 449b71a8..a1f02114 100644 --- a/pom.xml +++ b/pom.xml @@ -26,7 +26,7 @@ 4.0.0 org.onap.clamp clds - 2.0.2-SNAPSHOT + 3.0.0-SNAPSHOT clamp @@ -87,6 +87,7 @@ true false + 8.5.28 @@ -180,6 +181,26 @@ eelf-core ${eelf.core.version} + + org.apache.tomcat.embed + tomcat-embed-core + ${tomcat.version} + + + org.apache.tomcat.embed + tomcat-embed-el + ${tomcat.version} + + + org.apache.tomcat.embed + tomcat-embed-websocket + ${tomcat.version} + + + org.apache.tomcat + tomcat-annotations-api + ${tomcat.version} + org.apache.camel @@ -887,7 +908,11 @@ build - onap/clamp + + + onap-clamp + + @@ -897,7 +922,11 @@ push - onap/clamp + + + onap-clamp + + @@ -908,6 +937,14 @@ ${skipITs} + + + mariadb + + + python + + @@ -918,6 +955,14 @@ ${skipITs} + + + mariadb + + + python + + diff --git a/src/main/java/org/onap/clamp/clds/camel/CamelProxy.java b/src/main/java/org/onap/clamp/clds/camel/CamelProxy.java index a5521e37..7abb6928 100644 --- a/src/main/java/org/onap/clamp/clds/camel/CamelProxy.java +++ b/src/main/java/org/onap/clamp/clds/camel/CamelProxy.java @@ -55,6 +55,8 @@ public interface CamelProxy { * The user ID coming from the UI * @param isInsertTestEvent * Is a test or not (flag coming from the UI) + * @param eventAction + * The latest event action in database (like CREATE, SUBMIT, ...) * @return A string containing the result of the Camel flow execution */ String submit(@ExchangeProperty("actionCd") String actionCommand, @@ -62,6 +64,6 @@ public interface CamelProxy { @ExchangeProperty("modelBpmnProp") String modelBpmnProperties, @ExchangeProperty("modelName") String modelName, @ExchangeProperty("controlName") String controlName, @ExchangeProperty("docText") String docText, @ExchangeProperty("isTest") boolean isTest, - @ExchangeProperty("userid") String userId, - @ExchangeProperty("isInsertTestEvent") boolean isInsertTestEvent); + @ExchangeProperty("userid") String userId, @ExchangeProperty("isInsertTestEvent") boolean isInsertTestEvent, + @ExchangeProperty("eventAction") String eventAction); } diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java b/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java index 0ca2850f..0aca8fb1 100644 --- a/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java +++ b/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java @@ -28,10 +28,12 @@ import com.att.eelf.configuration.EELFManager; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; import java.util.Date; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.exception.dcae.DcaeDeploymentException; import org.onap.clamp.clds.util.LoggingUtils; @@ -52,7 +54,6 @@ public class DcaeDispatcherServices { private static final String STATUS_URL_LOG = "Status URL extracted: "; private static final String DCAE_URL_PREFIX = "/dcae-deployments/"; private static final String DCAE_URL_PROPERTY_NAME = "dcae.dispatcher.url"; - private static final String DCAE_REQUEST_FAILED_LOG = "RequestFailed - responseStr="; public static final String DCAE_REQUESTID_PROPERTY_NAME = "dcae.header.requestId"; private static final String DCAE_LINK_FIELD = "links"; private static final String DCAE_STATUS_FIELD = "status"; @@ -69,17 +70,11 @@ public class DcaeDispatcherServices { LoggingUtils.setTargetContext("DCAE", "deleteDeployment"); try { String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId; - String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, "DELETE", null, null); - JSONParser parser = new JSONParser(); - Object obj0 = parser.parse(responseStr); - JSONObject jsonObj = (JSONObject) obj0; - JSONObject linksObj = (JSONObject) jsonObj.get(DCAE_LINK_FIELD); - String statusUrl = (String) linksObj.get(DCAE_STATUS_FIELD); + String statusUrl = getDcaeResponse(url, "DELETE", null, null, DCAE_LINK_FIELD, DCAE_STATUS_FIELD); logger.info(STATUS_URL_LOG + statusUrl); LoggingUtils.setResponseContext("0", "Delete deployments success", this.getClass().getName()); return statusUrl; } catch (Exception e) { - // Log StatusCode during exception in metrics log LoggingUtils.setResponseContext("900", "Delete deployments failed", this.getClass().getName()); LoggingUtils.setErrorContext("900", "Delete deployments error"); logger.error("Exception occurred during Delete Deployment Operation with DCAE", e); @@ -120,16 +115,13 @@ public class DcaeDispatcherServices { LoggingUtils.setTargetContext("DCAE", "getOperationStatus"); try { String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(statusUrl, "GET", null, null); - JSONParser parser = new JSONParser(); - Object obj0 = parser.parse(responseStr); - JSONObject jsonObj = (JSONObject) obj0; + JSONObject jsonObj = parseResponse(responseStr); String operationType = (String) jsonObj.get("operationType"); - String status = (String) jsonObj.get("status"); + String status = (String) jsonObj.get(DCAE_STATUS_FIELD); logger.info("Operation Type - " + operationType + ", Status " + status); LoggingUtils.setResponseContext("0", "Get operation status success", this.getClass().getName()); opStatus = status; } catch (Exception e) { - // Log StatusCode during exception in metrics log LoggingUtils.setResponseContext("900", "Get operation status failed", this.getClass().getName()); LoggingUtils.setErrorContext("900", "Get operation status error"); logger.error("Exception occurred during getOperationStatus Operation with DCAE", e); @@ -151,7 +143,6 @@ public class DcaeDispatcherServices { DcaeHttpConnectionManager.doDcaeHttpQuery(url, "GET", null, null); LoggingUtils.setResponseContext("0", "Get deployments success", this.getClass().getName()); } catch (Exception e) { - // Log StatusCode during exception in metrics log LoggingUtils.setResponseContext("900", "Get deployments failed", this.getClass().getName()); LoggingUtils.setErrorContext("900", "Get deployments error"); logger.error("Exception occurred during getDeployments Operation with DCAE", e); @@ -180,23 +171,16 @@ public class DcaeDispatcherServices { ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("dcae.deployment.template"); rootNode.put("serviceTypeId", serviceTypeId); if (blueprintInputJson != null) { - rootNode.put("inputs", blueprintInputJson); + rootNode.set("inputs", blueprintInputJson); } String apiBodyString = rootNode.toString(); logger.info("Dcae api Body String - " + apiBodyString); String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId; - String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, "PUT", apiBodyString, - "application/json"); - JSONParser parser = new JSONParser(); - Object obj0 = parser.parse(responseStr); - JSONObject jsonObj = (JSONObject) obj0; - JSONObject linksObj = (JSONObject) jsonObj.get(DCAE_LINK_FIELD); - String statusUrl = (String) linksObj.get(DCAE_STATUS_FIELD); - logger.info(STATUS_URL_LOG + statusUrl); + String statusUrl = getDcaeResponse(url, "PUT", apiBodyString, "application/json", DCAE_LINK_FIELD, + DCAE_STATUS_FIELD); LoggingUtils.setResponseContext("0", "Create new deployment failed", this.getClass().getName()); return statusUrl; } catch (Exception e) { - // Log StatusCode during exception in metrics log LoggingUtils.setResponseContext("900", "Create new deployment failed", this.getClass().getName()); LoggingUtils.setErrorContext("900", "Create new deployment error"); logger.error("Exception occurred during createNewDeployment Operation with DCAE", e); @@ -207,7 +191,7 @@ public class DcaeDispatcherServices { } } - /** + /*** * Returns status URL for deleteExistingDeployment operation. * * @param deploymentId @@ -223,18 +207,12 @@ public class DcaeDispatcherServices { String apiBodyString = "{\"serviceTypeId\": \"" + serviceTypeId + "\"}"; logger.info("Dcae api Body String - " + apiBodyString); String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId; - String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, "DELETE", apiBodyString, - "application/json"); - JSONParser parser = new JSONParser(); - Object obj0 = parser.parse(responseStr); - JSONObject jsonObj = (JSONObject) obj0; - JSONObject linksObj = (JSONObject) jsonObj.get(DCAE_LINK_FIELD); - String statusUrl = (String) linksObj.get(DCAE_STATUS_FIELD); - logger.info(STATUS_URL_LOG + statusUrl); + String statusUrl = getDcaeResponse(url, "DELETE", apiBodyString, "application/json", DCAE_LINK_FIELD, + DCAE_STATUS_FIELD); LoggingUtils.setResponseContext("0", "Delete existing deployment success", this.getClass().getName()); return statusUrl; + } catch (Exception e) { - // Log StatusCode during exception in metrics log LoggingUtils.setResponseContext("900", "Delete existing deployment failed", this.getClass().getName()); LoggingUtils.setErrorContext("900", "Delete existing deployment error"); logger.error("Exception occurred during deleteExistingDeployment Operation with DCAE", e); @@ -245,4 +223,30 @@ public class DcaeDispatcherServices { metricsLogger.info("deleteExistingDeployment complete"); } } + + private String getDcaeResponse(String url, String requestMethod, String payload, String contentType, String node, + String nodeAttr) throws IOException, ParseException { + Date startTime = new Date(); + try { + String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, requestMethod, payload, contentType); + JSONObject jsonObj = parseResponse(responseStr); + JSONObject linksObj = (JSONObject) jsonObj.get(node); + String statusUrl = (String) linksObj.get(nodeAttr); + logger.info(STATUS_URL_LOG + statusUrl); + return statusUrl; + } catch (IOException | ParseException e) { + logger.error("Exception occurred getting response from DCAE", e); + throw e; + } finally { + LoggingUtils.setTimeContext(startTime, new Date()); + metricsLogger.info("getDcaeResponse complete"); + } + } + + private JSONObject parseResponse(String responseStr) throws ParseException { + JSONParser parser = new JSONParser(); + Object obj0 = parser.parse(responseStr); + JSONObject jsonObj = (JSONObject) obj0; + return jsonObj; + } } \ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java b/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java index 1e5dedaa..5f215968 100644 --- a/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java +++ b/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java @@ -126,15 +126,13 @@ public class DcaeInventoryServices { if (dcaeResponse != null) { logger.info("Dcae Response for query on inventory: " + dcaeResponse); String oldTypeId = cldsModel.getTypeId(); - String newTypeId = ""; if (dcaeResponse.getTypeId() != null) { - newTypeId = dcaeResponse.getTypeId(); cldsModel.setTypeId(dcaeResponse.getTypeId()); } if (dcaeResponse.getTypeName() != null) { cldsModel.setTypeName(dcaeResponse.getTypeName()); } - if (oldTypeId == null || !oldTypeId.equalsIgnoreCase(newTypeId) + if (oldTypeId == null || !cldsModel.getEvent().getActionCd().equalsIgnoreCase(CldsEvent.ACTION_DISTRIBUTE) || cldsModel.getEvent().getActionCd().equalsIgnoreCase(CldsEvent.ACTION_SUBMITDCAE)) { CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userId, dcaeEvent.getCldsActionCd(), CldsEvent.ACTION_STATE_RECEIVED, null); @@ -288,4 +286,40 @@ public class DcaeInventoryServices { } return typeId; } + + /** + * Method to delete blueprint from dcae inventory if it's exists. + * + * @param typeName + * @param serviceUuid + * @param resourceUuid + * @throws InterruptedException + */ + public void deleteDCAEServiceType(String typeName, String serviceUuid, String resourceUuid) + throws InterruptedException { + Date startTime = new Date(); + LoggingUtils.setTargetContext("DCAE", "deleteDCAEServiceType"); + boolean result = false; + try { + DcaeInventoryResponse inventoryResponse = getDcaeInformation(typeName, serviceUuid, resourceUuid); + if (inventoryResponse != null && inventoryResponse.getTypeId() != null) { + String fullUrl = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types/" + + inventoryResponse.getTypeId(); + DcaeHttpConnectionManager.doDcaeHttpQuery(fullUrl, "DELETE", null, null); + } + result = true; + } catch (IOException | ParseException e) { + logger.error("Exception occurred during deleteDCAEServiceType Operation with DCAE", e); + throw new BadRequestException("Exception occurred during deleteDCAEServiceType Operation with DCAE", e); + } finally { + if (result) { + LoggingUtils.setResponseContext("0", "Delete DCAE ServiceType success", this.getClass().getName()); + } else { + LoggingUtils.setResponseContext("900", "Delete DCAE ServiceType failed", this.getClass().getName()); + LoggingUtils.setErrorContext("900", "Delete DCAE ServiceType error"); + } + LoggingUtils.setTimeContext(startTime, new Date()); + metricsLogger.info("deleteDCAEServiceType completed"); + } + } } diff --git a/src/main/java/org/onap/clamp/clds/client/ModelDeleteDelegate.java b/src/main/java/org/onap/clamp/clds/client/ModelDeleteDelegate.java new file mode 100644 index 00000000..6a369db9 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/client/ModelDeleteDelegate.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ + +package org.onap.clamp.clds.client; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import org.apache.camel.Exchange; +import org.apache.camel.Handler; +import org.onap.clamp.clds.dao.CldsDao; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * Delete model. + */ +@Component +public class ModelDeleteDelegate { + + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(ModelDeleteDelegate.class); + protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + @Autowired + private CldsDao cldsDao; + + /** + * Insert event using process variables. + * + * @param camelExchange + * The Camel Exchange object containing the properties + */ + @Handler + public void execute(Exchange camelExchange) { + String modelName = (String) camelExchange.getProperty("modelName"); + cldsDao.deleteModel(modelName); + } +} diff --git a/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDeleteDelegate.java b/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDeleteDelegate.java index e585f31d..08cfba14 100644 --- a/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDeleteDelegate.java +++ b/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDeleteDelegate.java @@ -29,6 +29,7 @@ import com.att.eelf.configuration.EELFManager; import org.apache.camel.Exchange; import org.apache.camel.Handler; import org.onap.clamp.clds.client.req.policy.PolicyClient; +import org.onap.clamp.clds.model.CldsEvent; import org.onap.clamp.clds.model.properties.ModelProperties; import org.onap.clamp.clds.model.properties.Policy; import org.onap.clamp.clds.model.properties.PolicyChain; @@ -58,8 +59,9 @@ public class OperationalPolicyDeleteDelegate { ModelProperties prop = ModelProperties.create(camelExchange); Policy policy = prop.getType(Policy.class); prop.setCurrentModelElementId(policy.getId()); + String eventAction = (String) camelExchange.getProperty("eventAction"); String responseMessage = ""; - if (policy.isFound()) { + if (!eventAction.equalsIgnoreCase(CldsEvent.ACTION_CREATE) && policy.isFound()) { for (PolicyChain policyChain : policy.getPolicyChains()) { prop.setPolicyUniqueId(policyChain.getPolicyId()); responseMessage = policyClient.deleteBrms(prop); diff --git a/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyReq.java b/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyReq.java index 8d96dfcf..bf08a239 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyReq.java +++ b/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyReq.java @@ -91,8 +91,8 @@ public class OperationalPolicyReq { logger.info("notificationTopic=" + notificationTopic); Map ruleAttributes = new HashMap<>(); ruleAttributes.put("templateName", templateName); - ruleAttributes.put("ClosedLoopControlName", prop.getControlNameAndPolicyUniqueId()); - ruleAttributes.put("NotificationTopic", notificationTopic); + ruleAttributes.put("closedLoopControlName", prop.getControlNameAndPolicyUniqueId()); + ruleAttributes.put("notificationTopic", notificationTopic); if (operationTopic == null || operationTopic.isEmpty()) { logger.info("recipeTopic=" + recipeTopic); // if no operationTopic, then don't format yaml - use first policy @@ -115,8 +115,8 @@ public class OperationalPolicyReq { logger.info("operationTopic=" + operationTopic); // format yaml String yaml = formatYaml(refProp, prop, modelElementId, policyChain); - ruleAttributes.put("OperationTopic", operationTopic); - ruleAttributes.put("ControlLoopYaml", yaml); + ruleAttributes.put("operationTopic", operationTopic); + ruleAttributes.put("controlLoopYaml", yaml); } // matchingAttributes Map matchingAttributes = new HashMap<>(); @@ -189,22 +189,36 @@ public class OperationalPolicyReq { String policyName = policyItem.getRecipe() + " Policy"; Target target = new Target(); target.setType(TargetType.VM); + // We can send target type as VM/VNF for most of recipes + if (policyItem.getRecipeLevel() != null && !policyItem.getRecipeLevel().isEmpty()) { + target.setType(TargetType.valueOf(policyItem.getRecipeLevel())); + } target.setResourceID(policyItem.getTargetResourceId()); + String actor = refProp.getStringValue("op.policy.appc"); + Map payloadMap = null; + if ("health-diagnostic".equalsIgnoreCase(policyItem.getRecipe())) { + actor = refProp.getStringValue("op.policy.sdno"); + payloadMap = new HashMap(); + payloadMap.put("ttl", policyItem.getRecipePayload()); + } + // For reboot recipe we have to send type as SOFT/HARD in pay load + if (policyItem.getRecipeInfo() != null && !policyItem.getRecipeInfo().isEmpty()) { + payloadMap = new HashMap(); + payloadMap.put("type", policyItem.getRecipeInfo()); + } Policy policyObj; if (policyItemList.indexOf(policyItem) == 0) { String policyDescription = policyItem.getRecipe() + " Policy - the trigger (no parent) policy - created by CLDS"; - policyObj = builder.setTriggerPolicy(policyName, policyDescription, - refProp.getStringValue("op.policy.appc"), target, policyItem.getRecipe(), null, - policyItem.getMaxRetries(), policyItem.getRetryTimeLimit()); + policyObj = builder.setTriggerPolicy(policyName, policyDescription, actor, target, + policyItem.getRecipe(), payloadMap, policyItem.getMaxRetries(), policyItem.getRetryTimeLimit()); } else { Policy parentPolicyObj = policyObjMap.get(policyItem.getParentPolicy()); String policyDescription = policyItem.getRecipe() + " Policy - triggered conditionally by " + parentPolicyObj.getName() + " - created by CLDS"; - policyObj = builder.setPolicyForPolicyResult(policyName, policyDescription, - refProp.getStringValue("op.policy.appc"), target, policyItem.getRecipe(), null, - policyItem.getMaxRetries(), policyItem.getRetryTimeLimit(), parentPolicyObj.getId(), - convertToPolicyResult(policyItem.getParentPolicyConditions())); + policyObj = builder.setPolicyForPolicyResult(policyName, policyDescription, actor, target, + policyItem.getRecipe(), payloadMap, policyItem.getMaxRetries(), policyItem.getRetryTimeLimit(), + parentPolicyObj.getId(), convertToPolicyResult(policyItem.getParentPolicyConditions())); logger.info("policyObj.id=" + policyObj.getId() + "; parentPolicyObj.id=" + parentPolicyObj.getId()); } policyObjMap.put(policyItem.getId(), policyObj); @@ -215,7 +229,7 @@ public class OperationalPolicyReq { return URLEncoder.encode(results.getSpecification(), "UTF-8"); } - private static void validate(Results results) { + protected static void validate(Results results) { if (results.isValid()) { logger.info("results.getSpecification()=" + results.getSpecification()); } else { @@ -288,7 +302,7 @@ public class OperationalPolicyReq { * @param resourceType * @return */ - private static Resource[] convertToResource(List stringList, ResourceType resourceType) { + protected static Resource[] convertToResource(List stringList, ResourceType resourceType) { if (stringList == null || stringList.isEmpty()) { return new Resource[0]; } @@ -302,7 +316,7 @@ public class OperationalPolicyReq { * @param prList * @return */ - private static PolicyResult[] convertToPolicyResult(List prList) { + protected static PolicyResult[] convertToPolicyResult(List prList) { if (prList == null || prList.isEmpty()) { return new PolicyResult[0]; } diff --git a/src/main/java/org/onap/clamp/clds/client/req/policy/PolicyClient.java b/src/main/java/org/onap/clamp/clds/client/req/policy/PolicyClient.java index 1e423ffe..cc97a7ce 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/policy/PolicyClient.java +++ b/src/main/java/org/onap/clamp/clds/client/req/policy/PolicyClient.java @@ -56,12 +56,14 @@ import org.onap.policy.api.PolicyType; import org.onap.policy.api.PushPolicyParameters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; /** * Policy utility methods - specifically, send the policy. */ @Component +@Primary public class PolicyClient { protected PolicyEngine policyEngine; @@ -376,8 +378,19 @@ public class PolicyClient { * @return The response message from Policy */ public String deleteMicrosService(ModelProperties prop) { - String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME); - return deletePolicy(prop, policyType); + String deletePolicyResponse = ""; + try { + String policyNamePrefix = refProp.getStringValue(POLICY_MS_NAME_PREFIX_PROPERTY_NAME); + List versions = getVersions(policyNamePrefix, prop); + if (!versions.isEmpty()) { + String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME); + deletePolicyResponse = deletePolicy(prop, policyType); + } + } catch (Exception e) { + logger.error("Exception occurred during policy communication", e); + throw new PolicyClientException("Exception while communicating with Policy", e); + } + return deletePolicyResponse; } /** @@ -399,8 +412,19 @@ public class PolicyClient { * @return The response message from policy */ public String deleteBrms(ModelProperties prop) { - String policyType = refProp.getStringValue(POLICY_OP_TYPE_PROPERTY_NAME); - return deletePolicy(prop, policyType); + String deletePolicyResponse = ""; + try { + String policyNamePrefix = refProp.getStringValue(POLICY_OP_NAME_PREFIX_PROPERTY_NAME); + List versions = getVersions(policyNamePrefix, prop); + if (!versions.isEmpty()) { + String policyType = refProp.getStringValue(POLICY_OP_TYPE_PROPERTY_NAME); + deletePolicyResponse = deletePolicy(prop, policyType); + } + } catch (Exception e) { + logger.error("Exception occurred during policy communication", e); + throw new PolicyClientException("Exception while communicating with Policy", e); + } + return deletePolicyResponse; } /** diff --git a/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java b/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java index e3bd1785..9c940210 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java +++ b/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java @@ -77,9 +77,11 @@ import org.onap.clamp.clds.util.CryptoUtils; import org.onap.clamp.clds.util.JacksonUtils; import org.onap.clamp.clds.util.LoggingUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; @Component +@Primary public class SdcCatalogServices { private static final EELFLogger logger = EELFManager.getInstance().getLogger(SdcCatalogServices.class); @@ -1227,4 +1229,77 @@ public class SdcCatalogServices { } } } + + /** + * Method to delete blueprint and location json artifacts from sdc + * + * @param prop + * @param userid + * @param sdcReqUrlsList + * @param artifactName + * @param locationArtifactName + * @throws GeneralSecurityException + * @throws DecoderException + */ + public void deleteArtifactsFromSdc(ModelProperties prop, String userid, List sdcReqUrlsList, + String artifactName, String locationArtifactName) throws GeneralSecurityException, DecoderException { + String serviceInvariantUuid = getServiceInvariantUuidFromProps(prop); + for (String url : sdcReqUrlsList) { + String originalServiceUuid = getServiceUuidFromServiceInvariantId(serviceInvariantUuid); + logger.info("ServiceUUID used before deleting in url:" + originalServiceUuid); + String sdcServicesInformation = getSdcServicesInformation(originalServiceUuid); + SdcServiceDetail cldsSdcServiceDetail = decodeCldsSdcServiceDetailFromJson(sdcServicesInformation); + String uploadedArtifactUuid = getArtifactIdIfArtifactAlreadyExists(cldsSdcServiceDetail, artifactName); + String responseStr = deleteArtifact(userid, url, uploadedArtifactUuid); + logger.info("value of sdc Response of deleting blueprint from sdc :" + responseStr); + String updatedServiceUuid = getServiceUuidFromServiceInvariantId(serviceInvariantUuid); + if (!originalServiceUuid.equalsIgnoreCase(updatedServiceUuid)) { + url = url.replace(originalServiceUuid, updatedServiceUuid); + } + logger.info("ServiceUUID used after delete in ulr:" + updatedServiceUuid); + sdcServicesInformation = getSdcServicesInformation(updatedServiceUuid); + cldsSdcServiceDetail = decodeCldsSdcServiceDetailFromJson(sdcServicesInformation); + uploadedArtifactUuid = getArtifactIdIfArtifactAlreadyExists(cldsSdcServiceDetail, locationArtifactName); + responseStr = deleteArtifact(userid, url, uploadedArtifactUuid); + logger.info("value of sdc Response of deleting location json from sdc :" + responseStr); + } + } + + private String deleteArtifact(String userid, String url, String uploadedArtifactUuid) { + try { + String responseStr = ""; + if (uploadedArtifactUuid != null && !uploadedArtifactUuid.isEmpty()) { + logger.info("userid=" + userid); + String basicAuth = getSdcBasicAuth(); + String sdcXonapInstanceId = refProp.getStringValue("sdc.sdcX-InstanceID"); + url = url + "/" + uploadedArtifactUuid; + URL urlObj = new URL(url); + HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); + conn.setDoOutput(true); + conn.setRequestProperty(refProp.getStringValue(SDC_INSTANCE_ID_PROPERTY_NAME), sdcXonapInstanceId); + conn.setRequestProperty(HttpHeaders.AUTHORIZATION, basicAuth); + conn.setRequestProperty("USER_ID", userid); + conn.setRequestMethod("DELETE"); + conn.setRequestProperty("charset", "utf-8"); + conn.setUseCaches(false); + conn.setRequestProperty(refProp.getStringValue(SDC_REQUESTID_PROPERTY_NAME), + LoggingUtils.getRequestId()); + boolean requestFailed = true; + int responseCode = conn.getResponseCode(); + logger.info("responseCode=" + responseCode); + if (responseCode == 200) { + requestFailed = false; + } + responseStr = getResponse(conn); + if (responseStr != null && requestFailed) { + logger.error("requestFailed - responseStr=" + responseStr); + throw new BadRequestException(responseStr); + } + } + return responseStr; + } catch (IOException | DecoderException | GeneralSecurityException e) { + logger.error("Exception when attempting to communicate with SDC", e); + throw new SdcCommunicationException("Exception when attempting to communicate with SDC", e); + } + } } diff --git a/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcRequests.java b/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcRequests.java index f0e72ef0..efd664c6 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcRequests.java +++ b/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcRequests.java @@ -49,12 +49,14 @@ import org.onap.clamp.clds.model.sdc.SdcResource; import org.onap.clamp.clds.model.sdc.SdcServiceDetail; import org.onap.clamp.clds.util.JacksonUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; /** * Construct a Sdc request given CLDS objects. */ @Component +@Primary public class SdcRequests { protected static final EELFLogger logger = EELFManager.getInstance().getLogger(SdcRequests.class); diff --git a/src/main/java/org/onap/clamp/clds/dao/CldsDao.java b/src/main/java/org/onap/clamp/clds/dao/CldsDao.java index 6a7fa0b3..a3771aa5 100644 --- a/src/main/java/org/onap/clamp/clds/dao/CldsDao.java +++ b/src/main/java/org/onap/clamp/clds/dao/CldsDao.java @@ -68,8 +68,11 @@ public class CldsDao { private SimpleJdbcCall procGetTemplate; private SimpleJdbcCall procDelAllModelInstances; private SimpleJdbcCall procInsModelInstance; + private SimpleJdbcCall procDeleteModel; private static final String HEALTHCHECK = "Select 1"; - + private static final String V_CONTROL_NAME_PREFIX = "v_control_name_prefix"; + private static final String V_CONTROL_NAME_UUID = "v_control_name_uuid"; + /** * Log message when instantiating */ @@ -91,6 +94,7 @@ public class CldsDao { this.procSetTemplate = new SimpleJdbcCall(dataSource).withProcedureName("set_template"); this.procInsModelInstance = new SimpleJdbcCall(dataSource).withProcedureName("ins_model_instance"); this.procDelAllModelInstances = new SimpleJdbcCall(dataSource).withProcedureName("del_all_model_instances"); + this.procDeleteModel = new SimpleJdbcCall(dataSource).withProcedureName("del_model"); } /** @@ -112,25 +116,9 @@ public class CldsDao { CldsModel model = new CldsModel(); model.setName(modelName); SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName) - .addValue("v_control_name_uuid", controlNameUuid); + .addValue(V_CONTROL_NAME_UUID, controlNameUuid); Map out = logSqlExecution(procGetModel, in); - model.setControlNamePrefix((String) out.get("v_control_name_prefix")); - model.setControlNameUuid((String) out.get("v_control_name_uuid")); - model.setId((String) (out.get("v_model_id"))); - model.setTemplateId((String) (out.get("v_template_id"))); - model.setTemplateName((String) (out.get("v_template_name"))); - model.setBpmnText((String) out.get("v_template_bpmn_text")); - model.setPropText((String) out.get("v_model_prop_text")); - model.setImageText((String) out.get("v_template_image_text")); - model.setDocText((String) out.get("v_template_doc_text")); - model.setBlueprintText((String) out.get("v_model_blueprint_text")); - model.getEvent().setId((String) (out.get("v_event_id"))); - model.getEvent().setActionCd((String) out.get("v_action_cd")); - model.getEvent().setActionStateCd((String) out.get("v_action_state_cd")); - model.getEvent().setProcessInstanceId((String) out.get("v_event_process_instance_id")); - model.getEvent().setUserid((String) out.get("v_event_user_id")); - model.setTypeId((String) out.get("v_service_type_id")); - model.setDeploymentId((String) out.get("v_deployment_id")); + populateModelProperties(model, out); return model; } @@ -147,23 +135,7 @@ public class CldsDao { SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName); Map out = logSqlExecution(procGetModelTemplate, in); // todo : rationalize - model.setControlNamePrefix((String) out.get("v_control_name_prefix")); - model.setControlNameUuid((String) out.get("v_control_name_uuid")); - model.setId((String) (out.get("v_model_id"))); - model.setTemplateId((String) (out.get("v_template_id"))); - model.setTemplateName((String) (out.get("v_template_name"))); - model.setBpmnText((String) out.get("v_template_bpmn_text")); - model.setPropText((String) out.get("v_model_prop_text")); - model.setImageText((String) out.get("v_template_image_text")); - model.setDocText((String) out.get("v_template_doc_text")); - model.setBlueprintText((String) out.get("v_model_blueprint_text")); - model.getEvent().setId((String) (out.get("v_event_id"))); - model.getEvent().setActionCd((String) out.get("v_action_cd")); - model.getEvent().setActionStateCd((String) out.get("v_action_state_cd")); - model.getEvent().setProcessInstanceId((String) out.get("v_event_process_instance_id")); - model.getEvent().setUserid((String) out.get("v_event_user_id")); - model.setTypeId((String) out.get("v_service_type_id")); - model.setDeploymentId((String) out.get("v_deployment_id")); + populateModelProperties(model, out); Map modelResults = logSqlExecution(procGetModel, in); Object modelResultObject = modelResults.get("#result-set-1"); if (modelResultObject != null && modelResultObject instanceof ArrayList) { @@ -198,10 +170,10 @@ public class CldsDao { .addValue("v_model_blueprint_text", model.getBlueprintText()) .addValue("v_service_type_id", model.getTypeId()).addValue("v_deployment_id", model.getDeploymentId()) .addValue("v_control_name_prefix", model.getControlNamePrefix()) - .addValue("v_control_name_uuid", model.getControlNameUuid()); + .addValue(V_CONTROL_NAME_UUID, model.getControlNameUuid()); Map out = logSqlExecution(procSetModel, in); - model.setControlNamePrefix((String) out.get("v_control_name_prefix")); - model.setControlNameUuid((String) out.get("v_control_name_uuid")); + model.setControlNamePrefix((String) out.get(V_CONTROL_NAME_PREFIX)); + model.setControlNameUuid((String) out.get(V_CONTROL_NAME_UUID)); model.setId((String) (out.get("v_model_id"))); model.getEvent().setId((String) (out.get("v_event_id"))); model.getEvent().setActionCd((String) out.get("v_action_cd")); @@ -231,7 +203,7 @@ public class CldsDao { logger.debug("v_vm_name={}", currModelInstance.getVmName()); logger.debug("v_location={}", currModelInstance.getLocation()); SqlParameterSource in = new MapSqlParameterSource() - .addValue("v_control_name_uuid", model.getControlNameUuid()) + .addValue(V_CONTROL_NAME_UUID, model.getControlNameUuid()) .addValue("v_vm_name", currModelInstance.getVmName()) .addValue("v_location", currModelInstance.getLocation()); Map out = logSqlExecution(procInsModelInstance, in); @@ -258,7 +230,7 @@ public class CldsDao { public CldsEvent insEvent(String modelName, String controlNamePrefix, String controlNameUuid, CldsEvent cldsEvent) { CldsEvent event = new CldsEvent(); SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName) - .addValue("v_control_name_prefix", controlNamePrefix).addValue("v_control_name_uuid", controlNameUuid) + .addValue(V_CONTROL_NAME_PREFIX, controlNamePrefix).addValue(V_CONTROL_NAME_UUID, controlNameUuid) .addValue("v_user_id", cldsEvent.getUserid()).addValue("v_action_cd", cldsEvent.getActionCd()) .addValue("v_action_state_cd", cldsEvent.getActionStateCd()) .addValue("v_process_instance_id", cldsEvent.getProcessInstanceId()); @@ -268,7 +240,7 @@ public class CldsDao { } private String delAllModelInstances(String controlNameUUid) { - SqlParameterSource in = new MapSqlParameterSource().addValue("v_control_name_uuid", controlNameUUid); + SqlParameterSource in = new MapSqlParameterSource().addValue(V_CONTROL_NAME_UUID, controlNameUUid); Map out = logSqlExecution(procDelAllModelInstances, in); return (String) (out.get("v_model_id")); } @@ -360,9 +332,8 @@ public class CldsDao { CldsServiceData cldsServiceData = null; try { String getCldsServiceSQL = "SELECT * , TIMESTAMPDIFF(SECOND, timestamp, CURRENT_TIMESTAMP()) FROM clds_service_cache where invariant_service_id = ? "; - cldsServiceData = jdbcTemplateObject.queryForObject(getCldsServiceSQL, new Object[] { - invariantUUID - }, new CldsServiceDataMapper()); + cldsServiceData = jdbcTemplateObject.queryForObject(getCldsServiceSQL, new Object[] { invariantUUID }, + new CldsServiceDataMapper()); if (cldsServiceData != null) { logger.info("CldsServiceData found in cache for Service Invariant ID:" + cldsServiceData.getServiceInvariantUUID()); @@ -461,4 +432,35 @@ public class CldsDao { } return cldsMonitoringDetailsList; } + + /** + * Method to delete model from database. + * + * @param modelName + */ + public void deleteModel(String modelName) { + SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName); + logSqlExecution(procDeleteModel, in); + } + + private void populateModelProperties(CldsModel model, Map out) { + // todo : rationalize + model.setControlNamePrefix((String) out.get(V_CONTROL_NAME_PREFIX)); + model.setControlNameUuid((String) out.get(V_CONTROL_NAME_UUID)); + model.setId((String) (out.get("v_model_id"))); + model.setTemplateId((String) (out.get("v_template_id"))); + model.setTemplateName((String) (out.get("v_template_name"))); + model.setBpmnText((String) out.get("v_template_bpmn_text")); + model.setPropText((String) out.get("v_model_prop_text")); + model.setImageText((String) out.get("v_template_image_text")); + model.setDocText((String) out.get("v_template_doc_text")); + model.setBlueprintText((String) out.get("v_model_blueprint_text")); + model.getEvent().setId((String) (out.get("v_event_id"))); + model.getEvent().setActionCd((String) out.get("v_action_cd")); + model.getEvent().setActionStateCd((String) out.get("v_action_state_cd")); + model.getEvent().setProcessInstanceId((String) out.get("v_event_process_instance_id")); + model.getEvent().setUserid((String) out.get("v_event_user_id")); + model.setTypeId((String) out.get("v_service_type_id")); + model.setDeploymentId((String) out.get("v_deployment_id")); + } } diff --git a/src/main/java/org/onap/clamp/clds/dao/CldsServiceDataMapper.java b/src/main/java/org/onap/clamp/clds/dao/CldsServiceDataMapper.java index e881099b..4e0a50c4 100644 --- a/src/main/java/org/onap/clamp/clds/dao/CldsServiceDataMapper.java +++ b/src/main/java/org/onap/clamp/clds/dao/CldsServiceDataMapper.java @@ -34,6 +34,7 @@ import java.util.ArrayList; import org.apache.commons.io.serialization.ValidatingObjectInputStream; import org.onap.clamp.clds.model.CldsServiceData; import org.onap.clamp.clds.model.CldsVfData; +import org.onap.clamp.clds.model.CldsVfKPIData; import org.onap.clamp.clds.model.CldsVfcData; import org.springframework.jdbc.core.RowMapper; @@ -48,7 +49,8 @@ public final class CldsServiceDataMapper implements RowMapper { public CldsServiceData mapRow(ResultSet rs, int rowNum) throws SQLException { CldsServiceData cldsServiceData = new CldsServiceData(); try (ValidatingObjectInputStream oip = new ValidatingObjectInputStream(rs.getBlob(4).getBinaryStream())) { - oip.accept(CldsServiceData.class, ArrayList.class, CldsVfData.class, CldsVfcData.class); + oip.accept(CldsServiceData.class, ArrayList.class, CldsVfData.class, CldsVfcData.class, + CldsVfKPIData.class); cldsServiceData = (CldsServiceData) oip.readObject(); cldsServiceData.setAgeOfRecord(rs.getLong(5)); } catch (IOException | ClassNotFoundException e) { diff --git a/src/main/java/org/onap/clamp/clds/exception/CldsDelegateException.java b/src/main/java/org/onap/clamp/clds/exception/CldsDelegateException.java index 001cd2a9..22b7e3fd 100644 --- a/src/main/java/org/onap/clamp/clds/exception/CldsDelegateException.java +++ b/src/main/java/org/onap/clamp/clds/exception/CldsDelegateException.java @@ -2,19 +2,19 @@ * ============LICENSE_START======================================================= * ONAP CLAMP * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights * reserved. * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. + * 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 - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END============================================ * =================================================================== diff --git a/src/main/java/org/onap/clamp/clds/model/CldsEvent.java b/src/main/java/org/onap/clamp/clds/model/CldsEvent.java index e0caf7e3..0867b962 100644 --- a/src/main/java/org/onap/clamp/clds/model/CldsEvent.java +++ b/src/main/java/org/onap/clamp/clds/model/CldsEvent.java @@ -31,6 +31,7 @@ import org.onap.clamp.clds.dao.CldsDao; public class CldsEvent { public static final String ACTION_TEST = "TEST"; public static final String ACTION_CREATE = "CREATE"; + public static final String ACTION_MODIFY = "MODIFY"; public static final String ACTION_SUBMIT = "SUBMIT"; // an update before model is active public static final String ACTION_RESUBMIT = "RESUBMIT"; diff --git a/src/main/java/org/onap/clamp/clds/model/CldsModel.java b/src/main/java/org/onap/clamp/clds/model/CldsModel.java index af4d6c66..8b239956 100644 --- a/src/main/java/org/onap/clamp/clds/model/CldsModel.java +++ b/src/main/java/org/onap/clamp/clds/model/CldsModel.java @@ -97,9 +97,9 @@ public class CldsModel { public boolean canInventoryCall() { boolean canCall = false; - /* Below checks the clds event is submit/resubmit */ - if ((event.isActionCd(CldsEvent.ACTION_SUBMIT) || event.isActionCd(CldsEvent.ACTION_RESUBMIT) - || event.isActionCd(CldsEvent.ACTION_SUBMITDCAE))) { + /* Below checks the clds event is submit/resubmit/distribute */ + if (event.isActionCd(CldsEvent.ACTION_SUBMIT) || event.isActionCd(CldsEvent.ACTION_RESUBMIT) + || event.isActionCd(CldsEvent.ACTION_DISTRIBUTE) || event.isActionCd(CldsEvent.ACTION_SUBMITDCAE)) { canCall = true; } return canCall; @@ -128,7 +128,8 @@ public class CldsModel { || event.isActionAndStateCd(CldsEvent.ACTION_SUBMIT, CldsEvent.ACTION_STATE_ANY) || event.isActionAndStateCd(CldsEvent.ACTION_RESUBMIT, CldsEvent.ACTION_STATE_ANY) || event.isActionAndStateCd(CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_STATE_ANY) - || event.isActionAndStateCd(CldsEvent.ACTION_DELETE, CldsEvent.ACTION_STATE_RECEIVED)) { + || event.isActionAndStateCd(CldsEvent.ACTION_DELETE, CldsEvent.ACTION_STATE_RECEIVED) + || event.isActionAndStateCd(CldsEvent.ACTION_MODIFY, CldsEvent.ACTION_STATE_ANY)) { status = STATUS_DESIGN; } else if (event.isActionAndStateCd(CldsEvent.ACTION_DISTRIBUTE, CldsEvent.ACTION_STATE_RECEIVED) || event.isActionAndStateCd(CldsEvent.ACTION_UNDEPLOY, CldsEvent.ACTION_STATE_RECEIVED)) { @@ -181,32 +182,40 @@ public class CldsModel { String actionCd = getCurrentActionCd(); switch (actionCd) { case CldsEvent.ACTION_CREATE: - permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMIT, CldsEvent.ACTION_TEST); + permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMIT, CldsEvent.ACTION_TEST, + CldsEvent.ACTION_DELETE); if (isSimplifiedModel()) { - permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_TEST); + permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_TEST, + CldsEvent.ACTION_DELETE); + } + break; + case CldsEvent.ACTION_MODIFY: + permittedActionCd = Arrays.asList(CldsEvent.ACTION_RESUBMIT, CldsEvent.ACTION_DELETE); + if (isSimplifiedModel()) { + permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_DELETE); } break; case CldsEvent.ACTION_SUBMIT: case CldsEvent.ACTION_RESUBMIT: - // for 1702 delete is not currently implemented (and resubmit - // requires manually deleting artifact from sdc - permittedActionCd = Arrays.asList(CldsEvent.ACTION_RESUBMIT); + permittedActionCd = Arrays.asList(CldsEvent.ACTION_RESUBMIT, CldsEvent.ACTION_DELETE); break; case CldsEvent.ACTION_SUBMITDCAE: - permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMITDCAE); + permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_DELETE); break; case CldsEvent.ACTION_DISTRIBUTE: - permittedActionCd = Arrays.asList(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_RESUBMIT); + permittedActionCd = Arrays.asList(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_RESUBMIT, + CldsEvent.ACTION_DELETE); if (isSimplifiedModel()) { - permittedActionCd = Arrays.asList(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_SUBMITDCAE); + permittedActionCd = Arrays.asList(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_SUBMITDCAE, + CldsEvent.ACTION_DELETE); } break; case CldsEvent.ACTION_UNDEPLOY: permittedActionCd = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_DEPLOY, - CldsEvent.ACTION_RESUBMIT); + CldsEvent.ACTION_RESUBMIT, CldsEvent.ACTION_DELETE); if (isSimplifiedModel()) { permittedActionCd = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_DEPLOY, - CldsEvent.ACTION_SUBMITDCAE); + CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_DELETE); } break; case CldsEvent.ACTION_DEPLOY: @@ -215,19 +224,10 @@ public class CldsModel { break; case CldsEvent.ACTION_RESTART: case CldsEvent.ACTION_UPDATE: - // for 1702 delete is not currently implemented permittedActionCd = Arrays.asList(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_STOP, CldsEvent.ACTION_UNDEPLOY); break; - case CldsEvent.ACTION_DELETE: - if (getCurrentActionStateCd().equals(CldsEvent.ACTION_STATE_SENT)) { - permittedActionCd = Arrays.asList(); - } else { - permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMIT); - } - break; case CldsEvent.ACTION_STOP: - // for 1702 delete is not currently implemented permittedActionCd = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_RESTART, CldsEvent.ACTION_UNDEPLOY); break; diff --git a/src/main/java/org/onap/clamp/clds/model/properties/PolicyItem.java b/src/main/java/org/onap/clamp/clds/model/properties/PolicyItem.java index 337a9763..75bf6ae3 100644 --- a/src/main/java/org/onap/clamp/clds/model/properties/PolicyItem.java +++ b/src/main/java/org/onap/clamp/clds/model/properties/PolicyItem.java @@ -48,9 +48,9 @@ import java.util.List; * "targetResourceId","value":["Eace933104d443b496b8.nodes.heat.vpg"]}]]}] */ public class PolicyItem implements Cloneable { - protected static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyItem.class); protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); + private String id; private String recipe; private int maxRetries; @@ -59,6 +59,11 @@ public class PolicyItem implements Cloneable { private List parentPolicyConditions; private String actor; private String targetResourceId; + private String recipeInfo; + private String recipeLevel; + private String recipePayload; + private String oapRop; + private String oapLimit; /** * Parse Policy given json node. @@ -76,6 +81,11 @@ public class PolicyItem implements Cloneable { if (targetResourceId != null && targetResourceId.isEmpty()) { this.setTargetResourceId(null); } + recipeInfo = AbstractModelElement.getValueByName(node, "recipeInfo"); + recipeLevel = AbstractModelElement.getValueByName(node, "recipeLevel"); + recipePayload = AbstractModelElement.getValueByName(node, "recipeInput"); + oapRop = AbstractModelElement.getValueByName(node, "oapRop"); + oapLimit = AbstractModelElement.getValueByName(node, "oapLimit"); } /** @@ -184,6 +194,32 @@ public class PolicyItem implements Cloneable { this.targetResourceId = targetResourceId; } + public String getRecipeInfo() { + return recipeInfo; + } + + public String getRecipeLevel() { + return recipeLevel; + } + + public String getRecipePayload() { + return recipePayload; + } + + public String getOapRop() { + if (oapRop == null) { + oapRop = "0m"; + } + return oapRop; + } + + public String getOapLimit() { + if (oapLimit == null) { + oapLimit = "0"; + } + return oapLimit; + } + @Override public Object clone() throws CloneNotSupportedException { return super.clone(); diff --git a/src/main/java/org/onap/clamp/clds/model/properties/ResourceGroup.java b/src/main/java/org/onap/clamp/clds/model/properties/ResourceGroup.java deleted file mode 100644 index 114fbbcd..00000000 --- a/src/main/java/org/onap/clamp/clds/model/properties/ResourceGroup.java +++ /dev/null @@ -1,114 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END============================================ - * =================================================================== - * - */ - -package org.onap.clamp.clds.model.properties; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -/** - * Parse Resource Group json properties. - * - * Example json: - * {"TCA_0aji7go":{"Group1":[{"name":"rgname","value":"1493749598520"},{ - * "name":"rgfriendlyname","value":"Group1"},{"name":"policyName","value": - * "Policy1"},{"name":"policyId","value":"1"},{"serviceConfigurations":[[{"name" - * :"aaiMatchingFields","value":["complex.city","vserver.vserver-name"]},{"name" - * :"aaiSendFields","value":["complex.city","vserver.vserver-name"]},{"name": - * "eventSeverity","value":["OK"]},{"name":"eventSourceType","value":[""]},{ - * "name":"timeWindow","value":["100"]},{"name":"ageLimit","value":["100"]},{ - * "name":"createClosedLoopEventId","value":["Initial"]},{"name": - * "outputEventName","value":["ONSET"]}]]}],"Group2":[{"name":"rgname","value": - * "1493749665149"},{"name":"rgfriendlyname","value":"Group2"},{"name": - * "policyName","value":"Policy2"},{"name":"policyId","value":"2"},{ - * "serviceConfigurations":[[{"name":"aaiMatchingFields","value":[ - * "cloud-region.identity-url","vserver.vserver-name"]},{"name":"aaiSendFields", - * "value":["cloud-region.identity-url","vserver.vserver-name"]},{"name": - * "eventSeverity","value":["NORMAL"]},{"name":"eventSourceType","value":[""]},{ - * "name":"timeWindow","value":["1000"]},{"name":"ageLimit","value":["1000"]},{ - * "name":"createClosedLoopEventId","value":["Initial"]},{"name": - * "outputEventName","value":["ONSET"]}],[{"name":"aaiMatchingFields","value":[ - * "generic-vnf.vnf-name","vserver.vserver-name"]},{"name":"aaiSendFields", - * "value":["generic-vnf.vnf-name","vserver.vserver-name"]},{"name": - * "eventSeverity","value":["CRITICAL"]},{"name":"eventSourceType","value":[""]} - * ,{"name":"timeWindow","value":["3000"]},{"name":"ageLimit","value":["3000"]}, - * {"name":"createClosedLoopEventId","value":["Initial"]},{"name": - * "outputEventName","value":["ABATED"]}]]}]}} - * - */ -public class ResourceGroup { - - protected static final EELFLogger logger = EELFManager.getInstance().getLogger(ResourceGroup.class); - protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); - - private String groupNumber; - private String policyId; - private List serviceConfigurations; - - /** - * Parse String Match Resource Group given json node. - * - * @param modelBpmn - * @param modelJson - */ - public ResourceGroup(JsonNode node) { - - groupNumber = AbstractModelElement.getValueByName(node, "rgname"); - policyId = AbstractModelElement.getValueByName(node, "policyId"); - - // process Server_Configurations - JsonNode serviceConfigurationsNode = node.get(node.size() - 1).get("serviceConfigurations"); - Iterator itr = serviceConfigurationsNode.elements(); - serviceConfigurations = new ArrayList<>(); - while (itr.hasNext()) { - serviceConfigurations.add(new ServiceConfiguration(itr.next())); - } - } - - /** - * @return the groupNumber - */ - public String getGroupNumber() { - return groupNumber; - } - - /** - * @return the policyId - */ - public String getPolicyId() { - return policyId; - } - - /** - * @return the serviceConfigurations - */ - public List getServiceConfigurations() { - return serviceConfigurations; - } - -} diff --git a/src/main/java/org/onap/clamp/clds/model/properties/ServiceConfiguration.java b/src/main/java/org/onap/clamp/clds/model/properties/ServiceConfiguration.java deleted file mode 100644 index 04399bf9..00000000 --- a/src/main/java/org/onap/clamp/clds/model/properties/ServiceConfiguration.java +++ /dev/null @@ -1,181 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END============================================ - * =================================================================== - * - */ - -package org.onap.clamp.clds.model.properties; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; - -/** - * Parse serviceConfigurations from Tca json properties. - *

- * Example json: - * {"Tca_0aji7go":{"Group1":[{"name":"rgname","value":"1493749598520"},{ - * "name":"rgfriendlyname","value":"Group1"},{"name":"policyName","value": - * "Policy1"},{"name":"policyId","value":"1"},{"serviceConfigurations":[[{"name" - * :"aaiMatchingFields","value":["complex.city","vserver.vserver-name"]},{"name" - * :"aaiSendFields","value":["complex.city","vserver.vserver-name"]},{"name": - * "eventSeverity","value":["OK"]},{"name":"eventSourceType","value":[""]},{ - * "name":"timeWindow","value":["100"]},{"name":"ageLimit","value":["100"]},{ - * "name":"createClosedLoopEventId","value":["Initial"]},{"name": - * "outputEventName","value":["ONSET"]}]]}],"Group2":[{"name":"rgname","value": - * "1493749665149"},{"name":"rgfriendlyname","value":"Group2"},{"name": - * "policyName","value":"Policy2"},{"name":"policyId","value":"2"},{ - * "serviceConfigurations":[[{"name":"aaiMatchingFields","value":[ - * "cloud-region.identity-url","vserver.vserver-name"]},{"name":"aaiSendFields", - * "value":["cloud-region.identity-url","vserver.vserver-name"]},{"name": - * "eventSeverity","value":["NORMAL"]},{"name":"eventSourceType","value":[""]},{ - * "name":"timeWindow","value":["1000"]},{"name":"ageLimit","value":["1000"]},{ - * "name":"createClosedLoopEventId","value":["Initial"]},{"name": - * "outputEventName","value":["ONSET"]}],[{"name":"aaiMatchingFields","value":[ - * "generic-vnf.vnf-name","vserver.vserver-name"]},{"name":"aaiSendFields", - * "value":["generic-vnf.vnf-name","vserver.vserver-name"]},{"name": - * "eventSeverity","value":["CRITICAL"]},{"name":"eventSourceType","value":[""]} - * ,{"name":"timeWindow","value":["3000"]},{"name":"ageLimit","value":["3000"]}, - * {"name":"createClosedLoopEventId","value":["Initial"]},{"name": - * "outputEventName","value":["ABATED"]}]]}]}} - * - */ -public class ServiceConfiguration { - - protected static final EELFLogger logger = EELFManager.getInstance().getLogger(ServiceConfiguration.class); - protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); - - private final List aaiMatchingFields; - private final List aaiSendFields; - // private final String groupNumber; - private final List resourceVf; - private final List resourceVfc; - private final String timeWindow; - private final String ageLimit; - private final String createClosedLoopEventId; - private final String outputEventName; - private final Map stringSet; - - /** - * Parse serviceConfigurations given json node. - * - * @param node - */ - public ServiceConfiguration(JsonNode node) { - aaiMatchingFields = AbstractModelElement.getValuesByName(node, "aaiMatchingFields"); - aaiSendFields = AbstractModelElement.getValuesByName(node, "aaiSendFields"); - // groupNumber = ModelElement.getValueByName(node, "groupNumber"); - resourceVf = AbstractModelElement.getValuesByName(node, "vf"); - resourceVfc = AbstractModelElement.getValuesByName(node, "vfc"); - timeWindow = AbstractModelElement.getValueByName(node, "timeWindow"); - ageLimit = AbstractModelElement.getValueByName(node, "ageLimit"); - createClosedLoopEventId = AbstractModelElement.getValueByName(node, "createClosedLoopEventId"); - outputEventName = AbstractModelElement.getValueByName(node, "outputEventName"); - - // process the stringSet fields - JsonNode ssNodes = node.findPath("stringSet"); - Iterator itr = ssNodes.elements(); - stringSet = new HashMap<>(); - while (itr.hasNext()) { - JsonNode ssNode = itr.next(); - String key = ssNode.path("name").asText(); - String value = ssNode.path("value").path(0).asText(); - if (key.length() != 0 && value.length() != 0) { - // only add string set field if not null - logger.debug("stringSet: " + key + "=" + value); - stringSet.put(key, value); - } - } - } - - /** - * @return the aaiMatchingFields - */ - public List getaaiMatchingFields() { - return aaiMatchingFields; - } - - /** - * @return the aaiSendFields - */ - public List getaaiSendFields() { - return aaiSendFields; - } - - /** - * @return the groupNumber - */ /* - * public String getGroupNumber() { return groupNumber; } - */ - /** - * @return the resourceVf - */ - public List getResourceVf() { - return resourceVf; - } - - /** - * @return the resourceVfc - */ - public List getResourceVfc() { - return resourceVfc; - } - - /** - * @return the timeWindow - */ - public String getTimeWindow() { - return timeWindow; - } - - /** - * @return the ageLimit - */ - public String getAgeLimit() { - return ageLimit; - } - - /** - * @return the createClosedLoopEventId - */ - public String getCreateClosedLoopEventId() { - return createClosedLoopEventId; - } - - /** - * @return the outputEventName - */ - public String getOutputEventName() { - return outputEventName; - } - - /** - * @return the stringSet - */ - public Map getStringSet() { - return stringSet; - } - -} diff --git a/src/main/java/org/onap/clamp/clds/service/CldsHealthcheckService.java b/src/main/java/org/onap/clamp/clds/service/CldsHealthcheckService.java new file mode 100644 index 00000000..18533ad5 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/service/CldsHealthcheckService.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + */ +package org.onap.clamp.clds.service; + +import java.util.Date; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.onap.clamp.clds.dao.CldsDao; +import org.onap.clamp.clds.model.CldsHealthCheck; +import org.onap.clamp.clds.util.LoggingUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +/** + * Service to retrieve the Health Check of the clds application. + * + */ +@Component +@Path("/") +public class CldsHealthcheckService { + + @Autowired + private CldsDao cldsDao; + + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsHealthcheckService.class); + + /** + * REST service that retrieves clds healthcheck information. + * + * @return CldsHealthCheck class containing healthcheck info + */ + @GET + @Path("/healthcheck") + @Produces(MediaType.APPLICATION_JSON) + public Response gethealthcheck() { + CldsHealthCheck cldsHealthCheck = new CldsHealthCheck(); + Date startTime = new Date(); + LoggingUtils.setRequestContext("CldsService: GET healthcheck", "Clamp-Health-Check"); + LoggingUtils.setTimeContext(startTime, new Date()); + boolean healthcheckFailed = false; + try { + cldsDao.doHealthCheck(); + cldsHealthCheck.setHealthCheckComponent("CLDS-APP"); + cldsHealthCheck.setHealthCheckStatus("UP"); + cldsHealthCheck.setDescription("OK"); + LoggingUtils.setResponseContext("0", "Get healthcheck success", this.getClass().getName()); + } catch (Exception e) { + healthcheckFailed = true; + logger.error("CLAMP application Heath check failed", e); + LoggingUtils.setResponseContext("999", "Get healthcheck failed", this.getClass().getName()); + cldsHealthCheck.setHealthCheckComponent("CLDS-APP"); + cldsHealthCheck.setHealthCheckStatus("DOWN"); + cldsHealthCheck.setDescription("NOT-OK"); + } + // audit log + LoggingUtils.setTimeContext(startTime, new Date()); + if(healthcheckFailed) { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(cldsHealthCheck).build(); + } else { + return Response.status(Response.Status.OK).entity(cldsHealthCheck).build(); + } + } +} \ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/service/CldsService.java b/src/main/java/org/onap/clamp/clds/service/CldsService.java index 9b68845c..7cc9af9b 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsService.java @@ -353,6 +353,8 @@ public class CldsService extends SecureServiceBase { cldsModel.setBpmnText(template.getBpmnText()); } } + updateAndInsertNewEvent(cldsModel.getName(), cldsModel.getControlNamePrefix(), cldsModel.getEvent(), + CldsEvent.ACTION_MODIFY); cldsModel.save(cldsDao, getUserId()); // audit log LoggingUtils.setTimeContext(startTime, new Date()); @@ -442,6 +444,7 @@ public class CldsService extends SecureServiceBase { this.fillInCldsModel(model); // save model to db model.setName(modelName); + updateAndInsertNewEvent(modelName, model.getControlNamePrefix(), model.getEvent(), CldsEvent.ACTION_MODIFY); model.save(cldsDao, getUserId()); // get vars and format if necessary String prop = model.getPropText(); @@ -477,14 +480,16 @@ public class CldsService extends SecureServiceBase { logger.info("docText - " + docText); try { String result = camelProxy.submit(actionCd, prop, bpmnJson, modelName, controlName, docText, isTest, - userId, isInsertTestEvent); + userId, isInsertTestEvent, model.getEvent().getActionCd()); logger.info("Starting Camel flow on request, result is: ", result); } catch (SdcCommunicationException | PolicyClientException | BadRequestException e) { errorCase = true; logger.error("Exception occured during invoking Camel process", e); } - // refresh model info from db (get fresh event info) - retrievedModel = CldsModel.retrieve(cldsDao, modelName, false); + if (!actionCd.equalsIgnoreCase(CldsEvent.ACTION_DELETE)) { + // refresh model info from db (get fresh event info) + retrievedModel = CldsModel.retrieve(cldsDao, modelName, false); + } if (!isTest && (actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMIT) || actionCd.equalsIgnoreCase(CldsEvent.ACTION_RESUBMIT) || actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMITDCAE))) { @@ -955,4 +960,19 @@ public class CldsService extends SecureServiceBase { } } } + + private void updateAndInsertNewEvent(String cldsModelName, String cldsControlNamePrfx, CldsEvent event, + String newAction) { + // If model action is in submit/resubmit/distributed and user try + // to save then we are changing action back to create. + if (event != null && (CldsEvent.ACTION_SUBMIT.equalsIgnoreCase(event.getActionCd()) + || CldsEvent.ACTION_RESUBMIT.equalsIgnoreCase(event.getActionCd()) + || CldsEvent.ACTION_DISTRIBUTE.equalsIgnoreCase(event.getActionCd()))) { + CldsEvent newEvent = new CldsEvent(); + newEvent.setUserid(getUserId()); + newEvent.setActionCd(newAction); + newEvent.setActionStateCd(CldsEvent.ACTION_STATE_COMPLETED); + cldsDao.insEvent(cldsModelName, cldsControlNamePrfx, null, newEvent); + } + } } \ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/service/SecureServiceBase.java b/src/main/java/org/onap/clamp/clds/service/SecureServiceBase.java index 94ae2990..22fe4a8e 100644 --- a/src/main/java/org/onap/clamp/clds/service/SecureServiceBase.java +++ b/src/main/java/org/onap/clamp/clds/service/SecureServiceBase.java @@ -103,39 +103,20 @@ public abstract class SecureServiceBase { * In case of issues with the permission test, error is returned * in this exception */ - public boolean isAuthorized(SecureServicePermission inPermission) throws NotAuthorizedException { - boolean authorized = false; - - Date startTime = new Date(); - LoggingUtils.setTargetContext("CLDS", "isAuthorized"); - LoggingUtils.setTimeContext(startTime, new Date()); - - securityLogger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission); - - // check if the user has the permission key or the permission key with a - // combination of all instance and/or all action. - if (securityContext.isUserInRole(inPermission.getKey())) { - securityLogger.info("{} authorized for permission: {}", getPrincipalName(), inPermission.getKey()); - authorized = true; - // the rest of these don't seem to be required - isUserInRole method - // appears to take * as a wildcard - } else if (securityContext.isUserInRole(inPermission.getKeyAllInstance())) { - securityLogger.info("{} authorized because user has permission with * for instance: {}", getPrincipalName(), inPermission.getKey()); - authorized = true; - } else if (securityContext.isUserInRole(inPermission.getKeyAllInstanceAction())) { - securityLogger.info("{} authorized because user has permission with * for instance and * for action: {}", getPrincipalName(), inPermission.getKey()); - authorized = true; - } else if (securityContext.isUserInRole(inPermission.getKeyAllAction())) { - securityLogger.info("{} authorized because user has permission with * for action: {}", getPrincipalName(), inPermission.getKey()); - authorized = true; - } else { - String msg = getPrincipalName() + " does not have permission: " + inPermission; - LoggingUtils.setErrorContext("100", "Authorization Error"); - securityLogger.warn(msg); - throw new NotAuthorizedException(msg); - } - return authorized; - } + public boolean isAuthorized(SecureServicePermission inPermission) throws NotAuthorizedException { + Date startTime = new Date(); + LoggingUtils.setTargetContext("CLDS", "isAuthorized"); + LoggingUtils.setTimeContext(startTime, new Date()); + securityLogger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission); + try { + return isUserPermitted(inPermission); + } catch (NotAuthorizedException nae) { + String msg = getPrincipalName() + " does not have permission: " + inPermission; + LoggingUtils.setErrorContext("100", "Authorization Error"); + securityLogger.warn(msg); + throw new NotAuthorizedException(msg); + } + } /** * Check if user is authorized for the given aaf permission. Allow matches @@ -150,38 +131,20 @@ public abstract class SecureServiceBase { * @return A boolean to indicate if the user has the permission to do * execute the inPermission */ - public boolean isAuthorizedNoException(SecureServicePermission inPermission) { - boolean authorized = false; - - securityLogger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission); - Date startTime = new Date(); - LoggingUtils.setTargetContext("CLDS", "isAuthorizedNoException"); - LoggingUtils.setTimeContext(startTime, new Date()); - - // check if the user has the permission key or the permission key with a - // combination of all instance and/or all action. - if (securityContext.isUserInRole(inPermission.getKey())) { - securityLogger.info("{} authorized for permission: {}", getPrincipalName(), inPermission.getKey()); - authorized = true; - // the rest of these don't seem to be required - isUserInRole method - // appears to take * as a wildcard - } else if (securityContext.isUserInRole(inPermission.getKeyAllInstance())) { - securityLogger.info("{} authorized because user has permission with * for instance: {}", getPrincipalName(),inPermission.getKey()); - authorized = true; - } else if (securityContext.isUserInRole(inPermission.getKeyAllInstanceAction())) { - securityLogger.info("{} authorized because user has permission with * for instance and * for action: {}", getPrincipalName(), inPermission.getKey()); - authorized = true; - } else if (securityContext.isUserInRole(inPermission.getKeyAllAction())) { - securityLogger.info("{} authorized because user has permission with * for action: {}", getPrincipalName(), inPermission.getKey()); - authorized = true; - } else { - String msg = getPrincipalName() + " does not have permission: " + inPermission; - LoggingUtils.setErrorContext("100", "Authorization Error"); - securityLogger.warn(msg); - logger.warn(msg); - } - return authorized; - } + public boolean isAuthorizedNoException(SecureServicePermission inPermission) { + securityLogger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission); + Date startTime = new Date(); + LoggingUtils.setTargetContext("CLDS", "isAuthorizedNoException"); + LoggingUtils.setTimeContext(startTime, new Date()); + try { + return isUserPermitted(inPermission); + } catch (NotAuthorizedException nae) { + String msg = getPrincipalName() + " does not have permission: " + inPermission; + LoggingUtils.setErrorContext("100", "Authorization Error"); + securityLogger.warn(msg); + } + return false; + } /** * This method can be used by the Application.class to set the @@ -200,5 +163,28 @@ public abstract class SecureServiceBase { public void setSecurityContext(SecurityContext securityContext) { this.securityContext = securityContext; } - -} + + private boolean isUserPermitted(SecureServicePermission inPermission) throws NotAuthorizedException { + boolean authorized = false; + // check if the user has the permission key or the permission key with a + // combination of all instance and/or all action. + if (securityContext.isUserInRole(inPermission.getKey())) { + securityLogger.info("{} authorized for permission: {}", getPrincipalName(), inPermission.getKey()); + authorized = true; + // the rest of these don't seem to be required - isUserInRole method + // appears to take * as a wildcard + } else if (securityContext.isUserInRole(inPermission.getKeyAllInstance())) { + securityLogger.info("{} authorized because user has permission with * for instance: {}", getPrincipalName(), inPermission.getKey()); + authorized = true; + } else if (securityContext.isUserInRole(inPermission.getKeyAllInstanceAction())) { + securityLogger.info("{} authorized because user has permission with * for instance and * for action: {}", getPrincipalName(), inPermission.getKey()); + authorized = true; + } else if (securityContext.isUserInRole(inPermission.getKeyAllAction())) { + securityLogger.info("{} authorized because user has permission with * for action: {}", getPrincipalName(), inPermission.getKey()); + authorized = true; + } else { + throw new NotAuthorizedException(""); + } + return authorized; + } +} \ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java b/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java index 9f408105..07c4147b 100644 --- a/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java +++ b/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java @@ -65,6 +65,12 @@ public final class CryptoUtils { * Definition of encryption algorithm. */ private static final String ALGORITHM = "AES"; + + /** + * AES Encryption Key environment variable for external configuration + */ + private static final String AES_ENCRYPTION_KEY = "AES_ENCRYPTION_KEY"; + /** * Detailed definition of encryption algorithm. */ @@ -156,8 +162,15 @@ public final class CryptoUtils { private static SecretKeySpec readSecretKeySpec(String propertiesFileName) { Properties props = new Properties(); try { - props.load(ResourceFileUtil.getResourceAsStream(propertiesFileName)); - return getSecretKeySpec(props.getProperty(KEY_PARAM)); + //Workaround fix to make encryption key configurable. + //System environment variable takes precedence for over clds/key.properties + String encryptionKey = System.getenv(AES_ENCRYPTION_KEY); + if(encryptionKey != null && encryptionKey.trim().length() > 0) { + return getSecretKeySpec(encryptionKey); + } else { + props.load(ResourceFileUtil.getResourceAsStream(propertiesFileName)); + return getSecretKeySpec(props.getProperty(KEY_PARAM)); + } } catch (IOException | DecoderException e) { logger.error("Exception occurred during the key reading", e); return null; diff --git a/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java b/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java index e4f9ce3a..7a6667c4 100644 --- a/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java +++ b/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java @@ -62,6 +62,8 @@ public final class LoggingUtils { MDC.put("RequestId", UUID.randomUUID().toString()); MDC.put("ServiceName", service); MDC.put("PartnerName", partner); + //Defaulting to HTTP/1.1 protocol + MDC.put("Protocol", "HTTP/1.1"); try { MDC.put("ServerFQDN", InetAddress.getLocalHost().getCanonicalHostName()); MDC.put("ServerIPAddress", InetAddress.getLocalHost().getHostAddress()); diff --git a/src/main/resources/clds/camel/flexible-flow.xml b/src/main/resources/clds/camel/flexible-flow.xml index 16daec92..8305c2e4 100644 --- a/src/main/resources/clds/camel/flexible-flow.xml +++ b/src/main/resources/clds/camel/flexible-flow.xml @@ -10,11 +10,13 @@ 30000 + ${exchangeProperty.actionCd} == 'DELETE' + 30000 @@ -29,18 +31,20 @@ 30000 + ${exchangeProperty.actionCd} == 'STOP' + ${exchangeProperty.actionCd} == 'RESTART' + - \ No newline at end of file diff --git a/src/test/java/org/onap/clamp/clds/it/CldsHealthcheckServiceItCase.java b/src/test/java/org/onap/clamp/clds/it/CldsHealthcheckServiceItCase.java new file mode 100644 index 00000000..40e87688 --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/it/CldsHealthcheckServiceItCase.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + */ + +package org.onap.clamp.clds.it; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import javax.ws.rs.core.Response; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.clamp.clds.model.CldsHealthCheck; +import org.onap.clamp.clds.service.CldsHealthcheckService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * Tests HealthCheck Service. + */ +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class CldsHealthcheckServiceItCase { + + @Autowired + private CldsHealthcheckService cldsHealthcheckService; + + @Test + public void testGetHealthCheck() { + Response response = cldsHealthcheckService.gethealthcheck(); + CldsHealthCheck cldsHealthCheck = (CldsHealthCheck) response.getEntity(); + assertNotNull(cldsHealthCheck); + assertEquals("UP", cldsHealthCheck.getHealthCheckStatus()); + assertEquals("CLDS-APP", cldsHealthCheck.getHealthCheckComponent()); + assertEquals("OK", cldsHealthCheck.getDescription()); + } +} diff --git a/src/test/java/org/onap/clamp/clds/it/OperationPolicyReqItCase.java b/src/test/java/org/onap/clamp/clds/it/OperationPolicyReqItCase.java index ba3df843..b6f3ef42 100644 --- a/src/test/java/org/onap/clamp/clds/it/OperationPolicyReqItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/OperationPolicyReqItCase.java @@ -73,10 +73,10 @@ public class OperationPolicyReqItCase { assertTrue(attributes.size() == 2); // now validate the Yaml, to do so we replace the dynamic ID by a known // key so that we can compare it - String yaml = URLDecoder.decode(attributes.get(0).get(AttributeType.RULE).get("ControlLoopYaml"), "UTF-8"); + String yaml = URLDecoder.decode(attributes.get(0).get(AttributeType.RULE).get("controlLoopYaml"), "UTF-8"); yaml = replaceGeneratedValues(yaml); assertEquals(ResourceFileUtil.getResourceAsString("example/operational-policy/yaml-policy-chain-1.yaml"), yaml); - yaml = URLDecoder.decode(attributes.get(1).get(AttributeType.RULE).get("ControlLoopYaml"), "UTF-8"); + yaml = URLDecoder.decode(attributes.get(1).get(AttributeType.RULE).get("controlLoopYaml"), "UTF-8"); yaml = replaceGeneratedValues(yaml); assertEquals(ResourceFileUtil.getResourceAsString("example/operational-policy/yaml-policy-chain-2.yaml"), yaml); } diff --git a/src/test/java/org/onap/clamp/clds/model/CldsModelTest.java b/src/test/java/org/onap/clamp/clds/model/CldsModelTest.java index 82c668c2..6ebdc4bb 100644 --- a/src/test/java/org/onap/clamp/clds/model/CldsModelTest.java +++ b/src/test/java/org/onap/clamp/clds/model/CldsModelTest.java @@ -145,23 +145,6 @@ public class CldsModelTest { fail("Exception should have been sent"); } - @Test(expected = IllegalArgumentException.class) - public void testValidateActionFromDelete() { - CldsModel cldsModel = new CldsModel(); - cldsModel.getEvent().setActionCd(CldsEvent.ACTION_DELETE); - cldsModel.validateAction(CldsEvent.ACTION_SUBMIT); - try { - cldsModel.validateAction(CldsEvent.ACTION_CREATE); - fail("Exception should have been sent"); - } catch (IllegalArgumentException e) { - System.out.println("Exception caught IllegalArgumentException as expected"); - } - cldsModel.getEvent().setActionCd(CldsEvent.ACTION_DELETE); - cldsModel.getEvent().setActionStateCd(CldsEvent.ACTION_STATE_SENT); - cldsModel.validateAction(CldsEvent.ACTION_SUBMIT); - fail("Exception should have been sent"); - } - @Test(expected = IllegalArgumentException.class) public void testValidateActionFromStop() { CldsModel cldsModel = new CldsModel(); diff --git a/src/test/java/org/onap/clamp/clds/swagger/SwaggerConfig.java b/src/test/java/org/onap/clamp/clds/swagger/SwaggerConfig.java index 87409644..96784dd6 100644 --- a/src/test/java/org/onap/clamp/clds/swagger/SwaggerConfig.java +++ b/src/test/java/org/onap/clamp/clds/swagger/SwaggerConfig.java @@ -23,24 +23,17 @@ package org.onap.clamp.clds.swagger; import org.springframework.context.annotation.Configuration; + import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.service.*; -import springfox.documentation.spi.DocumentationType; +import springfox.documentation.service.ApiInfo; import springfox.documentation.swagger2.annotations.EnableSwagger2; - - - @EnableSwagger2 @Configuration public class SwaggerConfig { private ApiInfo apiInfo() { - return new ApiInfoBuilder() - .title("Clamp") - .description("Clamp API Description") - .license("Apache 2.0") - .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0") - .build(); + return new ApiInfoBuilder().title("Clamp").description("Clamp API Description").license("Apache 2.0") + .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0").build(); } } diff --git a/src/test/java/org/onap/clamp/clds/swagger/SwaggerGenerationTest.java b/src/test/java/org/onap/clamp/clds/swagger/SwaggerGenerationTest.java index a4691b16..363d12d4 100644 --- a/src/test/java/org/onap/clamp/clds/swagger/SwaggerGenerationTest.java +++ b/src/test/java/org/onap/clamp/clds/swagger/SwaggerGenerationTest.java @@ -19,19 +19,24 @@ * ============LICENSE_END============================================ * =================================================================== */ + package org.onap.clamp.clds.swagger; +import java.nio.file.Path; +import java.nio.file.Paths; + import org.junit.Test; import org.junit.runner.RunWith; +import org.onap.clamp.clds.Application; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.nio.file.Path; -import java.nio.file.Paths; + import io.github.swagger2markup.Swagger2MarkupConverter; -import org.onap.clamp.clds.Application; @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = {Application.class, SwaggerConfig.class}) +@SpringBootTest(classes = { + Application.class, SwaggerConfig.class +}) public class SwaggerGenerationTest { @Test diff --git a/src/test/resources/clds/key.properties b/src/test/resources/clds/key.properties deleted file mode 100644 index dda81104..00000000 --- a/src/test/resources/clds/key.properties +++ /dev/null @@ -1 +0,0 @@ -org.onap.clamp.encryption.aes.key=aa3871669d893c7fb8abbcda31b88b4f \ No newline at end of file diff --git a/version.properties b/version.properties index 614d4714..22b38287 100644 --- a/version.properties +++ b/version.properties @@ -25,9 +25,9 @@ # Note that these variables cannot be structured (e.g. : version.release or version.snapshot etc... ) # because they are used in Jenkins, whose plug-in doesn't support -major=2 +major=3 minor=0 -patch=2 +patch=0 base_version=${major}.${minor}.${patch} -- 2.16.6