diff options
author | Benjamin, Max (mb388a) <mb388a@us.att.com> | 2019-04-08 14:14:34 -0400 |
---|---|---|
committer | Benjamin, Max (mb388a) <mb388a@us.att.com> | 2019-04-08 14:24:59 -0400 |
commit | f47919f1fe367b612fa9c96d34c59f01a541e882 (patch) | |
tree | 5b6aa2fc36747d868897e68ccbec0c6db0aee81c /adapters/mso-openstack-adapters/src/main/java | |
parent | 54452b80a1cf4d22ef750bc1377f8c1b05431d57 (diff) |
Replaced all tabs with spaces in java and pom.xml
Added in maven plugins to enforce coding style rules
Added in eclipse java formatting xml
Change-Id: I3727bbf4ce8dc66abfd8ad21b6cfd0890c5d3ff0
Issue-ID: SO-1765
Signed-off-by: Benjamin, Max (mb388a) <mb388a@us.att.com>
Diffstat (limited to 'adapters/mso-openstack-adapters/src/main/java')
114 files changed, 11688 insertions, 13566 deletions
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAudit.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAudit.java index a2c117b3d9..149de0b698 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAudit.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAudit.java @@ -2,55 +2,55 @@ package org.onap.so.adapters.audit; import java.io.Serializable; import java.net.URI; - import org.onap.so.client.aai.AAIObjectType; import org.apache.commons.lang3.builder.ToStringBuilder; -public class AAIObjectAudit implements Serializable{ - - /** - * - */ - private static final long serialVersionUID = -4560928512855386021L; - private boolean doesObjectExist = false; - private Object aaiObject; - private URI resourceURI; - private String aaiObjectType; - - @Override - public String toString() { - return new ToStringBuilder(this).append("doesObjectExist", doesObjectExist).append("aaiObject", aaiObject) - .append("resourceURI", resourceURI).append("aaiObjectType", aaiObjectType).toString(); - } - - public String getAaiObjectType() { - return aaiObjectType; - } - - public void setAaiObjectType(String aaiObjectType) { - this.aaiObjectType = aaiObjectType; - } - - public boolean isDoesObjectExist() { - return doesObjectExist; - } - - public void setDoesObjectExist(boolean doesObjectExist) { - this.doesObjectExist = doesObjectExist; - } - - public Object getAaiObject() { - return aaiObject; - } - - public void setAaiObject(Object aaiObject) { - this.aaiObject = aaiObject; - } - - public URI getResourceURI() { - return resourceURI; - } - public void setResourceURI(URI resourceURI) { - this.resourceURI = resourceURI; - } -}
\ No newline at end of file +public class AAIObjectAudit implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -4560928512855386021L; + private boolean doesObjectExist = false; + private Object aaiObject; + private URI resourceURI; + private String aaiObjectType; + + @Override + public String toString() { + return new ToStringBuilder(this).append("doesObjectExist", doesObjectExist).append("aaiObject", aaiObject) + .append("resourceURI", resourceURI).append("aaiObjectType", aaiObjectType).toString(); + } + + public String getAaiObjectType() { + return aaiObjectType; + } + + public void setAaiObjectType(String aaiObjectType) { + this.aaiObjectType = aaiObjectType; + } + + public boolean isDoesObjectExist() { + return doesObjectExist; + } + + public void setDoesObjectExist(boolean doesObjectExist) { + this.doesObjectExist = doesObjectExist; + } + + public Object getAaiObject() { + return aaiObject; + } + + public void setAaiObject(Object aaiObject) { + this.aaiObject = aaiObject; + } + + public URI getResourceURI() { + return resourceURI; + } + + public void setResourceURI(URI resourceURI) { + this.resourceURI = resourceURI; + } +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAuditList.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAuditList.java index a1a8d5b5ed..f3a2cfea9b 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAuditList.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AAIObjectAuditList.java @@ -5,21 +5,21 @@ import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.builder.ToStringBuilder; -public class AAIObjectAuditList implements Serializable{ +public class AAIObjectAuditList implements Serializable { - /** - * - */ - private static final long serialVersionUID = 6712662349909726930L; - private List<AAIObjectAudit> auditList = new ArrayList<>(); + /** + * + */ + private static final long serialVersionUID = 6712662349909726930L; + private List<AAIObjectAudit> auditList = new ArrayList<>(); - @Override - public String toString() { - return new ToStringBuilder(this).append("auditList", auditList).toString(); - } + @Override + public String toString() { + return new ToStringBuilder(this).append("auditList", auditList).toString(); + } - public List<AAIObjectAudit> getAuditList() { - return auditList; - } + public List<AAIObjectAudit> getAuditList() { + return auditList; + } -}
\ No newline at end of file +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAudit.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAudit.java index 292cebf292..ad28f0daeb 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAudit.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAudit.java @@ -23,17 +23,17 @@ package org.onap.so.adapters.audit; import org.onap.so.client.aai.AAIResourcesClient; public class AbstractAudit { - - private AAIResourcesClient aaiClient; - protected AAIResourcesClient getAaiClient(){ - if(aaiClient == null) - return new AAIResourcesClient(); - else - return aaiClient; - } - - protected void setAaiClient(AAIResourcesClient aaiResource){ - aaiClient = aaiResource; - } + private AAIResourcesClient aaiClient; + + protected AAIResourcesClient getAaiClient() { + if (aaiClient == null) + return new AAIResourcesClient(); + else + return aaiClient; + } + + protected void setAaiClient(AAIResourcesClient aaiResource) { + aaiClient = aaiResource; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAuditService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAuditService.java index 710a6ddc13..52f5478f2f 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAuditService.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAuditService.java @@ -1,7 +1,6 @@ package org.onap.so.adapters.audit; import java.util.Optional; - import org.camunda.bpm.client.task.ExternalTask; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.slf4j.Logger; @@ -13,63 +12,64 @@ import org.springframework.stereotype.Component; @Component public abstract class AbstractAuditService { - - private static final Logger logger = LoggerFactory.getLogger(AbstractAuditService.class); - - - - protected static final String UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI = "Unable to find all VServers and L-Interaces in A&AI"; - - @Autowired - public Environment env; - - /** - * @param auditHeatStackFailed - * @param auditList - * @return - */ - protected boolean didCreateAuditFail(Optional<AAIObjectAuditList> auditList) { - if (auditList.get().getAuditList() != null && !auditList.get().getAuditList().isEmpty()) { - if (logger.isInfoEnabled()) { - logger.info("Audit Results: {}", auditList.get().toString()); - } - return auditList.get().getAuditList().stream().filter(auditObject -> !auditObject.isDoesObjectExist()) - .findFirst().map(v -> true).orElse(false); - } else { - return false; - } - } - - /** - * @param auditHeatStackFailed - * @param auditList - * @return - */ - protected boolean didDeleteAuditFail(Optional<AAIObjectAuditList> auditList) { - if (auditList.get().getAuditList() != null && !auditList.get().getAuditList().isEmpty()) { - if (logger.isInfoEnabled()) { - logger.info("Audit Results: {}", auditList.get().toString()); - } - return auditList.get().getAuditList().stream().filter(AAIObjectAudit::isDoesObjectExist) - .findFirst().map(v -> true).orElse(false); - } else { - return false; - } - } - - protected String[] getRetrySequence() { - return env.getProperty("mso.workflow.topics.retrySequence",String[].class); - } - - protected void setupMDC(ExternalTask externalTask) { - String msoRequestId = externalTask.getVariable("mso-request-id"); - if(msoRequestId != null && !msoRequestId.isEmpty()) - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, msoRequestId); - } - - protected long calculateRetryDelay(int currentRetries){ - int retrySequence = getRetrySequence().length - currentRetries; - long retryMultiplier = Long.parseLong(env.getProperty("mso.workflow.topics.retryMultiplier","6000")); - return Integer.parseInt(getRetrySequence()[retrySequence]) * retryMultiplier; - } + + private static final Logger logger = LoggerFactory.getLogger(AbstractAuditService.class); + + + + protected static final String UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI = + "Unable to find all VServers and L-Interaces in A&AI"; + + @Autowired + public Environment env; + + /** + * @param auditHeatStackFailed + * @param auditList + * @return + */ + protected boolean didCreateAuditFail(Optional<AAIObjectAuditList> auditList) { + if (auditList.get().getAuditList() != null && !auditList.get().getAuditList().isEmpty()) { + if (logger.isInfoEnabled()) { + logger.info("Audit Results: {}", auditList.get().toString()); + } + return auditList.get().getAuditList().stream().filter(auditObject -> !auditObject.isDoesObjectExist()) + .findFirst().map(v -> true).orElse(false); + } else { + return false; + } + } + + /** + * @param auditHeatStackFailed + * @param auditList + * @return + */ + protected boolean didDeleteAuditFail(Optional<AAIObjectAuditList> auditList) { + if (auditList.get().getAuditList() != null && !auditList.get().getAuditList().isEmpty()) { + if (logger.isInfoEnabled()) { + logger.info("Audit Results: {}", auditList.get().toString()); + } + return auditList.get().getAuditList().stream().filter(AAIObjectAudit::isDoesObjectExist).findFirst() + .map(v -> true).orElse(false); + } else { + return false; + } + } + + protected String[] getRetrySequence() { + return env.getProperty("mso.workflow.topics.retrySequence", String[].class); + } + + protected void setupMDC(ExternalTask externalTask) { + String msoRequestId = externalTask.getVariable("mso-request-id"); + if (msoRequestId != null && !msoRequestId.isEmpty()) + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, msoRequestId); + } + + protected long calculateRetryDelay(int currentRetries) { + int retrySequence = getRetrySequence().length - currentRetries; + long retryMultiplier = Long.parseLong(env.getProperty("mso.workflow.topics.retryMultiplier", "6000")); + return Integer.parseInt(getRetrySequence()[retrySequence]) * retryMultiplier; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java index 5dfba25141..d46229ae8e 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java @@ -25,7 +25,6 @@ package org.onap.so.adapters.audit; import java.util.HashMap; import java.util.Map; import java.util.Optional; - import org.camunda.bpm.client.task.ExternalTask; import org.camunda.bpm.client.task.ExternalTaskService; import org.onap.logging.ref.slf4j.ONAPLogConstants; @@ -40,54 +39,59 @@ import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component -public class AuditCreateStackService extends AbstractAuditService{ +public class AuditCreateStackService extends AbstractAuditService { + + private static final Logger logger = LoggerFactory.getLogger(AuditCreateStackService.class); + + @Autowired + public HeatStackAudit heatStackAudit; - private static final Logger logger = LoggerFactory.getLogger(AuditCreateStackService.class); - - @Autowired - public HeatStackAudit heatStackAudit; - - @Autowired - public Environment env; + @Autowired + public Environment env; - protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService){ - AuditInventory auditInventory = externalTask.getVariable("auditInventory"); + protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + AuditInventory auditInventory = externalTask.getVariable("auditInventory"); Map<String, Object> variables = new HashMap<>(); - setupMDC(externalTask); - boolean success = false; - try { - logger.info("Executing External Task Audit Inventory, Retry Number: {} \n {}", auditInventory,externalTask.getRetries()); - Optional<AAIObjectAuditList> auditListOpt= heatStackAudit.auditHeatStack(auditInventory.getCloudRegion(), auditInventory.getCloudOwner(), - auditInventory.getTenantId(), auditInventory.getHeatStackName()); - if (auditListOpt.isPresent()) { - GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); - variables.put("auditInventoryResult", objectMapper.getMapper().writeValueAsString(auditListOpt.get())); - success = !didCreateAuditFail(auditListOpt); - } - } catch (Exception e) { - logger.error("Error during audit of stack", e); - } - variables.put("auditIsSuccessful", success); - if (success) { - externalTaskService.complete(externalTask,variables); - logger.debug("The External Task Id: {} Successful", externalTask.getId()); - } else { - if(externalTask.getRetries() == null){ - logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", externalTask.getId(),getRetrySequence().length); - externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, getRetrySequence().length, 10000); - }else if(externalTask.getRetries() != null && - externalTask.getRetries()-1 == 0){ - logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTask.getId()); - externalTaskService.complete(externalTask, variables); - }else{ - logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ", externalTask.getId(),externalTask.getRetries()-1, calculateRetryDelay(externalTask.getRetries())); - externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, externalTask.getRetries()-1, calculateRetryDelay(externalTask.getRetries())); - } - logger.debug("The External Task Id: {} Failed", externalTask.getId()); - } - } + setupMDC(externalTask); + boolean success = false; + try { + logger.info("Executing External Task Audit Inventory, Retry Number: {} \n {}", auditInventory, + externalTask.getRetries()); + Optional<AAIObjectAuditList> auditListOpt = heatStackAudit.auditHeatStack(auditInventory.getCloudRegion(), + auditInventory.getCloudOwner(), auditInventory.getTenantId(), auditInventory.getHeatStackName()); + if (auditListOpt.isPresent()) { + GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); + variables.put("auditInventoryResult", objectMapper.getMapper().writeValueAsString(auditListOpt.get())); + success = !didCreateAuditFail(auditListOpt); + } + } catch (Exception e) { + logger.error("Error during audit of stack", e); + } + variables.put("auditIsSuccessful", success); + if (success) { + externalTaskService.complete(externalTask, variables); + logger.debug("The External Task Id: {} Successful", externalTask.getId()); + } else { + if (externalTask.getRetries() == null) { + logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", + externalTask.getId(), getRetrySequence().length); + externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, + UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, getRetrySequence().length, 10000); + } else if (externalTask.getRetries() != null && externalTask.getRetries() - 1 == 0) { + logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTask.getId()); + externalTaskService.complete(externalTask, variables); + } else { + logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ", + externalTask.getId(), externalTask.getRetries() - 1, + calculateRetryDelay(externalTask.getRetries())); + externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, + UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, externalTask.getRetries() - 1, + calculateRetryDelay(externalTask.getRetries())); + } + logger.debug("The External Task Id: {} Failed", externalTask.getId()); + } + } - } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java index 2c2b2f810d..aca6e9e268 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java @@ -23,7 +23,6 @@ package org.onap.so.adapters.audit; import java.util.HashMap; import java.util.Map; import java.util.Optional; - import org.camunda.bpm.client.task.ExternalTask; import org.camunda.bpm.client.task.ExternalTaskService; import org.onap.logging.ref.slf4j.ONAPLogConstants; @@ -37,51 +36,57 @@ import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component -public class AuditDeleteStackService extends AbstractAuditService{ - - private static final Logger logger = LoggerFactory.getLogger(AuditDeleteStackService.class); - - @Autowired - public HeatStackAudit heatStackAudit; - - @Autowired - public Environment env; +public class AuditDeleteStackService extends AbstractAuditService { + + private static final Logger logger = LoggerFactory.getLogger(AuditDeleteStackService.class); + + @Autowired + public HeatStackAudit heatStackAudit; + + @Autowired + public Environment env; - protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService){ - AuditInventory auditInventory = externalTask.getVariable("auditInventory"); - Map<String, Object> variables = new HashMap<>(); - setupMDC(externalTask); - boolean success = false; - try { - logger.info("Executing External Task Audit Inventory, Retry Number: {} \n {}", auditInventory,externalTask.getRetries()); - Optional<AAIObjectAuditList> auditListOpt=heatStackAudit.auditHeatStack(auditInventory.getCloudRegion(), auditInventory.getCloudOwner(), - auditInventory.getTenantId(), auditInventory.getHeatStackName()); - if (auditListOpt.isPresent()) { - GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); - variables.put("auditInventoryResult", objectMapper.getMapper().writeValueAsString(auditListOpt.get())); - success = didDeleteAuditFail(auditListOpt); - } - } catch (Exception e) { - logger.error("Error during audit of stack", e); - } - variables.put("auditIsSuccessful", success); - if (success) { - externalTaskService.complete(externalTask, variables); - logger.debug("The External Task Id: {} Successful", externalTask.getId()); - } else { - if(externalTask.getRetries() == null){ - logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", externalTask.getId(),getRetrySequence().length); - externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, getRetrySequence().length, 10000); - }else if(externalTask.getRetries() != null && - externalTask.getRetries()-1 == 0){ - logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTask.getId()); - externalTaskService.complete(externalTask); - }else{ - logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ", externalTask.getId(),externalTask.getRetries()-1, calculateRetryDelay(externalTask.getRetries())); - externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, externalTask.getRetries()-1, calculateRetryDelay(externalTask.getRetries())); - } - logger.debug("The External Task Id: {} Failed", externalTask.getId()); - } - } + protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + AuditInventory auditInventory = externalTask.getVariable("auditInventory"); + Map<String, Object> variables = new HashMap<>(); + setupMDC(externalTask); + boolean success = false; + try { + logger.info("Executing External Task Audit Inventory, Retry Number: {} \n {}", auditInventory, + externalTask.getRetries()); + Optional<AAIObjectAuditList> auditListOpt = heatStackAudit.auditHeatStack(auditInventory.getCloudRegion(), + auditInventory.getCloudOwner(), auditInventory.getTenantId(), auditInventory.getHeatStackName()); + if (auditListOpt.isPresent()) { + GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); + variables.put("auditInventoryResult", objectMapper.getMapper().writeValueAsString(auditListOpt.get())); + success = didDeleteAuditFail(auditListOpt); + } + } catch (Exception e) { + logger.error("Error during audit of stack", e); + } + variables.put("auditIsSuccessful", success); + if (success) { + externalTaskService.complete(externalTask, variables); + logger.debug("The External Task Id: {} Successful", externalTask.getId()); + } else { + if (externalTask.getRetries() == null) { + logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", + externalTask.getId(), getRetrySequence().length); + externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, + UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, getRetrySequence().length, 10000); + } else if (externalTask.getRetries() != null && externalTask.getRetries() - 1 == 0) { + logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTask.getId()); + externalTaskService.complete(externalTask); + } else { + logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ", + externalTask.getId(), externalTask.getRetries() - 1, + calculateRetryDelay(externalTask.getRetries())); + externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, + UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, externalTask.getRetries() - 1, + calculateRetryDelay(externalTask.getRetries())); + } + logger.debug("The External Task Id: {} Failed", externalTask.getId()); + } + } -}
\ No newline at end of file +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java index ed29a1c47d..3508810e04 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java @@ -21,9 +21,7 @@ package org.onap.so.adapters.audit; import java.security.GeneralSecurityException; - import javax.annotation.PostConstruct; - import org.camunda.bpm.client.ExternalTaskClient; import org.camunda.bpm.client.backoff.ExponentialBackoffStrategy; import org.camunda.bpm.client.interceptor.ClientRequestInterceptor; @@ -40,49 +38,48 @@ import org.springframework.stereotype.Component; @Profile("!test") public class AuditStackService { - private static final Logger logger = LoggerFactory.getLogger(AuditStackService.class); + private static final Logger logger = LoggerFactory.getLogger(AuditStackService.class); + + @Autowired + public Environment env; + + @Autowired + private AuditCreateStackService auditCreateStack; + + @Autowired + private AuditDeleteStackService auditDeleteStack; - @Autowired - public Environment env; + @PostConstruct + public void auditAddAAIInventory() { + String auth = ""; + try { + auth = CryptoUtils.decrypt(env.getRequiredProperty("mso.auth"), env.getRequiredProperty("mso.msoKey")); + } catch (IllegalStateException | GeneralSecurityException e) { + logger.error("Error Decrypting Password", e); + } + ClientRequestInterceptor interceptor = + new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"), auth); + ExternalTaskClient client = ExternalTaskClient.create() + .baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1).addInterceptor(interceptor) + .asyncResponseTimeout(120000).backoffStrategy(new ExponentialBackoffStrategy(0, 0, 0)).build(); + client.subscribe("InventoryAddAudit").lockDuration(60000).handler(auditCreateStack::executeExternalTask).open(); + } - @Autowired - private AuditCreateStackService auditCreateStack; - - @Autowired - private AuditDeleteStackService auditDeleteStack; + @PostConstruct + public void auditDeleteAAIInventory() { + String auth = ""; + try { + auth = CryptoUtils.decrypt(env.getRequiredProperty("mso.auth"), env.getRequiredProperty("mso.msoKey")); + } catch (IllegalStateException | GeneralSecurityException e) { + logger.error("Error Decrypting Password", e); + } + ClientRequestInterceptor interceptor = + new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"), auth); + ExternalTaskClient client = ExternalTaskClient.create() + .baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1).addInterceptor(interceptor) + .asyncResponseTimeout(120000).backoffStrategy(new ExponentialBackoffStrategy(0, 0, 0)).build(); + client.subscribe("InventoryDeleteAudit").lockDuration(60000).handler(auditDeleteStack::executeExternalTask) + .open(); + } - @PostConstruct - public void auditAddAAIInventory() { - String auth = ""; - try { - auth = CryptoUtils.decrypt(env.getRequiredProperty("mso.auth"), env.getRequiredProperty("mso.msoKey")); - } catch (IllegalStateException | GeneralSecurityException e) { - logger.error("Error Decrypting Password", e); - } - ClientRequestInterceptor interceptor = new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"), - auth); - ExternalTaskClient client = ExternalTaskClient.create() - .baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1).addInterceptor(interceptor) - .asyncResponseTimeout(120000).backoffStrategy(new ExponentialBackoffStrategy(0, 0, 0)).build(); - client.subscribe("InventoryAddAudit").lockDuration(60000) - .handler(auditCreateStack::executeExternalTask).open(); - } - - @PostConstruct - public void auditDeleteAAIInventory() { - String auth = ""; - try { - auth = CryptoUtils.decrypt(env.getRequiredProperty("mso.auth"), env.getRequiredProperty("mso.msoKey")); - } catch (IllegalStateException | GeneralSecurityException e) { - logger.error("Error Decrypting Password", e); - } - ClientRequestInterceptor interceptor = new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"), - auth); - ExternalTaskClient client = ExternalTaskClient.create() - .baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1).addInterceptor(interceptor) - .asyncResponseTimeout(120000).backoffStrategy(new ExponentialBackoffStrategy(0,0,0)).build(); - client.subscribe("InventoryDeleteAudit").lockDuration(60000) - .handler(auditDeleteStack::executeExternalTask).open(); - } - } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java index 519e1c92b1..8559fe5c36 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java @@ -22,7 +22,6 @@ package org.onap.so.adapters.audit; import java.util.Optional; import java.util.Set; - import org.onap.aai.domain.yang.LInterface; import org.onap.aai.domain.yang.Vserver; import org.onap.so.client.aai.AAIObjectType; @@ -33,97 +32,100 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Component; - import com.fasterxml.jackson.core.JsonProcessingException; @Component public class AuditVServer extends AbstractAudit { - private static final Logger logger = LoggerFactory.getLogger(AuditVServer.class); + private static final Logger logger = LoggerFactory.getLogger(AuditVServer.class); + + public Optional<AAIObjectAuditList> auditVservers(Set<Vserver> vServersToAudit, String tenantId, String cloudOwner, + String cloudRegion) { + if (vServersToAudit == null || vServersToAudit.isEmpty()) { + return Optional.empty(); + } + GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); + vServersToAudit.stream().forEach(vserver -> { + try { + logger.debug("Vserver to Audit: {}", objectMapper.getMapper().writeValueAsString(vserver)); + } catch (JsonProcessingException e) { + + } + }); + AAIObjectAuditList auditList = new AAIObjectAuditList(); + vServersToAudit.stream().forEach(vServer -> auditList.getAuditList() + .addAll(doesVServerExistInAAI(vServer, tenantId, cloudOwner, cloudRegion).getAuditList())); + return Optional.of(auditList); + } + + private AAIObjectAuditList doesVServerExistInAAI(Vserver vServer, String tenantId, String cloudOwner, + String cloudRegion) { + AAIObjectAuditList auditList = new AAIObjectAuditList(); + AAIObjectAudit vServerAudit = new AAIObjectAudit(); + AAIResourceUri vserverURI = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, + tenantId, vServer.getVserverId()); + Vserver vServerShallow = new Vserver(); + BeanUtils.copyProperties(vServer, vServerShallow, "LInterfaces"); + boolean vServerExists = getAaiClient().exists(vserverURI); + logger.info("v-server {} exists: {}", vServer.getVserverId(), vServerExists); + vServerAudit.setAaiObject(vServerShallow); + vServerAudit.setDoesObjectExist(vServerExists); + vServerAudit.setResourceURI(vserverURI.build()); + vServerAudit.setAaiObjectType(AAIObjectType.VSERVER.typeName()); + auditList.getAuditList().add(vServerAudit); + if (vServer.getLInterfaces() != null) { + vServer.getLInterfaces().getLInterface().stream().forEach(lInterface -> auditList.getAuditList().addAll( + doesLinterfaceExistinAAI(lInterface, vServer.getVserverId(), tenantId, cloudOwner, cloudRegion) + .getAuditList())); + } + return auditList; + } - public Optional<AAIObjectAuditList> auditVservers(Set<Vserver> vServersToAudit, String tenantId, String cloudOwner, String cloudRegion) { - if (vServersToAudit == null || vServersToAudit.isEmpty()){ - return Optional.empty(); - } - GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); - vServersToAudit.stream().forEach(vserver -> { - try { - logger.debug("Vserver to Audit: {}",objectMapper.getMapper().writeValueAsString(vserver)); - } catch (JsonProcessingException e) { - - } - }); - AAIObjectAuditList auditList = new AAIObjectAuditList(); - vServersToAudit.stream() - .forEach(vServer -> auditList.getAuditList().addAll(doesVServerExistInAAI(vServer, tenantId, cloudOwner, cloudRegion).getAuditList())); - return Optional.of(auditList); - } + private AAIObjectAuditList doesLinterfaceExistinAAI(LInterface lInterface, String vServerId, String tenantId, + String cloudOwner, String cloudRegion) { + AAIObjectAuditList auditList = new AAIObjectAuditList(); + AAIObjectAudit lInterfaceAudit = new AAIObjectAudit(); + AAIResourceUri linterfaceURI = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, cloudOwner, + cloudRegion, tenantId, vServerId, lInterface.getInterfaceName()); + Optional<LInterface> queriedLInterface = getAaiClient().get(LInterface.class, linterfaceURI); + if (queriedLInterface.isPresent()) { + lInterfaceAudit.setDoesObjectExist(true); + lInterface.setInterfaceName(lInterface.getInterfaceName()); + } + LInterface lInterfaceShallow = new LInterface(); + BeanUtils.copyProperties(lInterface, lInterfaceShallow, "LInterfaces"); + lInterfaceAudit.setAaiObject(lInterface); + lInterfaceAudit.setResourceURI(linterfaceURI.build()); + lInterfaceAudit.setAaiObjectType(AAIObjectType.L_INTERFACE.typeName()); + auditList.getAuditList().add(lInterfaceAudit); + logger.info("l-interface id:{} name: {} exists: {} ", lInterface.getInterfaceId(), + lInterface.getInterfaceName(), lInterfaceAudit.isDoesObjectExist()); - private AAIObjectAuditList doesVServerExistInAAI(Vserver vServer, String tenantId, String cloudOwner, String cloudRegion) { - AAIObjectAuditList auditList = new AAIObjectAuditList(); - AAIObjectAudit vServerAudit = new AAIObjectAudit(); - AAIResourceUri vserverURI = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, - tenantId, vServer.getVserverId()); - Vserver vServerShallow = new Vserver(); - BeanUtils.copyProperties(vServer,vServerShallow,"LInterfaces"); - boolean vServerExists = getAaiClient().exists(vserverURI); - logger.info("v-server {} exists: {}", vServer.getVserverId(), vServerExists); - vServerAudit.setAaiObject(vServerShallow); - vServerAudit.setDoesObjectExist(vServerExists); - vServerAudit.setResourceURI(vserverURI.build()); - vServerAudit.setAaiObjectType(AAIObjectType.VSERVER.typeName()); - auditList.getAuditList().add(vServerAudit); - if (vServer.getLInterfaces() != null) { - vServer.getLInterfaces().getLInterface().stream().forEach(lInterface -> auditList.getAuditList().addAll(doesLinterfaceExistinAAI(lInterface, - vServer.getVserverId(), tenantId, cloudOwner, cloudRegion).getAuditList())); - } - return auditList; - } + if (lInterface.getLInterfaces() != null) { + lInterface.getLInterfaces().getLInterface().stream() + .forEach(subInterface -> auditList.getAuditList().add(doesSubInterfaceExistinAAI(subInterface, + lInterface.getInterfaceName(), vServerId, tenantId, cloudOwner, cloudRegion))); + } + logger.debug("l-interface {} does not contain any sub-iterfaces, skipping audit of sub-interfaces", + lInterface.getInterfaceId()); - private AAIObjectAuditList doesLinterfaceExistinAAI(LInterface lInterface, String vServerId, String tenantId, - String cloudOwner, String cloudRegion) { - AAIObjectAuditList auditList = new AAIObjectAuditList(); - AAIObjectAudit lInterfaceAudit = new AAIObjectAudit(); - AAIResourceUri linterfaceURI = AAIUriFactory - .createResourceUri(AAIObjectType.L_INTERFACE, cloudOwner, cloudRegion, tenantId, vServerId, lInterface.getInterfaceName()); - Optional<LInterface> queriedLInterface = getAaiClient().get(LInterface.class, linterfaceURI); - if (queriedLInterface.isPresent()) { - lInterfaceAudit.setDoesObjectExist(true); - lInterface.setInterfaceName(lInterface.getInterfaceName()); - } - LInterface lInterfaceShallow = new LInterface(); - BeanUtils.copyProperties(lInterface,lInterfaceShallow,"LInterfaces"); - lInterfaceAudit.setAaiObject(lInterface); - lInterfaceAudit.setResourceURI(linterfaceURI.build()); - lInterfaceAudit.setAaiObjectType(AAIObjectType.L_INTERFACE.typeName()); - auditList.getAuditList().add(lInterfaceAudit); - logger.info("l-interface id:{} name: {} exists: {} ", lInterface.getInterfaceId(), lInterface.getInterfaceName(), - lInterfaceAudit.isDoesObjectExist()); + return auditList; + } - if (lInterface.getLInterfaces() != null) { - lInterface.getLInterfaces().getLInterface().stream() - .forEach(subInterface -> auditList.getAuditList().add(doesSubInterfaceExistinAAI(subInterface, - lInterface.getInterfaceName(), vServerId, tenantId, cloudOwner, cloudRegion))); - } - logger.debug("l-interface {} does not contain any sub-iterfaces, skipping audit of sub-interfaces", lInterface.getInterfaceId()); + private AAIObjectAudit doesSubInterfaceExistinAAI(LInterface subInterface, String linterfaceName, String vServerId, + String tenantId, String cloudOwner, String cloudRegion) { + logger.info("checking if sub-l-interface {} , linterfaceName: {} vserverId: {} exists", + subInterface.getInterfaceName(), linterfaceName, vServerId); + AAIObjectAudit subInterfaceAudit = new AAIObjectAudit(); - return auditList; - } - private AAIObjectAudit doesSubInterfaceExistinAAI(LInterface subInterface, String linterfaceName, String vServerId, - String tenantId, String cloudOwner, String cloudRegion) { - logger.info("checking if sub-l-interface {} , linterfaceName: {} vserverId: {} exists", - subInterface.getInterfaceName(), linterfaceName, vServerId); - AAIObjectAudit subInterfaceAudit = new AAIObjectAudit(); - - - AAIResourceUri subInterfaceURI = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner, - cloudRegion, tenantId, vServerId, linterfaceName, subInterface.getInterfaceName()); - subInterfaceAudit.setResourceURI(subInterfaceURI.build()); - boolean doesExist = getAaiClient().exists(subInterfaceURI); - logger.info("sub-l-interface-id:{} exists: {}", subInterface.getInterfaceId(), doesExist); - subInterfaceAudit.setAaiObject(subInterface); - subInterfaceAudit.setDoesObjectExist(doesExist); - subInterfaceAudit.setAaiObjectType(AAIObjectType.SUB_L_INTERFACE.typeName()); - return subInterfaceAudit; - } + AAIResourceUri subInterfaceURI = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner, + cloudRegion, tenantId, vServerId, linterfaceName, subInterface.getInterfaceName()); + subInterfaceAudit.setResourceURI(subInterfaceURI.build()); + boolean doesExist = getAaiClient().exists(subInterfaceURI); + logger.info("sub-l-interface-id:{} exists: {}", subInterface.getInterfaceId(), doesExist); + subInterfaceAudit.setAaiObject(subInterface); + subInterfaceAudit.setDoesObjectExist(doesExist); + subInterfaceAudit.setAaiObjectType(AAIObjectType.SUB_L_INTERFACE.typeName()); + return subInterfaceAudit; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java index b522300b6a..5c0d2d3019 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java @@ -30,7 +30,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; - import org.onap.aai.domain.yang.LInterface; import org.onap.aai.domain.yang.LInterfaces; import org.onap.aai.domain.yang.Vlan; @@ -42,7 +41,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; - import com.woorea.openstack.heat.model.Link; import com.woorea.openstack.heat.model.Resource; import com.woorea.openstack.heat.model.Resources; @@ -52,213 +50,222 @@ import com.woorea.openstack.quantum.model.Port; @Component public class HeatStackAudit { - private static final String RESOURCES = "/resources"; + private static final String RESOURCES = "/resources"; + + protected static final Logger logger = LoggerFactory.getLogger(HeatStackAudit.class); + + @Autowired + protected MsoHeatUtils heat; + + @Autowired + protected MsoNeutronUtils neutron; + + @Autowired + protected AuditVServer auditVservers; + + public Optional<AAIObjectAuditList> auditHeatStack(String cloudRegion, String cloudOwner, String tenantId, + String heatStackName) { + try { + logger.debug("Fetching Top Level Stack Information"); + Resources resources = heat.queryStackResources(cloudRegion, tenantId, heatStackName, 3); + List<Resource> novaResources = resources.getList().stream() + .filter(p -> "OS::Nova::Server".equals(p.getType())).collect(Collectors.toList()); + List<Resource> resourceGroups = resources.getList().stream() + .filter(p -> "OS::Heat::ResourceGroup".equals(p.getType()) && p.getName().contains("subinterfaces")) + .collect(Collectors.toList()); + List<Optional<Port>> neutronPortDetails = retrieveNeutronPortDetails(resources, cloudRegion, tenantId); + if (novaResources.isEmpty()) + return Optional.of(new AAIObjectAuditList()); + else { + Set<Vserver> vserversToAudit = createVserverSet(resources, novaResources, neutronPortDetails); + Set<Vserver> vserversWithSubInterfaces = + processSubInterfaces(cloudRegion, tenantId, resourceGroups, vserversToAudit); + return auditVservers.auditVservers(vserversWithSubInterfaces, tenantId, cloudOwner, cloudRegion); + } + } catch (Exception e) { + logger.error("Error during auditing stack resources", e); + return Optional.empty(); + } + } + + protected Set<Vserver> processSubInterfaces(String cloudRegion, String tenantId, List<Resource> resourceGroups, + Set<Vserver> vServersToAudit) throws Exception { + for (Resource resourceGroup : resourceGroups) { + processResourceGroups(cloudRegion, tenantId, vServersToAudit, resourceGroup); + } + return vServersToAudit; + } + + protected void processResourceGroups(String cloudRegion, String tenantId, Set<Vserver> vServersWithLInterface, + Resource resourceGroup) throws Exception { + Optional<Link> stackLink = + resourceGroup.getLinks().stream().filter(link -> "nested".equals(link.getRel())).findAny(); + if (stackLink.isPresent()) { + try { + Optional<String> path = extractResourcePathFromHref(stackLink.get().getHref()); + if (path.isPresent()) { + logger.debug("Fetching nested Resource Stack Information"); + Resources nestedResourceGroupResources = + heat.executeHeatClientRequest(path.get(), cloudRegion, tenantId, Resources.class); + processNestedResourceGroup(cloudRegion, tenantId, vServersWithLInterface, + nestedResourceGroupResources); + } else + throw new Exception("Error finding Path from Self Link"); + } catch (Exception e) { + logger.error("Error Parsing Link to obtain Path", e); + throw new Exception("Error finding Path from Self Link"); + } + } + } + + protected void processNestedResourceGroup(String cloudRegion, String tenantId, Set<Vserver> vServersWithLInterface, + Resources nestedResourceGroupResources) throws Exception { + for (Resource resourceGroupNested : nestedResourceGroupResources) { + Optional<Link> subInterfaceStackLink = + resourceGroupNested.getLinks().stream().filter(link -> "nested".equals(link.getRel())).findAny(); + if (subInterfaceStackLink.isPresent()) { + addSubInterface(cloudRegion, tenantId, vServersWithLInterface, subInterfaceStackLink.get()); + } + } + } + + protected void addSubInterface(String cloudRegion, String tenantId, Set<Vserver> vServersWithLInterface, + Link subInterfaceStackLink) throws Exception { + Optional<String> resourcePath = extractResourcePathFromHref(subInterfaceStackLink.getHref()); + Optional<String> stackPath = extractStackPathFromHref(subInterfaceStackLink.getHref()); + if (resourcePath.isPresent() && stackPath.isPresent()) { + logger.debug("Fetching nested Sub-Interface Stack Information"); + Stack subinterfaceStack = + heat.executeHeatClientRequest(stackPath.get(), cloudRegion, tenantId, Stack.class); + Resources subinterfaceResources = + heat.executeHeatClientRequest(resourcePath.get(), cloudRegion, tenantId, Resources.class); + if (subinterfaceStack != null) { + addSubInterfaceToVserver(vServersWithLInterface, subinterfaceStack, subinterfaceResources); + } + } else + throw new Exception("Error finding Path from Self Link"); - protected static final Logger logger = LoggerFactory.getLogger(HeatStackAudit.class); + } - @Autowired - protected MsoHeatUtils heat; - - @Autowired - protected MsoNeutronUtils neutron; + protected void addSubInterfaceToVserver(Set<Vserver> vServersWithLInterface, Stack subinterfaceStack, + Resources subinterfaceResources) throws Exception { + String parentNeutronPortId = (String) subinterfaceStack.getParameters().get("port_interface"); + logger.debug("Parent neutron Port: {} on SubInterface: {}", parentNeutronPortId, subinterfaceStack.getId()); + for (Vserver auditVserver : vServersWithLInterface) + for (LInterface lInterface : auditVserver.getLInterfaces().getLInterface()) - @Autowired - protected AuditVServer auditVservers; + if (parentNeutronPortId.equals(lInterface.getInterfaceId())) { + logger.debug("Found Parent Port on VServer: {} on Port: {}", auditVserver.getVserverId(), + lInterface.getInterfaceId()); + Resource contrailVm = subinterfaceResources.getList().stream() + .filter(resource -> "OS::ContrailV2::VirtualMachineInterface".equals(resource.getType())) + .findAny().orElse(null); + if (contrailVm == null) { + throw new Exception("Cannnot find Contrail Virtual Machine Interface on Stack: " + + subinterfaceStack.getId()); + } + LInterface subInterface = new LInterface(); + subInterface.setInterfaceId(contrailVm.getPhysicalResourceId()); + subInterface.setIsPortMirrored(false); + subInterface.setInMaint(false); + subInterface.setIsIpUnnumbered(false); + String macAddr = (String) subinterfaceStack.getParameters().get("mac_address"); + subInterface.setMacaddr(macAddr); - public Optional<AAIObjectAuditList> auditHeatStack(String cloudRegion, String cloudOwner, String tenantId, String heatStackName) { - try { - logger.debug("Fetching Top Level Stack Information"); - Resources resources = heat.queryStackResources(cloudRegion, tenantId, heatStackName, 3); - List<Resource> novaResources = resources.getList().stream() - .filter(p -> "OS::Nova::Server".equals(p.getType())).collect(Collectors.toList()); - List<Resource> resourceGroups = resources.getList().stream() - .filter(p -> "OS::Heat::ResourceGroup".equals(p.getType()) && p.getName().contains("subinterfaces")) - .collect(Collectors.toList()); - List<Optional<Port>> neutronPortDetails = retrieveNeutronPortDetails(resources, cloudRegion, tenantId); - if (novaResources.isEmpty()) - return Optional.of(new AAIObjectAuditList()); - else { - Set<Vserver> vserversToAudit = createVserverSet(resources, novaResources, neutronPortDetails); - Set<Vserver> vserversWithSubInterfaces = processSubInterfaces(cloudRegion, tenantId, resourceGroups, - vserversToAudit); - return auditVservers.auditVservers(vserversWithSubInterfaces, - tenantId, cloudOwner, cloudRegion); - } - } catch (Exception e) { - logger.error("Error during auditing stack resources", e); - return Optional.empty(); - } - } + String namePrefix = (String) subinterfaceStack.getParameters().get("subinterface_name_prefix"); + Integer vlanIndex = Integer.parseInt((String) subinterfaceStack.getParameters().get("counter")); + String vlanTagList = (String) subinterfaceStack.getParameters().get("vlan_tag"); + List<String> subInterfaceVlanTagList = Arrays.asList(vlanTagList.split(",")); + subInterface.setInterfaceName(namePrefix + "_" + subInterfaceVlanTagList.get(vlanIndex)); + subInterface.setVlans(new Vlans()); + Vlan vlan = new Vlan(); + vlan.setInMaint(false); + vlan.setIsIpUnnumbered(false); + vlan.setVlanIdInner(Long.parseLong(subInterfaceVlanTagList.get(vlanIndex))); + vlan.setVlanInterface(namePrefix + "_" + subInterfaceVlanTagList.get(vlanIndex)); + subInterface.getVlans().getVlan().add(vlan); + if (lInterface.getLInterfaces() == null) + lInterface.setLInterfaces(new LInterfaces()); - protected Set<Vserver> processSubInterfaces(String cloudRegion, String tenantId, List<Resource> resourceGroups, - Set<Vserver> vServersToAudit) throws Exception { - for (Resource resourceGroup : resourceGroups) { - processResourceGroups(cloudRegion, tenantId, vServersToAudit, resourceGroup); - } - return vServersToAudit; - } + lInterface.getLInterfaces().getLInterface().add(subInterface); + } else + logger.debug("Did Not Find Parent Port on VServer: {} Parent Port: SubInterface: {}", + auditVserver.getVserverId(), lInterface.getInterfaceId(), subinterfaceStack.getId()); + } - protected void processResourceGroups(String cloudRegion, String tenantId, Set<Vserver> vServersWithLInterface, - Resource resourceGroup) throws Exception { - Optional<Link> stackLink = resourceGroup.getLinks().stream().filter(link -> "nested".equals(link.getRel())) - .findAny(); - if (stackLink.isPresent()) { - try { - Optional<String> path = extractResourcePathFromHref(stackLink.get().getHref()); - if (path.isPresent()) { - logger.debug("Fetching nested Resource Stack Information"); - Resources nestedResourceGroupResources = heat.executeHeatClientRequest(path.get(), cloudRegion, - tenantId, Resources.class); - processNestedResourceGroup(cloudRegion, tenantId, vServersWithLInterface, - nestedResourceGroupResources); - } else - throw new Exception("Error finding Path from Self Link"); - } catch (Exception e) { - logger.error("Error Parsing Link to obtain Path", e); - throw new Exception("Error finding Path from Self Link"); - } - } - } + protected Set<Vserver> createVserverSet(Resources resources, List<Resource> novaResources, + List<Optional<Port>> neutronPortDetails) { + Set<Vserver> vserversToAudit = new HashSet<>(); + for (Resource novaResource : novaResources) { + Vserver auditVserver = new Vserver(); + auditVserver.setLInterfaces(new LInterfaces()); + auditVserver.setVserverId(novaResource.getPhysicalResourceId()); + Stream<Port> filteredNeutronPorts = filterNeutronPorts(novaResource, neutronPortDetails); + filteredNeutronPorts.forEach(port -> { + LInterface lInterface = new LInterface(); + lInterface.setInterfaceId(port.getId()); + lInterface.setInterfaceName(port.getName()); + auditVserver.getLInterfaces().getLInterface().add(lInterface); + }); + vserversToAudit.add(auditVserver); + } + return vserversToAudit; + } - protected void processNestedResourceGroup(String cloudRegion, String tenantId, Set<Vserver> vServersWithLInterface, - Resources nestedResourceGroupResources) throws Exception { - for (Resource resourceGroupNested : nestedResourceGroupResources) { - Optional<Link> subInterfaceStackLink = resourceGroupNested.getLinks().stream() - .filter(link -> "nested".equals(link.getRel())).findAny(); - if (subInterfaceStackLink.isPresent()) { - addSubInterface(cloudRegion, tenantId, vServersWithLInterface,subInterfaceStackLink.get()); - } - } - } + /** + * @param novaResource Single openstack resource that is of type Nova + * @param neutronPorts List of Neutron ports created within the stack + * @return Filtered list of neutron ports taht relate to the nova server in openstack + */ + protected Stream<Port> filterNeutronPorts(Resource novaResource, List<Optional<Port>> neutronPorts) { + List<Port> filteredNeutronPorts = + neutronPorts.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList()); + return filteredNeutronPorts.stream() + .filter(port -> port.getDeviceId().equalsIgnoreCase(novaResource.getPhysicalResourceId())); + } - protected void addSubInterface(String cloudRegion, String tenantId, Set<Vserver> vServersWithLInterface, Link subInterfaceStackLink) throws Exception { - Optional<String> resourcePath = extractResourcePathFromHref(subInterfaceStackLink.getHref()); - Optional<String> stackPath = extractStackPathFromHref(subInterfaceStackLink.getHref()); - if (resourcePath.isPresent() && stackPath.isPresent()) { - logger.debug("Fetching nested Sub-Interface Stack Information"); - Stack subinterfaceStack = heat.executeHeatClientRequest(stackPath.get(), cloudRegion, tenantId, Stack.class); - Resources subinterfaceResources = heat.executeHeatClientRequest(resourcePath.get(), cloudRegion, tenantId, Resources.class); - if (subinterfaceStack != null) { - addSubInterfaceToVserver(vServersWithLInterface, subinterfaceStack, subinterfaceResources); - } - } else - throw new Exception("Error finding Path from Self Link"); - - } + /** + * @param resources Resource stream created by the stack in openstack + * @param cloudSiteId Unique site id to identify which openstack we talk to + * @param tenantId The tenant within the cloud we are talking to where resouces exist + * @return List of optional neutron ports found within the cloud site and tenant + */ + protected List<Optional<Port>> retrieveNeutronPortDetails(Resources resources, String cloudSiteId, + String tenantId) { + return resources.getList().parallelStream().filter(resource -> "OS::Neutron::Port".equals(resource.getType())) + .map(resource -> neutron.getNeutronPort(resource.getPhysicalResourceId(), tenantId, cloudSiteId)) + .collect(Collectors.toList()); - protected void addSubInterfaceToVserver(Set<Vserver> vServersWithLInterface, Stack subinterfaceStack, Resources subinterfaceResources) throws Exception { - String parentNeutronPortId = (String) subinterfaceStack.getParameters().get("port_interface"); - logger.debug("Parent neutron Port: {} on SubInterface: {}", parentNeutronPortId, subinterfaceStack.getId()); - for (Vserver auditVserver : vServersWithLInterface) - for (LInterface lInterface : auditVserver.getLInterfaces().getLInterface()) - - if (parentNeutronPortId.equals(lInterface.getInterfaceId())) { - logger.debug("Found Parent Port on VServer: {} on Port: {}", auditVserver.getVserverId(), lInterface.getInterfaceId()); - Resource contrailVm = subinterfaceResources.getList().stream().filter(resource -> "OS::ContrailV2::VirtualMachineInterface".equals(resource.getType())).findAny() - .orElse(null); - if(contrailVm == null){ - throw new Exception("Cannnot find Contrail Virtual Machine Interface on Stack: "+ subinterfaceStack.getId()); - } - LInterface subInterface = new LInterface(); - subInterface.setInterfaceId(contrailVm.getPhysicalResourceId()); - subInterface.setIsPortMirrored(false); - subInterface.setInMaint(false); - subInterface.setIsIpUnnumbered(false); - String macAddr = (String) subinterfaceStack.getParameters().get("mac_address"); - subInterface.setMacaddr(macAddr); - - String namePrefix = (String) subinterfaceStack.getParameters().get("subinterface_name_prefix"); - Integer vlanIndex = Integer.parseInt((String) subinterfaceStack.getParameters().get("counter")); - String vlanTagList = (String) subinterfaceStack.getParameters().get("vlan_tag"); - List<String> subInterfaceVlanTagList = Arrays.asList(vlanTagList.split(",")); - subInterface.setInterfaceName(namePrefix+"_"+subInterfaceVlanTagList.get(vlanIndex)); - subInterface.setVlans(new Vlans()); - Vlan vlan = new Vlan(); - vlan.setInMaint(false); - vlan.setIsIpUnnumbered(false); - vlan.setVlanIdInner(Long.parseLong(subInterfaceVlanTagList.get(vlanIndex))); - vlan.setVlanInterface(namePrefix+"_"+subInterfaceVlanTagList.get(vlanIndex)); - subInterface.getVlans().getVlan().add(vlan); - if(lInterface.getLInterfaces() == null) - lInterface.setLInterfaces(new LInterfaces()); - - lInterface.getLInterfaces().getLInterface().add(subInterface); - }else - logger.debug("Did Not Find Parent Port on VServer: {} Parent Port: SubInterface: {}",auditVserver.getVserverId(), - lInterface.getInterfaceId(),subinterfaceStack.getId()); - } + } - protected Set<Vserver> createVserverSet(Resources resources, List<Resource> novaResources, List<Optional<Port>> neutronPortDetails) { - Set<Vserver> vserversToAudit = new HashSet<>(); - for (Resource novaResource : novaResources) { - Vserver auditVserver = new Vserver(); - auditVserver.setLInterfaces(new LInterfaces()); - auditVserver.setVserverId(novaResource.getPhysicalResourceId()); - Stream<Port> filteredNeutronPorts = filterNeutronPorts(novaResource, neutronPortDetails); - filteredNeutronPorts.forEach(port -> { - LInterface lInterface = new LInterface(); - lInterface.setInterfaceId(port.getId()); - lInterface.setInterfaceName(port.getName()); - auditVserver.getLInterfaces().getLInterface().add(lInterface); - }); - vserversToAudit.add(auditVserver); - } - return vserversToAudit; - } + protected Optional<String> extractResourcePathFromHref(String href) { + try { + Optional<String> stackPath = extractStackPathFromHref(href); + if (stackPath.isPresent()) { + return Optional.of(stackPath.get() + RESOURCES); + } else + return Optional.empty(); + } catch (Exception e) { + logger.error("Error parsing URI", e); + } + return Optional.empty(); + } - /** - * @param novaResource Single openstack resource that is of type Nova - * @param neutronPorts List of Neutron ports created within the stack - * @return Filtered list of neutron ports taht relate to the nova server in openstack - */ - protected Stream<Port> filterNeutronPorts(Resource novaResource, List<Optional<Port>> neutronPorts) { - List<Port> filteredNeutronPorts = neutronPorts.stream().filter(Optional::isPresent).map(Optional::get) - .collect(Collectors.toList()); - return filteredNeutronPorts.stream() - .filter(port -> port.getDeviceId().equalsIgnoreCase(novaResource.getPhysicalResourceId())); - } - - /** - * @param resources Resource stream created by the stack in openstack - * @param cloudSiteId Unique site id to identify which openstack we talk to - * @param tenantId The tenant within the cloud we are talking to where resouces exist - * @return List of optional neutron ports found within the cloud site and tenant - */ - protected List<Optional<Port>> retrieveNeutronPortDetails(Resources resources,String cloudSiteId,String tenantId){ - return resources.getList().parallelStream() - .filter(resource -> "OS::Neutron::Port".equals(resource.getType())) - .map(resource -> neutron.getNeutronPort(resource.getPhysicalResourceId(),tenantId,cloudSiteId)).collect(Collectors.toList()); + protected Optional<String> extractStackPathFromHref(String href) { + try { + URI uri = new URI(href); + Pattern p = Pattern.compile("/stacks.*"); + Matcher m = p.matcher(uri.getPath()); + if (m.find()) { + return Optional.of(m.group()); + } else + return Optional.empty(); + } catch (Exception e) { + logger.error("Error parsing URI", e); + } + return Optional.empty(); + } - } - protected Optional<String> extractResourcePathFromHref(String href) { - try { - Optional<String> stackPath = extractStackPathFromHref(href); - if (stackPath.isPresent()){ - return Optional.of(stackPath.get()+RESOURCES); - }else - return Optional.empty(); - } catch (Exception e) { - logger.error("Error parsing URI", e); - } - return Optional.empty(); - } - - protected Optional<String> extractStackPathFromHref(String href) { - try { - URI uri = new URI(href); - Pattern p = Pattern.compile("/stacks.*"); - Matcher m = p.matcher(uri.getPath()); - if (m.find()){ - return Optional.of(m.group()); - }else - return Optional.empty(); - } catch (Exception e) { - logger.error("Error parsing URI", e); - } - return Optional.empty(); - } - - } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java index efced9d9f9..4453071e06 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java @@ -22,7 +22,6 @@ package org.onap.so.adapters.inventory.create; import java.util.Optional; import java.util.stream.Stream; - import org.onap.aai.domain.yang.LInterface; import org.onap.so.adapters.audit.AAIObjectAudit; import org.onap.so.adapters.audit.AAIObjectAuditList; @@ -32,37 +31,44 @@ import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.springframework.stereotype.Component; @Component -public class CreateAAIInventory{ - - private AAIResourcesClient aaiClient; +public class CreateAAIInventory { + + private AAIResourcesClient aaiClient; + + public void createInventory(AAIObjectAuditList auditList) throws InventoryException { + if (didAuditFailVserverLInterfaces(auditList)) { + throw new InventoryException("Audit failed for VServer or LInterface cannot write Sub-Interfaces"); + } + auditList.getAuditList().parallelStream() + .filter(auditObject -> !auditObject.isDoesObjectExist() + && AAIObjectType.SUB_L_INTERFACE.typeName().equals(auditObject.getAaiObjectType())) + .forEach(auditObject -> getAaiClient().createIfNotExists(AAIUriFactory.createResourceFromExistingURI( + AAIObjectType.fromTypeName(auditObject.getAaiObjectType()), auditObject.getResourceURI()), + Optional.of(auditObject.getAaiObject()))); + } + + + /** + * @param auditHeatStackFailed + * @param auditList + * @return + */ + protected boolean didAuditFailVserverLInterfaces(AAIObjectAuditList auditList) { + Stream<AAIObjectAudit> issue = auditList.getAuditList().stream() + .filter(auditObject -> auditObject.getAaiObjectType().equals(AAIObjectType.VSERVER.typeName()) + || auditObject.getAaiObjectType().equals(AAIObjectType.L_INTERFACE.typeName())); + + return issue.filter(auditObject -> !auditObject.isDoesObjectExist()).findFirst().map(v -> true).orElse(false); + } - public void createInventory(AAIObjectAuditList auditList) throws InventoryException { - if(didAuditFailVserverLInterfaces(auditList)){ - throw new InventoryException("Audit failed for VServer or LInterface cannot write Sub-Interfaces"); - } - auditList.getAuditList().parallelStream().filter(auditObject -> !auditObject.isDoesObjectExist() && AAIObjectType.SUB_L_INTERFACE.typeName().equals(auditObject.getAaiObjectType())). - forEach(auditObject -> getAaiClient().createIfNotExists(AAIUriFactory.createResourceFromExistingURI(AAIObjectType.fromTypeName(auditObject.getAaiObjectType()), auditObject.getResourceURI()), Optional.of(auditObject.getAaiObject()))); - } - - - /** - * @param auditHeatStackFailed - * @param auditList - * @return - */ - protected boolean didAuditFailVserverLInterfaces(AAIObjectAuditList auditList) { - Stream<AAIObjectAudit> issue = auditList.getAuditList().stream().filter(auditObject -> auditObject.getAaiObjectType().equals(AAIObjectType.VSERVER.typeName()) || auditObject.getAaiObjectType().equals(AAIObjectType.L_INTERFACE.typeName())); - - return issue.filter(auditObject -> !auditObject.isDoesObjectExist()).findFirst().map(v -> true).orElse(false); - } + protected AAIResourcesClient getAaiClient() { + if (aaiClient == null) + return new AAIResourcesClient(); + else + return aaiClient; + } - protected AAIResourcesClient getAaiClient(){ - if(aaiClient == null) - return new AAIResourcesClient(); - else - return aaiClient; - } - protected void setAaiClient(AAIResourcesClient aaiResource){ - aaiClient = aaiResource; - } + protected void setAaiClient(AAIResourcesClient aaiResource) { + aaiClient = aaiResource; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java index 58d8a4cd55..8bd813026f 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java @@ -21,9 +21,7 @@ package org.onap.so.adapters.inventory.create; import java.security.GeneralSecurityException; - import javax.annotation.PostConstruct; - import org.camunda.bpm.client.ExternalTaskClient; import org.camunda.bpm.client.backoff.ExponentialBackoffStrategy; import org.camunda.bpm.client.interceptor.ClientRequestInterceptor; @@ -40,29 +38,28 @@ import org.springframework.stereotype.Component; @Profile("!test") public class CreateInventoryService { - private static final Logger logger = LoggerFactory.getLogger(CreateInventoryService.class); + private static final Logger logger = LoggerFactory.getLogger(CreateInventoryService.class); - @Autowired - public Environment env; + @Autowired + public Environment env; - @Autowired - private CreateInventoryTask createInventory; + @Autowired + private CreateInventoryTask createInventory; - @PostConstruct - public void auditAAIInventory() { - String auth = ""; - try { - auth = CryptoUtils.decrypt(env.getRequiredProperty("mso.auth"), env.getRequiredProperty("mso.msoKey")); - } catch (IllegalStateException | GeneralSecurityException e) { - logger.error("Error Decrypting Password", e); - } - ClientRequestInterceptor interceptor = new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"), - auth); - ExternalTaskClient client = ExternalTaskClient.create() - .baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1).addInterceptor(interceptor) - .asyncResponseTimeout(120000).backoffStrategy(new ExponentialBackoffStrategy(0, 0, 0)).build(); - client.subscribe("InventoryCreate").lockDuration(60000) - .handler(createInventory::executeExternalTask).open(); - } + @PostConstruct + public void auditAAIInventory() { + String auth = ""; + try { + auth = CryptoUtils.decrypt(env.getRequiredProperty("mso.auth"), env.getRequiredProperty("mso.msoKey")); + } catch (IllegalStateException | GeneralSecurityException e) { + logger.error("Error Decrypting Password", e); + } + ClientRequestInterceptor interceptor = + new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"), auth); + ExternalTaskClient client = ExternalTaskClient.create() + .baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1).addInterceptor(interceptor) + .asyncResponseTimeout(120000).backoffStrategy(new ExponentialBackoffStrategy(0, 0, 0)).build(); + client.subscribe("InventoryCreate").lockDuration(60000).handler(createInventory::executeExternalTask).open(); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryTask.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryTask.java index 4a14b1460e..add3aac74d 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryTask.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryTask.java @@ -21,7 +21,6 @@ package org.onap.so.adapters.inventory.create; import java.io.IOException; - import org.camunda.bpm.client.task.ExternalTask; import org.camunda.bpm.client.task.ExternalTaskService; import org.onap.logging.ref.slf4j.ONAPLogConstants; @@ -38,77 +37,78 @@ import org.springframework.stereotype.Component; @Component public class CreateInventoryTask { - private static final String UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI = "Unable to write all inventory to A&AI"; + private static final String UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI = "Unable to write all inventory to A&AI"; + + private static final Logger logger = LoggerFactory.getLogger(CreateInventoryTask.class); + + @Autowired + CreateAAIInventory createInventory; + + @Autowired + public Environment env; + + protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + boolean success = true; + String auditInventoryString = externalTask.getVariable("auditInventoryResult"); + GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); + AAIObjectAuditList auditInventory = null; + try { + auditInventory = objectMapper.getMapper().readValue(auditInventoryString, AAIObjectAuditList.class); + } catch (IOException e1) { + success = false; + } + setupMDC(externalTask); + + if (auditInventory != null) { + try { + logger.info("Executing External Task Create Inventory, Retry Number: {} \n {}", auditInventory, + externalTask.getRetries()); + createInventory.createInventory(auditInventory); + } catch (Exception e) { + logger.error("Error during inventory of stack", e); + success = false; + } + if (success) { + externalTaskService.complete(externalTask); + logger.debug("The External Task Id: {} Successful", externalTask.getId()); + } else { + if (externalTask.getRetries() == null) { + logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", + externalTask.getId(), getRetrySequence().length); + externalTaskService.handleFailure(externalTask, UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, + UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, getRetrySequence().length, 10000); + } else if (externalTask.getRetries() != null && externalTask.getRetries() - 1 == 0) { + logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTask.getId()); + externalTaskService.handleBpmnError(externalTask, "AAIInventoryFailure"); + } else { + logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ", + externalTask.getId(), externalTask.getRetries() - 1, + calculateRetryDelay(externalTask.getRetries())); + externalTaskService.handleFailure(externalTask, UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, + UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, externalTask.getRetries() - 1, + calculateRetryDelay(externalTask.getRetries())); + } + logger.debug("The External Task Id: {} Failed", externalTask.getId()); + } + } else { + logger.debug("The External Task Id: {} Failed, No Audit Results Written", externalTask.getId()); + externalTaskService.handleBpmnError(externalTask, "AAIInventoryFailure"); + } + } + + private void setupMDC(ExternalTask externalTask) { + String msoRequestId = (String) externalTask.getVariable("mso-request-id"); + if (msoRequestId != null && !msoRequestId.isEmpty()) + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, msoRequestId); + } - private static final Logger logger = LoggerFactory.getLogger(CreateInventoryTask.class); - - @Autowired - CreateAAIInventory createInventory; - - @Autowired - public Environment env; + protected long calculateRetryDelay(int currentRetries) { + int retrySequence = getRetrySequence().length - currentRetries; + long retryMultiplier = Long.parseLong(env.getProperty("mso.workflow.topics.retryMultiplier", "6000")); + return Integer.parseInt(getRetrySequence()[retrySequence]) * retryMultiplier; + } - protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { - boolean success = true; - String auditInventoryString = externalTask.getVariable("auditInventoryResult"); - GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); - AAIObjectAuditList auditInventory = null; - try { - auditInventory = objectMapper.getMapper().readValue(auditInventoryString, AAIObjectAuditList.class); - } catch (IOException e1) { - success = false; - } - setupMDC(externalTask); - - if (auditInventory != null) { - try { - logger.info("Executing External Task Create Inventory, Retry Number: {} \n {}", auditInventory, - externalTask.getRetries()); - createInventory.createInventory(auditInventory); - } catch (Exception e) { - logger.error("Error during inventory of stack", e); - success = false; - } - if (success) { - externalTaskService.complete(externalTask); - logger.debug("The External Task Id: {} Successful", externalTask.getId()); - } else { - if (externalTask.getRetries() == null) { - logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", - externalTask.getId(), getRetrySequence().length); - externalTaskService.handleFailure(externalTask, UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, - UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, getRetrySequence().length, 10000); - } else if (externalTask.getRetries() != null && externalTask.getRetries() - 1 == 0) { - logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTask.getId()); - externalTaskService.handleBpmnError(externalTask, "AAIInventoryFailure"); - } else { - logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ", - externalTask.getId(), externalTask.getRetries() - 1, - calculateRetryDelay(externalTask.getRetries())); - externalTaskService.handleFailure(externalTask, UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, - UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, externalTask.getRetries() - 1, - calculateRetryDelay(externalTask.getRetries())); - } - logger.debug("The External Task Id: {} Failed", externalTask.getId()); - } - } else { - logger.debug("The External Task Id: {} Failed, No Audit Results Written", externalTask.getId()); - externalTaskService.handleBpmnError(externalTask, "AAIInventoryFailure"); - } - } - - private void setupMDC(ExternalTask externalTask) { - String msoRequestId = (String)externalTask.getVariable("mso-request-id"); - if(msoRequestId != null && !msoRequestId.isEmpty()) - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, msoRequestId); - } - protected long calculateRetryDelay(int currentRetries){ - int retrySequence = getRetrySequence().length - currentRetries; - long retryMultiplier = Long.parseLong(env.getProperty("mso.workflow.topics.retryMultiplier","6000")); - return Integer.parseInt(getRetrySequence()[retrySequence]) * retryMultiplier; - } - - public String[] getRetrySequence() { - return env.getProperty("mso.workflow.topics.retrySequence",String[].class); - } + public String[] getRetrySequence() { + return env.getProperty("mso.workflow.topics.retrySequence", String[].class); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java index 22c6902ed2..24fa9af7f9 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java @@ -2,13 +2,13 @@ package org.onap.so.adapters.inventory.create; public class InventoryException extends Exception { - /** - * - */ - private static final long serialVersionUID = 912652713891488731L; - - public InventoryException(String errorMessage) { - super(errorMessage); - } + /** + * + */ + private static final long serialVersionUID = 912652713891488731L; + + public InventoryException(String errorMessage) { + super(errorMessage); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailPolicyRef.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailPolicyRef.java index 7febf7e9a0..9d7eafbf82 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailPolicyRef.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailPolicyRef.java @@ -34,48 +34,39 @@ import org.slf4j.LoggerFactory; public class ContrailPolicyRef { private static final Logger logger = LoggerFactory.getLogger(ContrailPolicyRef.class); - - @JsonProperty("network_policy_refs_data_sequence") - private ContrailPolicyRefSeq seq; - - public JsonNode toJsonNode() - { - JsonNode node = null; - try - { - ObjectMapper mapper = new ObjectMapper(); - node = mapper.convertValue(this, JsonNode.class); - } - catch (Exception e) - { - logger.error("{} {} Error creating JsonString for Contrail Policy Ref: ", MessageEnum.RA_MARSHING_ERROR, - ErrorCode.SchemaError.getValue(), e); - } - - return node; - } - - public String toJsonString() - { - String jsonString = null; - try - { - ObjectMapper mapper = new ObjectMapper(); - jsonString = mapper.writeValueAsString(this); - } - catch (Exception e) - { - logger.error("{} {} Error creating JsonString for Contrail Policy Ref: ", MessageEnum.RA_MARSHING_ERROR, - ErrorCode.SchemaError.getValue(), e); - } - - return jsonString; - } - - public void populate(String major, String minor) - { - seq = new ContrailPolicyRefSeq(major, minor); - return; - } - + + @JsonProperty("network_policy_refs_data_sequence") + private ContrailPolicyRefSeq seq; + + public JsonNode toJsonNode() { + JsonNode node = null; + try { + ObjectMapper mapper = new ObjectMapper(); + node = mapper.convertValue(this, JsonNode.class); + } catch (Exception e) { + logger.error("{} {} Error creating JsonString for Contrail Policy Ref: ", MessageEnum.RA_MARSHING_ERROR, + ErrorCode.SchemaError.getValue(), e); + } + + return node; + } + + public String toJsonString() { + String jsonString = null; + try { + ObjectMapper mapper = new ObjectMapper(); + jsonString = mapper.writeValueAsString(this); + } catch (Exception e) { + logger.error("{} {} Error creating JsonString for Contrail Policy Ref: ", MessageEnum.RA_MARSHING_ERROR, + ErrorCode.SchemaError.getValue(), e); + } + + return jsonString; + } + + public void populate(String major, String minor) { + seq = new ContrailPolicyRefSeq(major, minor); + return; + } + } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailPolicyRefSeq.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailPolicyRefSeq.java index 17d4a743dc..d5ea301dd3 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailPolicyRefSeq.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailPolicyRefSeq.java @@ -24,43 +24,42 @@ package org.onap.so.adapters.network; import com.fasterxml.jackson.annotation.JsonProperty; public class ContrailPolicyRefSeq { - - @JsonProperty("network_policy_refs_data_sequence_major") - private String major; - - @JsonProperty("network_policy_refs_data_sequence_minor") - private String minor; - public ContrailPolicyRefSeq() { - /* To be done */ - } - - public ContrailPolicyRefSeq(String major, String minor) { - super(); - this.major = major; - this.minor = minor; - } + @JsonProperty("network_policy_refs_data_sequence_major") + private String major; - public String getMajor() { - return major; - } + @JsonProperty("network_policy_refs_data_sequence_minor") + private String minor; - public void setMajor(String major) { - this.major = major; - } + public ContrailPolicyRefSeq() { + /* To be done */ + } - public String getMinor() { - return minor; - } + public ContrailPolicyRefSeq(String major, String minor) { + super(); + this.major = major; + this.minor = minor; + } - public void setMinor(String minor) { - this.minor = minor; - } + public String getMajor() { + return major; + } - @Override - public String toString() { - return "ContrailPolicyRefSeq [major=" + major + ", minor=" + minor - + "]"; - } + public void setMajor(String major) { + this.major = major; + } + + public String getMinor() { + return minor; + } + + public void setMinor(String minor) { + this.minor = minor; + } + + @Override + public String toString() { + return "ContrailPolicyRefSeq [major=" + major + ", minor=" + minor + "]"; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnet.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnet.java index 2662cef16e..0c55bd6945 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnet.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnet.java @@ -27,7 +27,6 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.ArrayList; import java.util.List; - import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.HostRoute; @@ -41,178 +40,161 @@ import org.springframework.beans.factory.annotation.Autowired; public class ContrailSubnet { private static final Logger logger = LoggerFactory.getLogger(ContrailSubnet.class); - @Autowired - private MsoCommonUtils msoCommonUtils; - - @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet") - private ContrailSubnetIp subnet = new ContrailSubnetIp(); - - @JsonProperty("network_ipam_refs_data_ipam_subnets_default_gateway") - private String defaultGateway; - - @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_name") - private String subnetName; - - @JsonProperty("network_ipam_refs_data_ipam_subnets_enable_dhcp") - private Boolean enableDhcp; - - @JsonProperty("network_ipam_refs_data_ipam_subnets_addr_from_start") - private Boolean addrFromStart = true; - /** future - leave this commented - private String subnet_uuid; - private String dns_server_address; - private List<String> dns_nameservers; - private String dhcp_option_list; - **/ - - @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools") - private List<ContrailSubnetPool> allocationPools = new ArrayList <> (); - - @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes") - private final ContrailSubnetHostRoutes host_routes = new ContrailSubnetHostRoutes(); - - public ContrailSubnet() { - super(); - } - - public String getDefaultGateway() { - return defaultGateway; - } - - public void setDefaultGateway(String defaultGateway) { - this.defaultGateway = defaultGateway; - } - - public ContrailSubnetIp getSubnet() { - return subnet; - } - - public void setSubnet(ContrailSubnetIp subnet) { - this.subnet = subnet; - } - - public Boolean isEnableDhcp() { - return enableDhcp; - } - - public void setEnableDhcp(Boolean enableDhcp) { - this.enableDhcp = enableDhcp; - } - - public String getSubnetName() { - return subnetName; - } - - public void setSubnetName(String subnetName) { - this.subnetName = subnetName; - } - - public List<ContrailSubnetPool> getAllocationPools() { - return allocationPools; - } - - public void setPools(List<ContrailSubnetPool> allocationPools) { - this.allocationPools = allocationPools; - } - - public Boolean isAddrFromStart() { - return addrFromStart; - } - - public void setAddrFromStart(Boolean addrFromStart) { - this.addrFromStart = addrFromStart; - } - - public JsonNode toJsonNode() - { - JsonNode node = null; - try - { - ObjectMapper mapper = new ObjectMapper(); - node = mapper.convertValue(this, JsonNode.class); - } - catch (Exception e) - { - logger.error("{} {} Error creating JsonNode for Contrail Subnet: {} ", MessageEnum.RA_MARSHING_ERROR, - ErrorCode.SchemaError.getValue(), subnetName, e); - } - - return node; - } - - public String toJsonString() - { - String jsonString = null; - try - { - ObjectMapper mapper = new ObjectMapper(); - jsonString = mapper.writeValueAsString(this); - } - catch (Exception e) - { - logger.error("{} {} Error creating JsonString for Contrail Subnet: {} ", MessageEnum.RA_MARSHING_ERROR, - ErrorCode.SchemaError.getValue(), subnetName, e); - } - - return jsonString; - } - //poulate contrail subnet with input(from bopel) subnet - public void populateWith(Subnet inputSubnet) - { - if (inputSubnet != null) - { - if (!msoCommonUtils.isNullOrEmpty(inputSubnet.getSubnetName())) - subnetName = inputSubnet.getSubnetName(); - else - subnetName = inputSubnet.getSubnetId(); - enableDhcp = inputSubnet.getEnableDHCP(); - defaultGateway = inputSubnet.getGatewayIp(); - if (!msoCommonUtils.isNullOrEmpty(inputSubnet.getCidr()) ) - { - int idx = inputSubnet.getCidr().indexOf("/"); - if (idx != -1) - { - subnet.setIpPrefix(inputSubnet.getCidr().substring(0, idx)); - subnet.setIpPrefixLen(inputSubnet.getCidr().substring(idx+1)); - } - } - if (inputSubnet.getAllocationPools() != null) - { - for (Pool pool : inputSubnet.getAllocationPools()) - { - if ( !msoCommonUtils.isNullOrEmpty(pool.getStart()) && !msoCommonUtils.isNullOrEmpty(pool.getEnd()) ) - { - ContrailSubnetPool csp = new ContrailSubnetPool(); - csp.populateWith(pool); - allocationPools.add (csp); - } - } - } - if (inputSubnet.getHostRoutes() != null) - { - List<ContrailSubnetHostRoute> hrList = host_routes.getHost_routes(); - for (HostRoute hr : inputSubnet.getHostRoutes()) - { - if ( !msoCommonUtils.isNullOrEmpty(hr.getPrefix()) || !msoCommonUtils.isNullOrEmpty(hr.getNextHop()) ) - { - ContrailSubnetHostRoute cshr = new ContrailSubnetHostRoute(); - cshr.populateWith(hr); - hrList.add (cshr); - } - } - } - } - } - - @Override - public String toString() { - StringBuilder buf = new StringBuilder (); - for (ContrailSubnetPool pool : allocationPools) - { - buf.append(pool.toString()); - } - return "ContrailSubnet [subnet=" + subnet.toString() + " default_gateway=" + defaultGateway - + " enable_dhcp=" + enableDhcp + " addr_from_start=" + addrFromStart + " subnet_name=" + subnetName + " allocation_pools=" + buf + " ]"; - } + @Autowired + private MsoCommonUtils msoCommonUtils; + + @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet") + private ContrailSubnetIp subnet = new ContrailSubnetIp(); + + @JsonProperty("network_ipam_refs_data_ipam_subnets_default_gateway") + private String defaultGateway; + + @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_name") + private String subnetName; + + @JsonProperty("network_ipam_refs_data_ipam_subnets_enable_dhcp") + private Boolean enableDhcp; + + @JsonProperty("network_ipam_refs_data_ipam_subnets_addr_from_start") + private Boolean addrFromStart = true; + /** + * future - leave this commented private String subnet_uuid; private String dns_server_address; private List<String> + * dns_nameservers; private String dhcp_option_list; + **/ + + @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools") + private List<ContrailSubnetPool> allocationPools = new ArrayList<>(); + + @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes") + private final ContrailSubnetHostRoutes host_routes = new ContrailSubnetHostRoutes(); + + public ContrailSubnet() { + super(); + } + + public String getDefaultGateway() { + return defaultGateway; + } + + public void setDefaultGateway(String defaultGateway) { + this.defaultGateway = defaultGateway; + } + + public ContrailSubnetIp getSubnet() { + return subnet; + } + + public void setSubnet(ContrailSubnetIp subnet) { + this.subnet = subnet; + } + + public Boolean isEnableDhcp() { + return enableDhcp; + } + + public void setEnableDhcp(Boolean enableDhcp) { + this.enableDhcp = enableDhcp; + } + + public String getSubnetName() { + return subnetName; + } + + public void setSubnetName(String subnetName) { + this.subnetName = subnetName; + } + + public List<ContrailSubnetPool> getAllocationPools() { + return allocationPools; + } + + public void setPools(List<ContrailSubnetPool> allocationPools) { + this.allocationPools = allocationPools; + } + + public Boolean isAddrFromStart() { + return addrFromStart; + } + + public void setAddrFromStart(Boolean addrFromStart) { + this.addrFromStart = addrFromStart; + } + + public JsonNode toJsonNode() { + JsonNode node = null; + try { + ObjectMapper mapper = new ObjectMapper(); + node = mapper.convertValue(this, JsonNode.class); + } catch (Exception e) { + logger.error("{} {} Error creating JsonNode for Contrail Subnet: {} ", MessageEnum.RA_MARSHING_ERROR, + ErrorCode.SchemaError.getValue(), subnetName, e); + } + + return node; + } + + public String toJsonString() { + String jsonString = null; + try { + ObjectMapper mapper = new ObjectMapper(); + jsonString = mapper.writeValueAsString(this); + } catch (Exception e) { + logger.error("{} {} Error creating JsonString for Contrail Subnet: {} ", MessageEnum.RA_MARSHING_ERROR, + ErrorCode.SchemaError.getValue(), subnetName, e); + } + + return jsonString; + } + + // poulate contrail subnet with input(from bopel) subnet + public void populateWith(Subnet inputSubnet) { + if (inputSubnet != null) { + if (!msoCommonUtils.isNullOrEmpty(inputSubnet.getSubnetName())) + subnetName = inputSubnet.getSubnetName(); + else + subnetName = inputSubnet.getSubnetId(); + enableDhcp = inputSubnet.getEnableDHCP(); + defaultGateway = inputSubnet.getGatewayIp(); + if (!msoCommonUtils.isNullOrEmpty(inputSubnet.getCidr())) { + int idx = inputSubnet.getCidr().indexOf("/"); + if (idx != -1) { + subnet.setIpPrefix(inputSubnet.getCidr().substring(0, idx)); + subnet.setIpPrefixLen(inputSubnet.getCidr().substring(idx + 1)); + } + } + if (inputSubnet.getAllocationPools() != null) { + for (Pool pool : inputSubnet.getAllocationPools()) { + if (!msoCommonUtils.isNullOrEmpty(pool.getStart()) + && !msoCommonUtils.isNullOrEmpty(pool.getEnd())) { + ContrailSubnetPool csp = new ContrailSubnetPool(); + csp.populateWith(pool); + allocationPools.add(csp); + } + } + } + if (inputSubnet.getHostRoutes() != null) { + List<ContrailSubnetHostRoute> hrList = host_routes.getHost_routes(); + for (HostRoute hr : inputSubnet.getHostRoutes()) { + if (!msoCommonUtils.isNullOrEmpty(hr.getPrefix()) + || !msoCommonUtils.isNullOrEmpty(hr.getNextHop())) { + ContrailSubnetHostRoute cshr = new ContrailSubnetHostRoute(); + cshr.populateWith(hr); + hrList.add(cshr); + } + } + } + } + } + + @Override + public String toString() { + StringBuilder buf = new StringBuilder(); + for (ContrailSubnetPool pool : allocationPools) { + buf.append(pool.toString()); + } + return "ContrailSubnet [subnet=" + subnet.toString() + " default_gateway=" + defaultGateway + " enable_dhcp=" + + enableDhcp + " addr_from_start=" + addrFromStart + " subnet_name=" + subnetName + " allocation_pools=" + + buf + " ]"; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetHostRoute.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetHostRoute.java index d938306c48..32f85ddf60 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetHostRoute.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetHostRoute.java @@ -23,45 +23,43 @@ package org.onap.so.adapters.network; import org.onap.so.openstack.beans.HostRoute; import com.fasterxml.jackson.annotation.JsonProperty; + public class ContrailSubnetHostRoute { - - @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes_route_prefix") - private String prefix; - - @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes_route_next_hop") - private String nextHop; - public ContrailSubnetHostRoute() { - } + @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes_route_prefix") + private String prefix; + + @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes_route_next_hop") + private String nextHop; + + public ContrailSubnetHostRoute() {} + + public String getPrefix() { + return prefix; + } + + public void setPrefix(String prefix) { + this.prefix = prefix; + } - public String getPrefix() { - return prefix; - } + public String getNextHop() { + return nextHop; + } - public void setPrefix(String prefix) { - this.prefix = prefix; - } + public void setNextHop(String nextHop) { + this.nextHop = nextHop; + } - public String getNextHop() { - return nextHop; - } + public void populateWith(HostRoute hostRoute) { + if (hostRoute != null) { + prefix = hostRoute.getPrefix(); + nextHop = hostRoute.getNextHop(); + } + } - public void setNextHop(String nextHop) { - this.nextHop = nextHop; - } - - public void populateWith(HostRoute hostRoute) - { - if (hostRoute != null) - { - prefix = hostRoute.getPrefix(); - nextHop = hostRoute.getNextHop(); - } - } + @Override + public String toString() { + return "ContrailSubnetHostRoute [prefix=" + prefix + ", nextHop=" + nextHop + "]"; + } - @Override - public String toString() { - return "ContrailSubnetHostRoute [prefix=" + prefix + ", nextHop=" + nextHop + "]"; - } - } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetHostRoutes.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetHostRoutes.java index 12744a4273..76881bd58b 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetHostRoutes.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetHostRoutes.java @@ -24,34 +24,31 @@ package org.onap.so.adapters.network; import java.util.ArrayList; import java.util.List; - import com.fasterxml.jackson.annotation.JsonProperty; + public class ContrailSubnetHostRoutes { - - @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes_route") - private List<ContrailSubnetHostRoute> host_routes = new ArrayList <ContrailSubnetHostRoute> (); - - public ContrailSubnetHostRoutes() { - } - - public List<ContrailSubnetHostRoute> getHost_routes() { - return host_routes; - } - - public void setHost_routes(List<ContrailSubnetHostRoute> host_routes) { - this.host_routes = host_routes; - } - - @Override - public String toString() { - StringBuilder buf = new StringBuilder (); - if (host_routes != null) - { - for (ContrailSubnetHostRoute hr : host_routes) - { - buf.append(hr.toString()); - } - } - return "ContrailSubnetHostRoutes [" + buf.toString() + "]"; - } + + @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes_route") + private List<ContrailSubnetHostRoute> host_routes = new ArrayList<ContrailSubnetHostRoute>(); + + public ContrailSubnetHostRoutes() {} + + public List<ContrailSubnetHostRoute> getHost_routes() { + return host_routes; + } + + public void setHost_routes(List<ContrailSubnetHostRoute> host_routes) { + this.host_routes = host_routes; + } + + @Override + public String toString() { + StringBuilder buf = new StringBuilder(); + if (host_routes != null) { + for (ContrailSubnetHostRoute hr : host_routes) { + buf.append(hr.toString()); + } + } + return "ContrailSubnetHostRoutes [" + buf.toString() + "]"; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetIp.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetIp.java index 91d089eb33..a00a1eb5ea 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetIp.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetIp.java @@ -24,36 +24,36 @@ package org.onap.so.adapters.network; import com.fasterxml.jackson.annotation.JsonProperty; public class ContrailSubnetIp { - - @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_ip_prefix") - private String ipPrefix; - - @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_ip_prefix_len") - private String ipPrefixLen; - - public ContrailSubnetIp() { - /* Empty constructor */ - } - - public String getIpPrefix() { - return ipPrefix; - } - - public void setIpPrefix(String ipPrefix) { - this.ipPrefix = ipPrefix; - } - - public String getIpPrefixLen() { - return ipPrefixLen; - } - - public void setIpPrefixLen(String ipPrefixLen) { - this.ipPrefixLen = ipPrefixLen; - } - - @Override - public String toString() { - return "ContrailSubnetIp [ip_prefix=" + ipPrefix + ", ip_prefix_len=" + ipPrefixLen + "]"; - } + + @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_ip_prefix") + private String ipPrefix; + + @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_ip_prefix_len") + private String ipPrefixLen; + + public ContrailSubnetIp() { + /* Empty constructor */ + } + + public String getIpPrefix() { + return ipPrefix; + } + + public void setIpPrefix(String ipPrefix) { + this.ipPrefix = ipPrefix; + } + + public String getIpPrefixLen() { + return ipPrefixLen; + } + + public void setIpPrefixLen(String ipPrefixLen) { + this.ipPrefixLen = ipPrefixLen; + } + + @Override + public String toString() { + return "ContrailSubnetIp [ip_prefix=" + ipPrefix + ", ip_prefix_len=" + ipPrefixLen + "]"; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetPool.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetPool.java index 710d0cc8fd..edba780318 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetPool.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/ContrailSubnetPool.java @@ -23,46 +23,45 @@ package org.onap.so.adapters.network; import org.onap.so.openstack.beans.Pool; import com.fasterxml.jackson.annotation.JsonProperty; + public class ContrailSubnetPool { - - @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools_start") - private String start; - - @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools_end") - private String end; - public ContrailSubnetPool() { - /* Empty constructor */ - } + @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools_start") + private String start; + + @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools_end") + private String end; + + public ContrailSubnetPool() { + /* Empty constructor */ + } + + public String getStart() { + return start; + } + + public void setStart(String start) { + this.start = start; + } - public String getStart() { - return start; - } + public String getEnd() { + return end; + } - public void setStart(String start) { - this.start = start; - } + public void setEnd(String end) { + this.end = end; + } - public String getEnd() { - return end; - } + public void populateWith(Pool pool) { + if (pool != null) { + start = pool.getStart(); + end = pool.getEnd(); + } + } - public void setEnd(String end) { - this.end = end; - } - - public void populateWith(Pool pool) - { - if (pool != null) - { - start = pool.getStart(); - end = pool.getEnd(); - } - } + @Override + public String toString() { + return "ContrailSubnetPool [start=" + start + ", end=" + end + "]"; + } - @Override - public String toString() { - return "ContrailSubnetPool [start=" + start + ", end=" + end + "]"; - } - } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapter.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapter.java index 6e2fcb02c9..302a6d302b 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapter.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapter.java @@ -23,14 +23,12 @@ package org.onap.so.adapters.network; import java.util.List; import java.util.Map; - import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebParam.Mode; import javax.jws.WebService; import javax.xml.bind.annotation.XmlElement; import javax.xml.ws.Holder; - import org.onap.so.adapters.network.exceptions.NetworkException; import org.onap.so.entity.MsoRequest; import org.onap.so.openstack.beans.NetworkRollback; @@ -38,193 +36,170 @@ import org.onap.so.openstack.beans.NetworkStatus; import org.onap.so.openstack.beans.RouteTarget; import org.onap.so.openstack.beans.Subnet; -@WebService (name="NetworkAdapter", targetNamespace="http://org.onap.so/network") -public interface MsoNetworkAdapter -{ - // TODO: Rename all of these to include Vlan in the service name? At least for the - // create and update calls, since they are specific to VLAN-based provider networks. - - /** - * This is the "Create Network" Web Service Endpoint definition. - */ - @WebMethod - public void createNetwork (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="networkType") @XmlElement(required=true) String networkType, - @WebParam(name="modelCustomizationUuid") String modelCustomizationUuid, - @WebParam(name="networkName") @XmlElement(required=true) String networkName, - @WebParam(name="physicalNetworkName") String physicalNetworkName, - @WebParam(name="vlans") List<Integer> vlans, - @WebParam(name="shared") String shared, - @WebParam(name="external") String external, - @WebParam(name="failIfExists") Boolean failIfExists, - @WebParam(name="backout") Boolean backout, - @WebParam(name="subnets") List<Subnet> subnets, - @WebParam(name="networkParams") Map<String, String> networkParams, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="networkId", mode=Mode.OUT) Holder<String> networkId, - @WebParam(name="neutronNetworkId", mode=Mode.OUT) Holder<String> neutronNetworkId, - @WebParam(name="subnetIdMap", mode=Mode.OUT) Holder<Map<String, String>> subnetIdMap, - @WebParam(name="rollback", mode=Mode.OUT) Holder<NetworkRollback> rollback ) - throws NetworkException; - - @WebMethod - public void createNetworkContrail (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="networkType") @XmlElement(required=true) String networkType, - @WebParam(name="modelCustomizationUuid") String modelCustomizationUuid, - @WebParam(name="networkName") @XmlElement(required=true) String networkName, - @WebParam(name="routeTargets") List<RouteTarget> routeTargets, - @WebParam(name="shared") String shared, - @WebParam(name="external") String external, - @WebParam(name="failIfExists") Boolean failIfExists, - @WebParam(name="backout") Boolean backout, - @WebParam(name="subnets") List<Subnet> subnets, - @WebParam(name="networkParams") Map<String, String> networkParams, - @WebParam(name="policyFqdns") List<String> policyFqdns, - @WebParam(name="routeTableFqdns") List<String> routeTableFqdns, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="networkId", mode=Mode.OUT) Holder<String> networkId, - @WebParam(name="neutronNetworkId", mode=Mode.OUT) Holder<String> neutronNetworkId, - @WebParam(name="networkFqdn", mode=Mode.OUT) Holder<String> networkFqdn, - @WebParam(name="subnetIdMap", mode=Mode.OUT) Holder<Map<String, String>> subnetIdMap, - @WebParam(name="rollback", mode=Mode.OUT) Holder<NetworkRollback> rollback ) - throws NetworkException; - - /** - * This is the "Update VLANs" Web Service Endpoint definition. - * This webservice replaces the set of VLANs on a network. - */ - @WebMethod - public void updateNetwork (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="networkType") @XmlElement(required=true) String networkType, - @WebParam(name="modelCustomizationUuid") String modelCustomizationUuid, - @WebParam(name="networkId") @XmlElement(required=true) String networkId, - @WebParam(name="networkName") @XmlElement(required=true) String networkName, - @WebParam(name="physicalNetworkName") @XmlElement(required=true) String physicalNetworkName, - @WebParam(name="vlans") @XmlElement(required=true) List<Integer> vlans, - @WebParam(name="shared") String shared, - @WebParam(name="external") String external, - @WebParam(name="subnets") List<Subnet> subnets, - @WebParam(name="networkParams") Map<String,String> networkParams, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="subnetIdMap", mode=Mode.OUT) Holder<Map<String, String>> subnetIdMap, - @WebParam(name="rollback", mode=Mode.OUT) Holder<NetworkRollback> rollback ) - throws NetworkException; - - @WebMethod - public void updateNetworkContrail (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="networkType") @XmlElement(required=true) String networkType, - @WebParam(name="modelCustomizationUuid") String modelCustomizationUuid, - @WebParam(name="networkId") @XmlElement(required=true) String networkId, - @WebParam(name="networkName") @XmlElement(required=true) String networkName, - @WebParam(name="routeTargets") List<RouteTarget> routeTargets, - @WebParam(name="shared") String shared, - @WebParam(name="external") String external, - @WebParam(name="subnets") List<Subnet> subnets, - @WebParam(name="networkParams") Map<String,String> networkParams, - @WebParam(name="policyFqdns") List<String> policyFqdns, - @WebParam(name="routeTableFqdns") List<String> routeTableFqdns, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="subnetIdMap", mode=Mode.OUT) Holder<Map<String, String>> subnetIdMap, - @WebParam(name="rollback", mode=Mode.OUT) Holder<NetworkRollback> rollback ) - throws NetworkException; - - /** - * TODO: - * This is the "Add VLAN" Web Service Endpoint definition. - * This webservice adds a VLAN to a network. - * This service assumes that PO supports querying the current vlans in real time. - * Otherwise, the caller must have the complete list and should use updateVlans instead. - @WebMethod - public void addVlan (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="networkType") @XmlElement(required=true) String networkType, - @WebParam(name="networkId") @XmlElement(required=true) String networkId, - @WebParam(name="physicalNetworkName") @XmlElement(required=true) String physicalNetworkName, - @WebParam(name="vlan") @XmlElement(required=true) Integer vlan, - @WebParam(name="rollback", mode=Mode.OUT) Holder<NetworkRollback> rollback ) - throws NetworkException; - */ - - /** - * TODO: - * This is the "Remove VLAN" Web Service Endpoint definition. - * This webservice removes a VLAN from a network. - * This service assumes that PO supports querying the current vlans in real time. - * Otherwise, the caller must have the complete list and should use updateVlans instead. - * - * This service returns an indicator (noMoreVLans) if the VLAN that was removed was - * the last one on the network. - * - * It is not clear that Rollback will work for delete. The network can be - * recreated from the NetworkRollback object, but the network ID (and stack ID - * for Heat-based orchestration) will be different. The caller will need to know - * to update these identifiers in the inventory DB (A&AI). - @WebMethod - public void removeVlan (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="networkType") @XmlElement(required=true) String networkType, - @WebParam(name="networkId") @XmlElement(required=true) String networkId, - @WebParam(name="physicalNetworkName") @XmlElement(required=true) String physicalNetworkName, - @WebParam(name="vlan") @XmlElement(required=true) Integer vlan, - @WebParam(name="noMoreVlans", mode=Mode.OUT) Holder<Boolean> noMoreVlans, - @WebParam(name="rollback", mode=Mode.OUT) Holder<NetworkRollback> rollback ) - throws NetworkException; - */ - - /** - * This is the "Query Network" Web Service Endpoint definition. - * TODO: Should this just return the NetworkInfo complete structure? - */ - @WebMethod - public void queryNetwork (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="networkNameOrId") @XmlElement(required=true) String networkNameOrId, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="networkExists", mode=Mode.OUT) Holder<Boolean> networkExists, - @WebParam(name="networkId", mode=Mode.OUT) Holder<String> networkId, - @WebParam(name="neutronNetworkId", mode=Mode.OUT) Holder<String> neutronNetworkId, - @WebParam(name="status", mode=Mode.OUT) Holder<NetworkStatus> status, - @WebParam(name="vlans", mode=Mode.OUT) Holder<List<Integer>> vlans, - @WebParam(name="subnetIdMap", mode=Mode.OUT) Holder<Map<String, String>> subnetIdMap) - throws NetworkException; - - @WebMethod - public void queryNetworkContrail (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="networkNameOrId") @XmlElement(required=true) String networkNameOrId, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="networkExists", mode=Mode.OUT) Holder<Boolean> networkExists, - @WebParam(name="networkId", mode=Mode.OUT) Holder<String> networkId, - @WebParam(name="neutronNetworkId", mode=Mode.OUT) Holder<String> neutronNetworkId, - @WebParam(name="status", mode=Mode.OUT) Holder<NetworkStatus> status, - @WebParam(name="routeTargets", mode=Mode.OUT) Holder<List<RouteTarget>> routeTargets, - @WebParam(name="subnetIdMap", mode=Mode.OUT) Holder<Map<String, String>> subnetIdMap) - throws NetworkException; - - /** - * This is the "Delete Network" Web Service endpoint definition. - */ - @WebMethod - public void deleteNetwork (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="networkType") @XmlElement(required=true) String networkType, - @WebParam(name="modelCustomizationUuid") String modelCustomizationUuid, - @WebParam(name="networkId") @XmlElement(required=true) String networkId, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="networkDeleted", mode=Mode.OUT) Holder<Boolean> networkDeleted) - throws NetworkException; - - /** - * This is the "Rollback Network" Web Service endpoint definition. - */ - @WebMethod - public void rollbackNetwork (@WebParam(name="rollback") @XmlElement(required=true) NetworkRollback rollback) - throws NetworkException; - - @WebMethod - public void healthCheck (); +@WebService(name = "NetworkAdapter", targetNamespace = "http://org.onap.so/network") +public interface MsoNetworkAdapter { + // TODO: Rename all of these to include Vlan in the service name? At least for the + // create and update calls, since they are specific to VLAN-based provider networks. + + /** + * This is the "Create Network" Web Service Endpoint definition. + */ + @WebMethod + public void createNetwork(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "networkType") @XmlElement(required = true) String networkType, + @WebParam(name = "modelCustomizationUuid") String modelCustomizationUuid, + @WebParam(name = "networkName") @XmlElement(required = true) String networkName, + @WebParam(name = "physicalNetworkName") String physicalNetworkName, + @WebParam(name = "vlans") List<Integer> vlans, @WebParam(name = "shared") String shared, + @WebParam(name = "external") String external, @WebParam(name = "failIfExists") Boolean failIfExists, + @WebParam(name = "backout") Boolean backout, @WebParam(name = "subnets") List<Subnet> subnets, + @WebParam(name = "networkParams") Map<String, String> networkParams, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "networkId", mode = Mode.OUT) Holder<String> networkId, + @WebParam(name = "neutronNetworkId", mode = Mode.OUT) Holder<String> neutronNetworkId, + @WebParam(name = "subnetIdMap", mode = Mode.OUT) Holder<Map<String, String>> subnetIdMap, + @WebParam(name = "rollback", mode = Mode.OUT) Holder<NetworkRollback> rollback) throws NetworkException; + + @WebMethod + public void createNetworkContrail(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "networkType") @XmlElement(required = true) String networkType, + @WebParam(name = "modelCustomizationUuid") String modelCustomizationUuid, + @WebParam(name = "networkName") @XmlElement(required = true) String networkName, + @WebParam(name = "routeTargets") List<RouteTarget> routeTargets, @WebParam(name = "shared") String shared, + @WebParam(name = "external") String external, @WebParam(name = "failIfExists") Boolean failIfExists, + @WebParam(name = "backout") Boolean backout, @WebParam(name = "subnets") List<Subnet> subnets, + @WebParam(name = "networkParams") Map<String, String> networkParams, + @WebParam(name = "policyFqdns") List<String> policyFqdns, + @WebParam(name = "routeTableFqdns") List<String> routeTableFqdns, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "networkId", mode = Mode.OUT) Holder<String> networkId, + @WebParam(name = "neutronNetworkId", mode = Mode.OUT) Holder<String> neutronNetworkId, + @WebParam(name = "networkFqdn", mode = Mode.OUT) Holder<String> networkFqdn, + @WebParam(name = "subnetIdMap", mode = Mode.OUT) Holder<Map<String, String>> subnetIdMap, + @WebParam(name = "rollback", mode = Mode.OUT) Holder<NetworkRollback> rollback) throws NetworkException; + + /** + * This is the "Update VLANs" Web Service Endpoint definition. This webservice replaces the set of VLANs on a + * network. + */ + @WebMethod + public void updateNetwork(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "networkType") @XmlElement(required = true) String networkType, + @WebParam(name = "modelCustomizationUuid") String modelCustomizationUuid, + @WebParam(name = "networkId") @XmlElement(required = true) String networkId, + @WebParam(name = "networkName") @XmlElement(required = true) String networkName, + @WebParam(name = "physicalNetworkName") @XmlElement(required = true) String physicalNetworkName, + @WebParam(name = "vlans") @XmlElement(required = true) List<Integer> vlans, + @WebParam(name = "shared") String shared, @WebParam(name = "external") String external, + @WebParam(name = "subnets") List<Subnet> subnets, + @WebParam(name = "networkParams") Map<String, String> networkParams, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "subnetIdMap", mode = Mode.OUT) Holder<Map<String, String>> subnetIdMap, + @WebParam(name = "rollback", mode = Mode.OUT) Holder<NetworkRollback> rollback) throws NetworkException; + + @WebMethod + public void updateNetworkContrail(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "networkType") @XmlElement(required = true) String networkType, + @WebParam(name = "modelCustomizationUuid") String modelCustomizationUuid, + @WebParam(name = "networkId") @XmlElement(required = true) String networkId, + @WebParam(name = "networkName") @XmlElement(required = true) String networkName, + @WebParam(name = "routeTargets") List<RouteTarget> routeTargets, @WebParam(name = "shared") String shared, + @WebParam(name = "external") String external, @WebParam(name = "subnets") List<Subnet> subnets, + @WebParam(name = "networkParams") Map<String, String> networkParams, + @WebParam(name = "policyFqdns") List<String> policyFqdns, + @WebParam(name = "routeTableFqdns") List<String> routeTableFqdns, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "subnetIdMap", mode = Mode.OUT) Holder<Map<String, String>> subnetIdMap, + @WebParam(name = "rollback", mode = Mode.OUT) Holder<NetworkRollback> rollback) throws NetworkException; + + /** + * TODO: This is the "Add VLAN" Web Service Endpoint definition. This webservice adds a VLAN to a network. This + * service assumes that PO supports querying the current vlans in real time. Otherwise, the caller must have the + * complete list and should use updateVlans instead. + * + * @WebMethod public void addVlan (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, + * @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, + * @WebParam(name="networkType") @XmlElement(required=true) String networkType, + * @WebParam(name="networkId") @XmlElement(required=true) String networkId, + * @WebParam(name="physicalNetworkName") @XmlElement(required=true) String physicalNetworkName, + * @WebParam(name="vlan") @XmlElement(required=true) Integer vlan, + * @WebParam(name="rollback", mode=Mode.OUT) Holder<NetworkRollback> rollback ) throws NetworkException; + */ + + /** + * TODO: This is the "Remove VLAN" Web Service Endpoint definition. This webservice removes a VLAN from a network. + * This service assumes that PO supports querying the current vlans in real time. Otherwise, the caller must have + * the complete list and should use updateVlans instead. + * + * This service returns an indicator (noMoreVLans) if the VLAN that was removed was the last one on the network. + * + * It is not clear that Rollback will work for delete. The network can be recreated from the NetworkRollback object, + * but the network ID (and stack ID for Heat-based orchestration) will be different. The caller will need to know to + * update these identifiers in the inventory DB (A&AI). + * + * @WebMethod public void removeVlan (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, + * @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, + * @WebParam(name="networkType") @XmlElement(required=true) String networkType, + * @WebParam(name="networkId") @XmlElement(required=true) String networkId, + * @WebParam(name="physicalNetworkName") @XmlElement(required=true) String physicalNetworkName, + * @WebParam(name="vlan") @XmlElement(required=true) Integer vlan, + * @WebParam(name="noMoreVlans", mode=Mode.OUT) Holder<Boolean> noMoreVlans, + * @WebParam(name="rollback", mode=Mode.OUT) Holder<NetworkRollback> rollback ) throws NetworkException; + */ + + /** + * This is the "Query Network" Web Service Endpoint definition. TODO: Should this just return the NetworkInfo + * complete structure? + */ + @WebMethod + public void queryNetwork(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "networkNameOrId") @XmlElement(required = true) String networkNameOrId, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "networkExists", mode = Mode.OUT) Holder<Boolean> networkExists, + @WebParam(name = "networkId", mode = Mode.OUT) Holder<String> networkId, + @WebParam(name = "neutronNetworkId", mode = Mode.OUT) Holder<String> neutronNetworkId, + @WebParam(name = "status", mode = Mode.OUT) Holder<NetworkStatus> status, + @WebParam(name = "vlans", mode = Mode.OUT) Holder<List<Integer>> vlans, + @WebParam(name = "subnetIdMap", mode = Mode.OUT) Holder<Map<String, String>> subnetIdMap) + throws NetworkException; + + @WebMethod + public void queryNetworkContrail(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "networkNameOrId") @XmlElement(required = true) String networkNameOrId, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "networkExists", mode = Mode.OUT) Holder<Boolean> networkExists, + @WebParam(name = "networkId", mode = Mode.OUT) Holder<String> networkId, + @WebParam(name = "neutronNetworkId", mode = Mode.OUT) Holder<String> neutronNetworkId, + @WebParam(name = "status", mode = Mode.OUT) Holder<NetworkStatus> status, + @WebParam(name = "routeTargets", mode = Mode.OUT) Holder<List<RouteTarget>> routeTargets, + @WebParam(name = "subnetIdMap", mode = Mode.OUT) Holder<Map<String, String>> subnetIdMap) + throws NetworkException; + + /** + * This is the "Delete Network" Web Service endpoint definition. + */ + @WebMethod + public void deleteNetwork(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "networkType") @XmlElement(required = true) String networkType, + @WebParam(name = "modelCustomizationUuid") String modelCustomizationUuid, + @WebParam(name = "networkId") @XmlElement(required = true) String networkId, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "networkDeleted", mode = Mode.OUT) Holder<Boolean> networkDeleted) throws NetworkException; + + /** + * This is the "Rollback Network" Web Service endpoint definition. + */ + @WebMethod + public void rollbackNetwork(@WebParam(name = "rollback") @XmlElement(required = true) NetworkRollback rollback) + throws NetworkException; + + @WebMethod + public void healthCheck(); } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsync.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsync.java index a85da58536..5b7340e24f 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsync.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsync.java @@ -23,87 +23,82 @@ package org.onap.so.adapters.network; import java.util.List; import java.util.Map; - import javax.jws.Oneway; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import javax.xml.bind.annotation.XmlElement; - import org.onap.so.entity.MsoRequest; import org.onap.so.openstack.beans.NetworkRollback; import org.onap.so.openstack.beans.Subnet; + /** - * This webservice defines the Asynchronous versions of NETWORK adapter calls. - * The notification messages for final responses are documented elsewhere - * (by the client service WSDL). + * This webservice defines the Asynchronous versions of NETWORK adapter calls. The notification messages for final + * responses are documented elsewhere (by the client service WSDL). * */ -@WebService (name="NetworkAdapterAsync", targetNamespace="http://org.onap.so/networkA") -public interface MsoNetworkAdapterAsync -{ - /** - * This is the "Create NETWORK" Web Service Endpoint definition. - */ - @WebMethod - @Oneway - public void createNetworkA (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="networkType") @XmlElement(required=true) String networkType, - @WebParam(name="modelCustomizationUuid") String modelCustomizationUuid, - @WebParam(name="networkName") @XmlElement(required=true) String networkName, - @WebParam(name="physicalNetworkName") String physicalNetworkName, - @WebParam(name="vlans") List<Integer> vlans, - @WebParam(name="failIfExists") Boolean failIfExists, - @WebParam(name="backout") Boolean backout, - @WebParam(name="subnets") List<Subnet> subnets, - @WebParam(name="networkParams") Map<String, String> networkParams, - @WebParam(name="messageId") @XmlElement(required=true) String messageId, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl ); +@WebService(name = "NetworkAdapterAsync", targetNamespace = "http://org.onap.so/networkA") +public interface MsoNetworkAdapterAsync { + /** + * This is the "Create NETWORK" Web Service Endpoint definition. + */ + @WebMethod + @Oneway + public void createNetworkA(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "networkType") @XmlElement(required = true) String networkType, + @WebParam(name = "modelCustomizationUuid") String modelCustomizationUuid, + @WebParam(name = "networkName") @XmlElement(required = true) String networkName, + @WebParam(name = "physicalNetworkName") String physicalNetworkName, + @WebParam(name = "vlans") List<Integer> vlans, @WebParam(name = "failIfExists") Boolean failIfExists, + @WebParam(name = "backout") Boolean backout, @WebParam(name = "subnets") List<Subnet> subnets, + @WebParam(name = "networkParams") Map<String, String> networkParams, + @WebParam(name = "messageId") @XmlElement(required = true) String messageId, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl); - @WebMethod - @Oneway - public void updateNetworkA (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="networkType") @XmlElement(required=true) String networkType, - @WebParam(name="modelCustomizationUuid") String modelCustomizationUuid, - @WebParam(name="networkId") @XmlElement(required=true) String networkId, - @WebParam(name="networkName") @XmlElement(required=true) String networkName, - @WebParam(name="physicalNetworkName") @XmlElement(required=true) String physicalNetworkName, - @WebParam(name="vlans") @XmlElement(required=true) List<Integer> vlans, - @WebParam(name="subnets") List<Subnet> subnets, - @WebParam(name="networkParams") Map<String, String> networkParams, - @WebParam(name="messageId") @XmlElement(required=true) String messageId, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl ); + @WebMethod + @Oneway + public void updateNetworkA(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "networkType") @XmlElement(required = true) String networkType, + @WebParam(name = "modelCustomizationUuid") String modelCustomizationUuid, + @WebParam(name = "networkId") @XmlElement(required = true) String networkId, + @WebParam(name = "networkName") @XmlElement(required = true) String networkName, + @WebParam(name = "physicalNetworkName") @XmlElement(required = true) String physicalNetworkName, + @WebParam(name = "vlans") @XmlElement(required = true) List<Integer> vlans, + @WebParam(name = "subnets") List<Subnet> subnets, + @WebParam(name = "networkParams") Map<String, String> networkParams, + @WebParam(name = "messageId") @XmlElement(required = true) String messageId, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl); - @WebMethod - @Oneway - public void queryNetworkA (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="networkNameOrId") @XmlElement(required=true) String networkNameOrId, - @WebParam(name="messageId") @XmlElement(required=true) String messageId, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl ); + @WebMethod + @Oneway + public void queryNetworkA(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "networkNameOrId") @XmlElement(required = true) String networkNameOrId, + @WebParam(name = "messageId") @XmlElement(required = true) String messageId, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl); - @WebMethod - @Oneway - public void deleteNetworkA (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="networkType") @XmlElement(required=true) String networkType, - @WebParam(name="modelCustomizationUuid") String modelCustomizationUuid, - @WebParam(name="networkId") @XmlElement(required=true) String networkId, - @WebParam(name="messageId") @XmlElement(required=true) String messageId, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl ); + @WebMethod + @Oneway + public void deleteNetworkA(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "networkType") @XmlElement(required = true) String networkType, + @WebParam(name = "modelCustomizationUuid") String modelCustomizationUuid, + @WebParam(name = "networkId") @XmlElement(required = true) String networkId, + @WebParam(name = "messageId") @XmlElement(required = true) String messageId, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl); - @WebMethod - @Oneway - public void rollbackNetworkA (@WebParam(name="rollback") @XmlElement(required=true) NetworkRollback rollback, - @WebParam(name="messageId") @XmlElement(required=true) String messageId, - @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl ); + @WebMethod + @Oneway + public void rollbackNetworkA(@WebParam(name = "rollback") @XmlElement(required = true) NetworkRollback rollback, + @WebParam(name = "messageId") @XmlElement(required = true) String messageId, + @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl); - @WebMethod - public void healthCheckA (); + @WebMethod + public void healthCheckA(); } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsyncImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsyncImpl.java index 53fa2f6dc2..d13b1724df 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsyncImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterAsyncImpl.java @@ -59,15 +59,17 @@ import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component -@WebService(serviceName = "NetworkAdapterAsync", endpointInterface = "org.onap.so.adapters.network.MsoNetworkAdapterAsync", targetNamespace = "http://org.onap.so/networkA") +@WebService(serviceName = "NetworkAdapterAsync", + endpointInterface = "org.onap.so.adapters.network.MsoNetworkAdapterAsync", + targetNamespace = "http://org.onap.so/networkA") public class MsoNetworkAdapterAsyncImpl implements MsoNetworkAdapterAsync { private static final Logger logger = LoggerFactory.getLogger(MsoNetworkAdapterAsyncImpl.class); private static final String BPEL_AUTH_PROP = "org.onap.so.adapters.network.bpelauth"; private static final String ENCRYPTION_KEY_PROP = "org.onap.so.adapters.network.encryptionKey"; - private static final String NETWORK_EXCEPTION_MSG="Got a NetworkException on createNetwork: "; - private static final String CREATE_NETWORK_ERROR_LOGMSG ="{} {} Error sending createNetwork notification {} "; + private static final String NETWORK_EXCEPTION_MSG = "Got a NetworkException on createNetwork: "; + private static final String CREATE_NETWORK_ERROR_LOGMSG = "{} {} Error sending createNetwork notification {} "; private static final String FAULT_INFO_ERROR_LOGMSG = "{} {} Exception - fault info "; @Autowired @@ -75,116 +77,86 @@ public class MsoNetworkAdapterAsyncImpl implements MsoNetworkAdapterAsync { @Autowired private MsoNetworkAdapter networkAdapter; + /** * Health Check web method. Does nothing but return to show the adapter is deployed. */ @Override - public void healthCheckA () { - logger.debug ("Health check call in Network Adapter"); + public void healthCheckA() { + logger.debug("Health check call in Network Adapter"); } /** - * This is the "Create Network" web service implementation. - * It will create a new Network of the requested type in the specified cloud - * and tenant. The tenant must exist at the time this service is called. + * This is the "Create Network" web service implementation. It will create a new Network of the requested type in + * the specified cloud and tenant. The tenant must exist at the time this service is called. * - * If a network with the same name already exists, this can be considered a - * success or failure, depending on the value of the 'failIfExists' parameter. + * If a network with the same name already exists, this can be considered a success or failure, depending on the + * value of the 'failIfExists' parameter. * - * There will be a pre-defined set of network types defined in the MSO Catalog. - * All such networks will have a similar configuration, based on the allowable - * Openstack networking definitions. This includes basic networks, provider - * networks (with a single VLAN), and multi-provider networks (one or more VLANs) + * There will be a pre-defined set of network types defined in the MSO Catalog. All such networks will have a + * similar configuration, based on the allowable Openstack networking definitions. This includes basic networks, + * provider networks (with a single VLAN), and multi-provider networks (one or more VLANs) * - * Initially, all provider networks must be "vlan" type, and multiple segments in - * a multi-provider network must be multiple VLANs on the same physical network. + * Initially, all provider networks must be "vlan" type, and multiple segments in a multi-provider network must be + * multiple VLANs on the same physical network. * - * This service supports two modes of Network creation/update: - * - via Heat Templates - * - via Neutron API - * The network orchestration mode for each network type is declared in its - * catalog definition. All Heat-based templates must support some subset of - * the same input parameters: network_name, physical_network, vlan(s). + * This service supports two modes of Network creation/update: - via Heat Templates - via Neutron API The network + * orchestration mode for each network type is declared in its catalog definition. All Heat-based templates must + * support some subset of the same input parameters: network_name, physical_network, vlan(s). * - * The method returns the network ID and a NetworkRollback object. This latter - * object can be passed as-is to the rollbackNetwork operation to undo everything - * that was created. This is useful if a network is successfully created but - * the orchestration fails on a subsequent operation. + * The method returns the network ID and a NetworkRollback object. This latter object can be passed as-is to the + * rollbackNetwork operation to undo everything that was created. This is useful if a network is successfully + * created but the orchestration fails on a subsequent operation. */ @Override - public void createNetworkA (String cloudSiteId, - String tenantId, - String networkType, - String modelCustomizationUuid, - String networkName, - String physicalNetworkName, - List <Integer> vlans, - Boolean failIfExists, - Boolean backout, - List <Subnet> subnets, - Map<String,String> networkParams, - String messageId, - MsoRequest msoRequest, - String notificationUrl) { + public void createNetworkA(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid, + String networkName, String physicalNetworkName, List<Integer> vlans, Boolean failIfExists, Boolean backout, + List<Subnet> subnets, Map<String, String> networkParams, String messageId, MsoRequest msoRequest, + String notificationUrl) { logger.debug("Async Create Network: {} of type {} in {}/{}", networkName, networkType, cloudSiteId, tenantId); // Use the synchronous method to perform the actual Create - + // Synchronous Web Service Outputs - Holder <String> networkId = new Holder <> (); - Holder <String> neutronNetworkId = new Holder <> (); - Holder <NetworkRollback> networkRollback = new Holder <> (); - Holder <Map <String, String>> subnetIdMap = new Holder <> (); - - HashMap<String, String> params = (HashMap<String,String>) networkParams; + Holder<String> networkId = new Holder<>(); + Holder<String> neutronNetworkId = new Holder<>(); + Holder<NetworkRollback> networkRollback = new Holder<>(); + Holder<Map<String, String>> subnetIdMap = new Holder<>(); + + HashMap<String, String> params = (HashMap<String, String>) networkParams; if (params == null) - params = new HashMap<String,String>(); + params = new HashMap<String, String>(); String shared = null; String external = null; if (params.containsKey("shared")) - shared = params.get("shared"); + shared = params.get("shared"); if (params.containsKey("external")) - external = params.get("external"); + external = params.get("external"); try { - networkAdapter.createNetwork (cloudSiteId, - tenantId, - networkType, - modelCustomizationUuid, - networkName, - physicalNetworkName, - vlans, - shared, - external, - failIfExists, - backout, - subnets, - params, - msoRequest, - networkId, - neutronNetworkId, - subnetIdMap, - networkRollback); + networkAdapter.createNetwork(cloudSiteId, tenantId, networkType, modelCustomizationUuid, networkName, + physicalNetworkName, vlans, shared, external, failIfExists, backout, subnets, params, msoRequest, + networkId, neutronNetworkId, subnetIdMap, networkRollback); } catch (NetworkException e) { - logger.debug (NETWORK_EXCEPTION_MSG, e); + logger.debug(NETWORK_EXCEPTION_MSG, e); MsoExceptionCategory exCat = null; String eMsg = null; try { - eMsg = e.getFaultInfo ().getMessage (); - exCat = MsoExceptionCategory.fromValue (e.getFaultInfo ().getCategory ().name ()); + eMsg = e.getFaultInfo().getMessage(); + exCat = MsoExceptionCategory.fromValue(e.getFaultInfo().getCategory().name()); } catch (Exception e1) { - logger.error(FAULT_INFO_ERROR_LOGMSG, MessageEnum.RA_FAULT_INFO_EXC, - ErrorCode.DataError.getValue(), e1); + logger.error(FAULT_INFO_ERROR_LOGMSG, MessageEnum.RA_FAULT_INFO_EXC, ErrorCode.DataError.getValue(), + e1); } // Build and send Asynchronous error response try { - NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl); - notifyPort.createNetworkNotification (messageId, false, exCat, eMsg, null, null, null, null); + NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl); + notifyPort.createNetworkNotification(messageId, false, exCat, eMsg, null, null, null, null); } catch (Exception e1) { logger.error(CREATE_NETWORK_ERROR_LOGMSG, MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC, - ErrorCode.DataError.getValue(), e1.getMessage(), e1); + ErrorCode.DataError.getValue(), e1.getMessage(), e1); } return; @@ -192,118 +164,83 @@ public class MsoNetworkAdapterAsyncImpl implements MsoNetworkAdapterAsync { logger.debug("Async Create Network:Name {} physicalNetworkName:{}", networkName, physicalNetworkName); // Build and send Asynchronous response try { - NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl); - notifyPort.createNetworkNotification (messageId, - true, - null, - null, - networkId.value, - neutronNetworkId.value, - copyCreateSubnetIdMap (subnetIdMap), - copyNrb (networkRollback)); + NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl); + notifyPort.createNetworkNotification(messageId, true, null, null, networkId.value, neutronNetworkId.value, + copyCreateSubnetIdMap(subnetIdMap), copyNrb(networkRollback)); } catch (Exception e) { logger.error(CREATE_NETWORK_ERROR_LOGMSG, MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC, - ErrorCode.DataError.getValue(), e.getMessage(), e); + ErrorCode.DataError.getValue(), e.getMessage(), e); } return; } /** - * This is the "Update Network" web service implementation. - * It will update an existing Network of the requested type in the specified cloud - * and tenant. The typical use will be to replace the VLANs with the supplied - * list (to add or remove a VLAN), but other properties may be updated as well. + * This is the "Update Network" web service implementation. It will update an existing Network of the requested type + * in the specified cloud and tenant. The typical use will be to replace the VLANs with the supplied list (to add or + * remove a VLAN), but other properties may be updated as well. * - * There will be a pre-defined set of network types defined in the MSO Catalog. - * All such networks will have a similar configuration, based on the allowable - * Openstack networking definitions. This includes basic networks, provider - * networks (with a single VLAN), and multi-provider networks (one or more VLANs). + * There will be a pre-defined set of network types defined in the MSO Catalog. All such networks will have a + * similar configuration, based on the allowable Openstack networking definitions. This includes basic networks, + * provider networks (with a single VLAN), and multi-provider networks (one or more VLANs). * - * Initially, all provider networks must currently be "vlan" type, and multi-provider - * networks must be multiple VLANs on the same physical network. + * Initially, all provider networks must currently be "vlan" type, and multi-provider networks must be multiple + * VLANs on the same physical network. * - * This service supports two modes of Network update: - * - via Heat Templates - * - via Neutron API - * The network orchestration mode for each network type is declared in its - * catalog definition. All Heat-based templates must support some subset of - * the same input parameters: network_name, physical_network, vlan, segments. + * This service supports two modes of Network update: - via Heat Templates - via Neutron API The network + * orchestration mode for each network type is declared in its catalog definition. All Heat-based templates must + * support some subset of the same input parameters: network_name, physical_network, vlan, segments. * - * The method returns a NetworkRollback object. This object can be passed - * as-is to the rollbackNetwork operation to undo everything that was updated. - * This is useful if a network is successfully updated but orchestration - * fails on a subsequent operation. + * The method returns a NetworkRollback object. This object can be passed as-is to the rollbackNetwork operation to + * undo everything that was updated. This is useful if a network is successfully updated but orchestration fails on + * a subsequent operation. */ @Override - public void updateNetworkA (String cloudSiteId, - String tenantId, - String networkType, - String modelCustomizationUuid, - String networkId, - String networkName, - String physicalNetworkName, - List <Integer> vlans, - List <Subnet> subnets, - Map <String,String> networkParams, - String messageId, - MsoRequest msoRequest, - String notificationUrl) { + public void updateNetworkA(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid, + String networkId, String networkName, String physicalNetworkName, List<Integer> vlans, List<Subnet> subnets, + Map<String, String> networkParams, String messageId, MsoRequest msoRequest, String notificationUrl) { logger.debug("Async Update Network: {} of type {} in {}/{}", networkId, networkType, cloudSiteId, tenantId); // Use the synchronous method to perform the actual Create - + // Synchronous Web Service Outputs - Holder <NetworkRollback> networkRollback = new Holder <> (); - Holder <Map <String, String>> subnetIdMap = new Holder <> (); - - HashMap<String, String> params = (HashMap<String,String>) networkParams; + Holder<NetworkRollback> networkRollback = new Holder<>(); + Holder<Map<String, String>> subnetIdMap = new Holder<>(); + + HashMap<String, String> params = (HashMap<String, String>) networkParams; if (params == null) - params = new HashMap<String,String>(); + params = new HashMap<String, String>(); String shared = null; String external = null; if (params.containsKey("shared")) - shared = params.get("shared"); + shared = params.get("shared"); if (params.containsKey("external")) - external = params.get("external"); + external = params.get("external"); try { - networkAdapter.updateNetwork (cloudSiteId, - tenantId, - networkType, - modelCustomizationUuid, - networkId, - networkName, - physicalNetworkName, - vlans, - shared, - external, - subnets, - params, - msoRequest, - subnetIdMap, - networkRollback); + networkAdapter.updateNetwork(cloudSiteId, tenantId, networkType, modelCustomizationUuid, networkId, + networkName, physicalNetworkName, vlans, shared, external, subnets, params, msoRequest, subnetIdMap, + networkRollback); } catch (NetworkException e) { - logger.debug ("Got a NetworkException on updateNetwork: ", e); + logger.debug("Got a NetworkException on updateNetwork: ", e); MsoExceptionCategory exCat = null; String eMsg = null; try { - eMsg = e.getFaultInfo ().getMessage (); - exCat = MsoExceptionCategory.fromValue (e.getFaultInfo ().getCategory ().name ()); + eMsg = e.getFaultInfo().getMessage(); + exCat = MsoExceptionCategory.fromValue(e.getFaultInfo().getCategory().name()); } catch (Exception e1) { - logger.error(FAULT_INFO_ERROR_LOGMSG, MessageEnum.RA_FAULT_INFO_EXC, - ErrorCode.DataError.getValue(), e1); + logger.error(FAULT_INFO_ERROR_LOGMSG, MessageEnum.RA_FAULT_INFO_EXC, ErrorCode.DataError.getValue(), + e1); } // Build and send Asynchronous error response try { - NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl); - notifyPort.updateNetworkNotification (messageId, false, exCat, eMsg, null, copyNrb (networkRollback)); + NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl); + notifyPort.updateNetworkNotification(messageId, false, exCat, eMsg, null, copyNrb(networkRollback)); } catch (Exception e1) { logger.error("{} {} Error sending updateNetwork notification {} ", - MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC, ErrorCode.DataError.getValue(), e1.getMessage(), - e1); + MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC, ErrorCode.DataError.getValue(), e1.getMessage(), e1); } return; @@ -311,161 +248,127 @@ public class MsoNetworkAdapterAsyncImpl implements MsoNetworkAdapterAsync { logger.debug("Async Update Network:Name {} NetworkId:{}", networkName, networkId); // Build and send Asynchronous response try { - NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl); - notifyPort.updateNetworkNotification (messageId, - true, - null, - null, - copyUpdateSubnetIdMap (subnetIdMap), - copyNrb (networkRollback)); + NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl); + notifyPort.updateNetworkNotification(messageId, true, null, null, copyUpdateSubnetIdMap(subnetIdMap), + copyNrb(networkRollback)); } catch (Exception e) { logger.error("{} {} Error sending updateNotification request {} ", MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC, - ErrorCode.DataError.getValue(), e.getMessage(), e); + ErrorCode.DataError.getValue(), e.getMessage(), e); } return; } /** - * This is the queryNetwork method. It returns the existence and status of - * the specified network, along with its Neutron UUID and list of VLANs. - * This method attempts to find the network using both Heat and Neutron. - * Heat stacks are first searched based on the provided network name/id. - * If none is found, the Neutron is directly queried. + * This is the queryNetwork method. It returns the existence and status of the specified network, along with its + * Neutron UUID and list of VLANs. This method attempts to find the network using both Heat and Neutron. Heat stacks + * are first searched based on the provided network name/id. If none is found, the Neutron is directly queried. */ @Override - public void queryNetworkA (String cloudSiteId, - String tenantId, - String networkNameOrId, - String messageId, - MsoRequest msoRequest, - String notificationUrl) { + public void queryNetworkA(String cloudSiteId, String tenantId, String networkNameOrId, String messageId, + MsoRequest msoRequest, String notificationUrl) { logger.debug("Async Query Network {} in {}/{}", networkNameOrId, cloudSiteId, tenantId); String errorCreateNetworkMessage = "{} {} Error sending createNetwork notification {} "; // Use the synchronous method to perform the actual Create - + // Synchronous Web Service Outputs - Holder <Boolean> networkExists = new Holder <> (); - Holder <String> networkId = new Holder <> (); - Holder <String> neutronNetworkId = new Holder <> (); - Holder <NetworkStatus> status = new Holder <> (); - Holder <List <Integer>> vlans = new Holder <> (); - Holder <Map <String, String>> subnetIdMap = new Holder <> (); + Holder<Boolean> networkExists = new Holder<>(); + Holder<String> networkId = new Holder<>(); + Holder<String> neutronNetworkId = new Holder<>(); + Holder<NetworkStatus> status = new Holder<>(); + Holder<List<Integer>> vlans = new Holder<>(); + Holder<Map<String, String>> subnetIdMap = new Holder<>(); try { - networkAdapter.queryNetwork (cloudSiteId, - tenantId, - networkNameOrId, - msoRequest, - networkExists, - networkId, - neutronNetworkId, - status, - vlans, - subnetIdMap); + networkAdapter.queryNetwork(cloudSiteId, tenantId, networkNameOrId, msoRequest, networkExists, networkId, + neutronNetworkId, status, vlans, subnetIdMap); } catch (NetworkException e) { - logger.debug (NETWORK_EXCEPTION_MSG, e); + logger.debug(NETWORK_EXCEPTION_MSG, e); MsoExceptionCategory exCat = null; String eMsg = null; try { - eMsg = e.getFaultInfo ().getMessage (); - exCat = MsoExceptionCategory.fromValue (e.getFaultInfo ().getCategory ().name ()); + eMsg = e.getFaultInfo().getMessage(); + exCat = MsoExceptionCategory.fromValue(e.getFaultInfo().getCategory().name()); } catch (Exception e1) { - logger.error(FAULT_INFO_ERROR_LOGMSG, MessageEnum.RA_FAULT_INFO_EXC, - ErrorCode.DataError.getValue(), e1); + logger.error(FAULT_INFO_ERROR_LOGMSG, MessageEnum.RA_FAULT_INFO_EXC, ErrorCode.DataError.getValue(), + e1); } // Build and send Asynchronous error response try { - NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl); - notifyPort.queryNetworkNotification (messageId, false, exCat, eMsg, null, null, null, null, null, null); + NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl); + notifyPort.queryNetworkNotification(messageId, false, exCat, eMsg, null, null, null, null, null, null); } catch (Exception e1) { logger.error(errorCreateNetworkMessage, MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC, - ErrorCode.DataError.getValue(), e1.getMessage(), e1); + ErrorCode.DataError.getValue(), e1.getMessage(), e1); } return; } logger.debug("Async Query Network:NameOrId {} tenantId:{}", networkNameOrId, tenantId); // Build and send Asynchronous response try { - NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl); - org.onap.so.adapters.network.async.client.NetworkStatus networkS = org.onap.so.adapters.network.async.client.NetworkStatus.fromValue (status.value.name ()); - notifyPort.queryNetworkNotification (messageId, - true, - null, - null, - networkExists.value, - networkId.value, - neutronNetworkId.value, - networkS, - vlans.value, - copyQuerySubnetIdMap (subnetIdMap)); + NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl); + org.onap.so.adapters.network.async.client.NetworkStatus networkS = + org.onap.so.adapters.network.async.client.NetworkStatus.fromValue(status.value.name()); + notifyPort.queryNetworkNotification(messageId, true, null, null, networkExists.value, networkId.value, + neutronNetworkId.value, networkS, vlans.value, copyQuerySubnetIdMap(subnetIdMap)); } catch (Exception e) { logger.error(errorCreateNetworkMessage, MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC, - ErrorCode.DataError.getValue(), e.getMessage(), e); + ErrorCode.DataError.getValue(), e.getMessage(), e); } return; } /** - * This is the "Delete Network" web service implementation. - * It will delete a Network in the specified cloud and tenant. + * This is the "Delete Network" web service implementation. It will delete a Network in the specified cloud and + * tenant. * * If the network is not found, it is treated as a success. * - * This service supports two modes of Network creation/update/delete: - * - via Heat Templates - * - via Neutron API - * The network orchestration mode for each network type is declared in its - * catalog definition. + * This service supports two modes of Network creation/update/delete: - via Heat Templates - via Neutron API The + * network orchestration mode for each network type is declared in its catalog definition. * - * For Heat-based orchestration, the networkId should be the stack ID. - * For Neutron-based orchestration, the networkId should be the Neutron network UUID. + * For Heat-based orchestration, the networkId should be the stack ID. For Neutron-based orchestration, the + * networkId should be the Neutron network UUID. * - * The method returns nothing on success. Rollback is not possible for delete - * commands, so any failure on delete will require manual fallout in the client. + * The method returns nothing on success. Rollback is not possible for delete commands, so any failure on delete + * will require manual fallout in the client. */ @Override - public void deleteNetworkA (String cloudSiteId, - String tenantId, - String networkType, - String modelCustomizationUuid, - String networkId, - String messageId, - MsoRequest msoRequest, - String notificationUrl) { + public void deleteNetworkA(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid, + String networkId, String messageId, MsoRequest msoRequest, String notificationUrl) { String serviceName = "DeleteNetworkA"; logger.debug("Async Delete Network {} in {}/{}", networkId, cloudSiteId, tenantId); // Use the synchronous method to perform the actual Create - + // Synchronous Web Service Outputs - Holder <Boolean> networkDeleted = new Holder <> (); + Holder<Boolean> networkDeleted = new Holder<>(); try { - networkAdapter.deleteNetwork (cloudSiteId, tenantId, networkType, modelCustomizationUuid, networkId, msoRequest, networkDeleted); + networkAdapter.deleteNetwork(cloudSiteId, tenantId, networkType, modelCustomizationUuid, networkId, + msoRequest, networkDeleted); } catch (NetworkException e) { - logger.debug (NETWORK_EXCEPTION_MSG, e); + logger.debug(NETWORK_EXCEPTION_MSG, e); MsoExceptionCategory exCat = null; String eMsg = null; try { - eMsg = e.getFaultInfo ().getMessage (); - exCat = MsoExceptionCategory.fromValue (e.getFaultInfo ().getCategory ().name ()); + eMsg = e.getFaultInfo().getMessage(); + exCat = MsoExceptionCategory.fromValue(e.getFaultInfo().getCategory().name()); } catch (Exception e1) { - logger.error(FAULT_INFO_ERROR_LOGMSG, MessageEnum.RA_FAULT_INFO_EXC, - ErrorCode.DataError.getValue(), e1); + logger.error(FAULT_INFO_ERROR_LOGMSG, MessageEnum.RA_FAULT_INFO_EXC, ErrorCode.DataError.getValue(), + e1); } // Build and send Asynchronous error response try { - NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl); - notifyPort.deleteNetworkNotification (messageId, false, exCat, eMsg, null); + NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl); + notifyPort.deleteNetworkNotification(messageId, false, exCat, eMsg, null); } catch (Exception e1) { logger.error("{} {} Error sending createNetwork notification {} ", - MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC, ErrorCode.DataError.getValue(), e1.getMessage(), - e1); + MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC, ErrorCode.DataError.getValue(), e1.getMessage(), e1); } return; @@ -473,59 +376,57 @@ public class MsoNetworkAdapterAsyncImpl implements MsoNetworkAdapterAsync { logger.debug("Async Delete NetworkId: {} tenantId:{}", networkId, tenantId); // Build and send Asynchronous response try { - NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl); - notifyPort.deleteNetworkNotification (messageId, true, null, null, networkDeleted.value); + NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl); + notifyPort.deleteNetworkNotification(messageId, true, null, null, networkDeleted.value); } catch (Exception e) { logger.error("{} {} Error sending deleteNetwork notification {} ", MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC, - ErrorCode.DataError.getValue(), e.getMessage(), e); + ErrorCode.DataError.getValue(), e.getMessage(), e); } return; } /** - * This web service endpoint will rollback a previous Create VNF operation. - * A rollback object is returned to the client in a successful creation - * response. The client can pass that object as-is back to the rollbackNetwork + * This web service endpoint will rollback a previous Create VNF operation. A rollback object is returned to the + * client in a successful creation response. The client can pass that object as-is back to the rollbackNetwork * operation to undo the creation. * - * The rollback includes removing the VNF and deleting the tenant if the - * tenant did not exist prior to the VNF creation. + * The rollback includes removing the VNF and deleting the tenant if the tenant did not exist prior to the VNF + * creation. */ @Override - public void rollbackNetworkA (NetworkRollback rollback, String messageId, String notificationUrl) { + public void rollbackNetworkA(NetworkRollback rollback, String messageId, String notificationUrl) { // rollback may be null (e.g. if network already existed when Create was called) if (rollback == null) { - logger.warn("{} {} Rollback is null", MessageEnum.RA_ROLLBACK_NULL, - ErrorCode.SchemaError.getValue()); + logger.warn("{} {} Rollback is null", MessageEnum.RA_ROLLBACK_NULL, ErrorCode.SchemaError.getValue()); return; } logger.info("{} {}", MessageEnum.RA_ASYNC_ROLLBACK, rollback.getNetworkStackId()); // Use the synchronous method to perform the actual Create - + try { - networkAdapter.rollbackNetwork (rollback); + networkAdapter.rollbackNetwork(rollback); } catch (NetworkException e) { - logger.debug ("Got a NetworkException on rollbackNetwork: ", e); + logger.debug("Got a NetworkException on rollbackNetwork: ", e); // Build and send Asynchronous error response MsoExceptionCategory exCat = null; String eMsg = null; try { - eMsg = e.getFaultInfo ().getMessage (); - exCat = MsoExceptionCategory.fromValue (e.getFaultInfo ().getCategory ().name ()); + eMsg = e.getFaultInfo().getMessage(); + exCat = MsoExceptionCategory.fromValue(e.getFaultInfo().getCategory().name()); } catch (Exception e1) { logger.error("{} {} Exception in get fault info ", MessageEnum.RA_FAULT_INFO_EXC, - ErrorCode.DataError.getValue(), e1); + ErrorCode.DataError.getValue(), e1); } // Build and send Asynchronous error response try { - NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl); - notifyPort.rollbackNetworkNotification (rollback.getMsoRequest ().getRequestId (), false, exCat, eMsg); + NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl); + notifyPort.rollbackNetworkNotification(rollback.getMsoRequest().getRequestId(), false, exCat, eMsg); } catch (Exception e1) { logger.error(CREATE_NETWORK_ERROR_LOGMSG, MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC, - ErrorCode.DataError.getValue(), e1.getMessage(), e1); + ErrorCode.DataError.getValue(), e1.getMessage(), e1); } return; @@ -533,169 +434,167 @@ public class MsoNetworkAdapterAsyncImpl implements MsoNetworkAdapterAsync { logger.debug("Async Rollback NetworkId: {} tenantId:{}", rollback.getNetworkStackId(), rollback.getTenantId()); // Build and send Asynchronous response try { - NetworkAdapterNotify notifyPort = getNotifyEP (notificationUrl); - notifyPort.rollbackNetworkNotification (rollback.getMsoRequest ().getRequestId (), true, null, null); + NetworkAdapterNotify notifyPort = getNotifyEP(notificationUrl); + notifyPort.rollbackNetworkNotification(rollback.getMsoRequest().getRequestId(), true, null, null); } catch (Exception e) { - logger - .error("{} {} Error sending rollbackNetwork notification {} ", MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC, - ErrorCode.DataError.getValue(), e.getMessage(), e); + logger.error("{} {} Error sending rollbackNetwork notification {} ", + MessageEnum.RA_CREATE_NETWORK_NOTIF_EXC, ErrorCode.DataError.getValue(), e.getMessage(), e); } return; } - private org.onap.so.adapters.network.async.client.NetworkRollback copyNrb (Holder <NetworkRollback> hNrb) { - org.onap.so.adapters.network.async.client.NetworkRollback cnrb = new org.onap.so.adapters.network.async.client.NetworkRollback (); + private org.onap.so.adapters.network.async.client.NetworkRollback copyNrb(Holder<NetworkRollback> hNrb) { + org.onap.so.adapters.network.async.client.NetworkRollback cnrb = + new org.onap.so.adapters.network.async.client.NetworkRollback(); if (hNrb != null && hNrb.value != null) { - org.onap.so.adapters.network.async.client.MsoRequest cmr = new org.onap.so.adapters.network.async.client.MsoRequest (); - - cnrb.setCloudId (hNrb.value.getCloudId ()); - cmr.setRequestId (hNrb.value.getMsoRequest ().getRequestId ()); - cmr.setServiceInstanceId (hNrb.value.getMsoRequest ().getServiceInstanceId ()); - cnrb.setMsoRequest (cmr); - cnrb.setNetworkId (hNrb.value.getNetworkId ()); - cnrb.setNetworkStackId (hNrb.value.getNetworkStackId ()); - cnrb.setNeutronNetworkId (hNrb.value.getNeutronNetworkId ()); - cnrb.setTenantId (hNrb.value.getTenantId ()); - cnrb.setNetworkType (hNrb.value.getNetworkType ()); - cnrb.setNetworkCreated (hNrb.value.getNetworkCreated ()); - cnrb.setNetworkName (hNrb.value.getNetworkName ()); - cnrb.setPhysicalNetwork (hNrb.value.getPhysicalNetwork ()); - List <Integer> vlansc = cnrb.getVlans (); - List <Integer> vlansh = hNrb.value.getVlans (); + org.onap.so.adapters.network.async.client.MsoRequest cmr = + new org.onap.so.adapters.network.async.client.MsoRequest(); + + cnrb.setCloudId(hNrb.value.getCloudId()); + cmr.setRequestId(hNrb.value.getMsoRequest().getRequestId()); + cmr.setServiceInstanceId(hNrb.value.getMsoRequest().getServiceInstanceId()); + cnrb.setMsoRequest(cmr); + cnrb.setNetworkId(hNrb.value.getNetworkId()); + cnrb.setNetworkStackId(hNrb.value.getNetworkStackId()); + cnrb.setNeutronNetworkId(hNrb.value.getNeutronNetworkId()); + cnrb.setTenantId(hNrb.value.getTenantId()); + cnrb.setNetworkType(hNrb.value.getNetworkType()); + cnrb.setNetworkCreated(hNrb.value.getNetworkCreated()); + cnrb.setNetworkName(hNrb.value.getNetworkName()); + cnrb.setPhysicalNetwork(hNrb.value.getPhysicalNetwork()); + List<Integer> vlansc = cnrb.getVlans(); + List<Integer> vlansh = hNrb.value.getVlans(); if (vlansh != null) { - vlansc.addAll (vlansh); + vlansc.addAll(vlansh); } } return cnrb; } - private NetworkAdapterNotify getNotifyEP (String notificationUrl) { + private NetworkAdapterNotify getNotifyEP(String notificationUrl) { URL warWsdlLoc = null; try { - warWsdlLoc = Thread.currentThread ().getContextClassLoader ().getResource ("NetworkAdapterNotify.wsdl"); + warWsdlLoc = Thread.currentThread().getContextClassLoader().getResource("NetworkAdapterNotify.wsdl"); } catch (Exception e) { logger.error("{} {} Exception - WSDL not found ", MessageEnum.RA_WSDL_NOT_FOUND, - ErrorCode.DataError.getValue(), e); + ErrorCode.DataError.getValue(), e); } if (warWsdlLoc == null) { - logger - .error("{} {} WSDL not found", MessageEnum.RA_WSDL_NOT_FOUND, ErrorCode.DataError.getValue()); + logger.error("{} {} WSDL not found", MessageEnum.RA_WSDL_NOT_FOUND, ErrorCode.DataError.getValue()); } else { try { logger.debug("NetworkAdpaterNotify.wsdl location: {}", warWsdlLoc.toURI().toString()); } catch (Exception e) { logger.error("{} {} Exception - WSDL URL convention ", MessageEnum.RA_WSDL_URL_CONVENTION_EXC, - ErrorCode.SchemaError.getValue(), e); + ErrorCode.SchemaError.getValue(), e); } } - NetworkAdapterNotify_Service notifySvc = new NetworkAdapterNotify_Service (warWsdlLoc, - new QName ("http://org.onap.so/networkNotify", - "networkAdapterNotify")); + NetworkAdapterNotify_Service notifySvc = new NetworkAdapterNotify_Service(warWsdlLoc, + new QName("http://org.onap.so/networkNotify", "networkAdapterNotify")); - NetworkAdapterNotify notifyPort = notifySvc.getMsoNetworkAdapterAsyncImplPort (); + NetworkAdapterNotify notifyPort = notifySvc.getMsoNetworkAdapterAsyncImplPort(); BindingProvider bp = (BindingProvider) notifyPort; URL epUrl = null; try { - epUrl = new URL (notificationUrl); + epUrl = new URL(notificationUrl); } catch (MalformedURLException e1) { logger.error("{} {} Exception - init notification ", MessageEnum.RA_INIT_NOTIF_EXC, - ErrorCode.DataError.getValue(), e1); + ErrorCode.DataError.getValue(), e1); } - if(null != epUrl) { + if (null != epUrl) { logger.debug("Notification Endpoint URL: {}", epUrl.toExternalForm()); - bp.getRequestContext ().put (BindingProvider.ENDPOINT_ADDRESS_PROPERTY, epUrl.toExternalForm ()); - } - else { + bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, epUrl.toExternalForm()); + } else { logger.debug("Notification Endpoint URL is NULL: "); } // authentication try { - Map <String, Object> reqCtx = bp.getRequestContext (); - Map <String, List <String>> headers = new HashMap <> (); + Map<String, Object> reqCtx = bp.getRequestContext(); + Map<String, List<String>> headers = new HashMap<>(); - String userCredentials = this.getEncryptedProperty (BPEL_AUTH_PROP, "", ENCRYPTION_KEY_PROP); + String userCredentials = this.getEncryptedProperty(BPEL_AUTH_PROP, "", ENCRYPTION_KEY_PROP); - String basicAuth = "Basic " + DatatypeConverter.printBase64Binary (userCredentials.getBytes ()); - reqCtx.put (MessageContext.HTTP_REQUEST_HEADERS, headers); - headers.put ("Authorization", Collections.singletonList (basicAuth)); + String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()); + reqCtx.put(MessageContext.HTTP_REQUEST_HEADERS, headers); + headers.put("Authorization", Collections.singletonList(basicAuth)); } catch (Exception e) { logger.error("{} {} Unable to set authorization in callback request {} ", - MessageEnum.RA_SET_CALLBACK_AUTH_EXC, ErrorCode.DataError.getValue(), e.getMessage(), e); + MessageEnum.RA_SET_CALLBACK_AUTH_EXC, ErrorCode.DataError.getValue(), e.getMessage(), e); } return notifyPort; } - + public String getEncryptedProperty(String key, String defaultValue, String encryptionKey) { - try { - return CryptoUtils.decrypt(this.environment.getProperty(key), this.environment.getProperty(encryptionKey)); - } catch (GeneralSecurityException e) { - logger.debug("Exception while decrypting property: {} ", this.environment.getProperty(key), e); - } - return defaultValue; + try { + return CryptoUtils.decrypt(this.environment.getProperty(key), this.environment.getProperty(encryptionKey)); + } catch (GeneralSecurityException e) { + logger.debug("Exception while decrypting property: {} ", this.environment.getProperty(key), e); + } + return defaultValue; - } + } - private CreateNetworkNotification.SubnetIdMap copyCreateSubnetIdMap (Holder <Map <String, String>> hMap) { + private CreateNetworkNotification.SubnetIdMap copyCreateSubnetIdMap(Holder<Map<String, String>> hMap) { - CreateNetworkNotification.SubnetIdMap subnetIdMap = new CreateNetworkNotification.SubnetIdMap (); + CreateNetworkNotification.SubnetIdMap subnetIdMap = new CreateNetworkNotification.SubnetIdMap(); if (hMap != null && hMap.value != null) { - Map <String, String> sMap = hMap.value; - CreateNetworkNotification.SubnetIdMap.Entry entry = new CreateNetworkNotification.SubnetIdMap.Entry (); - - for (Map.Entry<String,String> mapEntry : sMap.entrySet ()) { - String key = mapEntry.getKey(); - String value = mapEntry.getValue(); - entry.setKey (key); - entry.setValue (value); - subnetIdMap.getEntry ().add (entry); + Map<String, String> sMap = hMap.value; + CreateNetworkNotification.SubnetIdMap.Entry entry = new CreateNetworkNotification.SubnetIdMap.Entry(); + + for (Map.Entry<String, String> mapEntry : sMap.entrySet()) { + String key = mapEntry.getKey(); + String value = mapEntry.getValue(); + entry.setKey(key); + entry.setValue(value); + subnetIdMap.getEntry().add(entry); } } return subnetIdMap; } - private UpdateNetworkNotification.SubnetIdMap copyUpdateSubnetIdMap (Holder <Map <String, String>> hMap) { + private UpdateNetworkNotification.SubnetIdMap copyUpdateSubnetIdMap(Holder<Map<String, String>> hMap) { - UpdateNetworkNotification.SubnetIdMap subnetIdMap = new UpdateNetworkNotification.SubnetIdMap (); + UpdateNetworkNotification.SubnetIdMap subnetIdMap = new UpdateNetworkNotification.SubnetIdMap(); if (hMap != null && hMap.value != null) { - Map <String, String> sMap = hMap.value; - UpdateNetworkNotification.SubnetIdMap.Entry entry = new UpdateNetworkNotification.SubnetIdMap.Entry (); - - for (Map.Entry<String,String> mapEntry : sMap.entrySet ()) { - String key = mapEntry.getKey(); - String value = mapEntry.getValue(); - entry.setKey (key); - entry.setValue (value); - subnetIdMap.getEntry ().add (entry); + Map<String, String> sMap = hMap.value; + UpdateNetworkNotification.SubnetIdMap.Entry entry = new UpdateNetworkNotification.SubnetIdMap.Entry(); + + for (Map.Entry<String, String> mapEntry : sMap.entrySet()) { + String key = mapEntry.getKey(); + String value = mapEntry.getValue(); + entry.setKey(key); + entry.setValue(value); + subnetIdMap.getEntry().add(entry); } } return subnetIdMap; } - private QueryNetworkNotification.SubnetIdMap copyQuerySubnetIdMap (Holder <Map <String, String>> hMap) { + private QueryNetworkNotification.SubnetIdMap copyQuerySubnetIdMap(Holder<Map<String, String>> hMap) { - QueryNetworkNotification.SubnetIdMap subnetIdMap = new QueryNetworkNotification.SubnetIdMap (); + QueryNetworkNotification.SubnetIdMap subnetIdMap = new QueryNetworkNotification.SubnetIdMap(); if (hMap != null && hMap.value != null) { - Map <String, String> sMap = hMap.value; - QueryNetworkNotification.SubnetIdMap.Entry entry = new QueryNetworkNotification.SubnetIdMap.Entry (); - - for (Map.Entry<String,String> mapEntry : sMap.entrySet ()) { - String key = mapEntry.getKey(); - String value = mapEntry.getValue(); - entry.setKey (key); - entry.setValue (value); - subnetIdMap.getEntry ().add (entry); + Map<String, String> sMap = hMap.value; + QueryNetworkNotification.SubnetIdMap.Entry entry = new QueryNetworkNotification.SubnetIdMap.Entry(); + + for (Map.Entry<String, String> mapEntry : sMap.entrySet()) { + String key = mapEntry.getKey(); + String value = mapEntry.getValue(); + entry.setKey(key); + entry.setValue(value); + subnetIdMap.getEntry().add(entry); } } return subnetIdMap; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java index 73e7143ae3..a79a6191cf 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java @@ -76,11 +76,12 @@ import org.springframework.transaction.annotation.Transactional; @Component @Transactional -@WebService(serviceName = "NetworkAdapter", endpointInterface = "org.onap.so.adapters.network.MsoNetworkAdapter", targetNamespace = "http://org.onap.so/network") +@WebService(serviceName = "NetworkAdapter", endpointInterface = "org.onap.so.adapters.network.MsoNetworkAdapter", + targetNamespace = "http://org.onap.so/network") public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { - private static final String AIC3_NW_PROPERTY= "org.onap.so.adapters.network.aic3nw"; - private static final String AIC3_NW="OS::ContrailV2::VirtualNetwork"; + private static final String AIC3_NW_PROPERTY = "org.onap.so.adapters.network.aic3nw"; + private static final String AIC3_NW = "OS::ContrailV2::VirtualNetwork"; private static final String VLANS = "vlans"; private static final String PHYSICAL_NETWORK = "physical_network"; private static final String UPDATE_NETWORK_CONTEXT = "UpdateNetwork"; @@ -106,176 +107,93 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { private MsoCommonUtils commonUtils; @Autowired - private NetworkResourceCustomizationRepository networkCustomRepo; + private NetworkResourceCustomizationRepository networkCustomRepo; @Autowired private CollectionNetworkResourceCustomizationRepository collectionNetworkCustomRepo; @Autowired - private NetworkResourceRepository networkResourceRepo; + private NetworkResourceRepository networkResourceRepo; + /** * Health Check web method. Does nothing but return to show the adapter is deployed. */ @Override - public void healthCheck () { - logger.debug ("Health check call in Network Adapter"); + public void healthCheck() { + logger.debug("Health check call in Network Adapter"); } /** * Do not use this constructor or the msoPropertiesFactory will be NULL. * - * @see MsoNetworkAdapterImpl#MsoNetworkAdapterImpl(MsoPropertiesFactory) + * @see MsoNetworkAdapterImpl#MsoNetworkAdapterImpl(MsoPropertiesFactory) */ - public MsoNetworkAdapterImpl() { - } + public MsoNetworkAdapterImpl() {} @Override - public void createNetwork (String cloudSiteId, - String tenantId, - String networkType, - String modelCustomizationUuid, - String networkName, - String physicalNetworkName, - List <Integer> vlans, - String shared, - String external, - Boolean failIfExists, - Boolean backout, - List <Subnet> subnets, - Map<String, String> networkParams, - MsoRequest msoRequest, - Holder <String> networkId, - Holder <String> neutronNetworkId, - Holder <Map <String, String>> subnetIdMap, - Holder <NetworkRollback> rollback) throws NetworkException { - Holder <String> networkFqdn = new Holder <> (); - createNetwork (cloudSiteId, - tenantId, - networkType, - modelCustomizationUuid, - networkName, - physicalNetworkName, - vlans, - null, - shared, - external, - failIfExists, - backout, - subnets, - null, - null, - msoRequest, - networkId, - neutronNetworkId, - networkFqdn, - subnetIdMap, - rollback); + public void createNetwork(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid, + String networkName, String physicalNetworkName, List<Integer> vlans, String shared, String external, + Boolean failIfExists, Boolean backout, List<Subnet> subnets, Map<String, String> networkParams, + MsoRequest msoRequest, Holder<String> networkId, Holder<String> neutronNetworkId, + Holder<Map<String, String>> subnetIdMap, Holder<NetworkRollback> rollback) throws NetworkException { + Holder<String> networkFqdn = new Holder<>(); + createNetwork(cloudSiteId, tenantId, networkType, modelCustomizationUuid, networkName, physicalNetworkName, + vlans, null, shared, external, failIfExists, backout, subnets, null, null, msoRequest, networkId, + neutronNetworkId, networkFqdn, subnetIdMap, rollback); } @Override - public void createNetworkContrail (String cloudSiteId, - String tenantId, - String networkType, - String modelCustomizationUuid, - String networkName, - List <RouteTarget> routeTargets, - String shared, - String external, - Boolean failIfExists, - Boolean backout, - List <Subnet> subnets, - Map<String, String> networkParams, - List <String> policyFqdns, - List<String> routeTableFqdns, - MsoRequest msoRequest, - Holder <String> networkId, - Holder <String> neutronNetworkId, - Holder <String> networkFqdn, - Holder <Map <String, String>> subnetIdMap, - Holder <NetworkRollback> rollback) throws NetworkException { - createNetwork (cloudSiteId, - tenantId, - networkType, - modelCustomizationUuid, - networkName, - null, - null, - routeTargets, - shared, - external, - failIfExists, - backout, - subnets, - policyFqdns, - routeTableFqdns, - msoRequest, - networkId, - neutronNetworkId, - networkFqdn, - subnetIdMap, - rollback); + public void createNetworkContrail(String cloudSiteId, String tenantId, String networkType, + String modelCustomizationUuid, String networkName, List<RouteTarget> routeTargets, String shared, + String external, Boolean failIfExists, Boolean backout, List<Subnet> subnets, + Map<String, String> networkParams, List<String> policyFqdns, List<String> routeTableFqdns, + MsoRequest msoRequest, Holder<String> networkId, Holder<String> neutronNetworkId, + Holder<String> networkFqdn, Holder<Map<String, String>> subnetIdMap, Holder<NetworkRollback> rollback) + throws NetworkException { + createNetwork(cloudSiteId, tenantId, networkType, modelCustomizationUuid, networkName, null, null, routeTargets, + shared, external, failIfExists, backout, subnets, policyFqdns, routeTableFqdns, msoRequest, networkId, + neutronNetworkId, networkFqdn, subnetIdMap, rollback); } /** - * This is the "Create Network" web service implementation. - * It will create a new Network of the requested type in the specified cloud - * and tenant. The tenant must exist at the time this service is called. + * This is the "Create Network" web service implementation. It will create a new Network of the requested type in + * the specified cloud and tenant. The tenant must exist at the time this service is called. * - * If a network with the same name already exists, this can be considered a - * success or failure, depending on the value of the 'failIfExists' parameter. + * If a network with the same name already exists, this can be considered a success or failure, depending on the + * value of the 'failIfExists' parameter. * - * There will be a pre-defined set of network types defined in the MSO Catalog. - * All such networks will have a similar configuration, based on the allowable - * Openstack networking definitions. This includes basic networks, provider - * networks (with a single VLAN), and multi-provider networks (one or more VLANs) + * There will be a pre-defined set of network types defined in the MSO Catalog. All such networks will have a + * similar configuration, based on the allowable Openstack networking definitions. This includes basic networks, + * provider networks (with a single VLAN), and multi-provider networks (one or more VLANs) * - * Initially, all provider networks must be "vlan" type, and multiple segments in - * a multi-provider network must be multiple VLANs on the same physical network. + * Initially, all provider networks must be "vlan" type, and multiple segments in a multi-provider network must be + * multiple VLANs on the same physical network. * - * This service supports two modes of Network creation/update: - * - via Heat Templates - * - via Neutron API - * The network orchestration mode for each network type is declared in its - * catalog definition. All Heat-based templates must support some subset of - * the same input parameters: network_name, physical_network, vlan(s). + * This service supports two modes of Network creation/update: - via Heat Templates - via Neutron API The network + * orchestration mode for each network type is declared in its catalog definition. All Heat-based templates must + * support some subset of the same input parameters: network_name, physical_network, vlan(s). * - * The method returns the network ID and a NetworkRollback object. This latter - * object can be passed as-is to the rollbackNetwork operation to undo everything - * that was created. This is useful if a network is successfully created but - * the orchestration fails on a subsequent operation. + * The method returns the network ID and a NetworkRollback object. This latter object can be passed as-is to the + * rollbackNetwork operation to undo everything that was created. This is useful if a network is successfully + * created but the orchestration fails on a subsequent operation. */ - private void createNetwork (String cloudSiteId, - String tenantId, - String networkType, - String modelCustomizationUuid, - String networkName, - String physicalNetworkName, - List <Integer> vlans, - List <RouteTarget> routeTargets, - String shared, - String external, - Boolean failIfExists, - Boolean backout, - List <Subnet> subnets, - List <String> policyFqdns, - List <String> routeTableFqdns, - MsoRequest msoRequest, - Holder <String> networkId, - Holder <String> neutronNetworkId, - Holder <String> networkFqdn, - Holder <Map <String, String>> subnetIdMap, - Holder <NetworkRollback> rollback) throws NetworkException { + private void createNetwork(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid, + String networkName, String physicalNetworkName, List<Integer> vlans, List<RouteTarget> routeTargets, + String shared, String external, Boolean failIfExists, Boolean backout, List<Subnet> subnets, + List<String> policyFqdns, List<String> routeTableFqdns, MsoRequest msoRequest, Holder<String> networkId, + Holder<String> neutronNetworkId, Holder<String> networkFqdn, Holder<Map<String, String>> subnetIdMap, + Holder<NetworkRollback> rollback) throws NetworkException { logger.debug("*** CREATE Network: {} of type {} in {}/{}", networkName, networkType, cloudSiteId, tenantId); // Will capture execution time for metrics - long startTime = System.currentTimeMillis (); + long startTime = System.currentTimeMillis(); // Build a default rollback object (no actions performed) - NetworkRollback networkRollback = new NetworkRollback (); - networkRollback.setCloudId (cloudSiteId); - networkRollback.setTenantId (tenantId); - networkRollback.setMsoRequest (msoRequest); + NetworkRollback networkRollback = new NetworkRollback(); + networkRollback.setCloudId(cloudSiteId); + networkRollback.setTenantId(tenantId); + networkRollback.setMsoRequest(msoRequest); networkRollback.setModelCustomizationUuid(modelCustomizationUuid); // tenant query is not required here. @@ -283,10 +201,9 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { // So this is just catching that error in a bit more obvious way up front. Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId); - if (!cloudSiteOpt.isPresent()) - { - String error = String - .format("Configuration Error. Stack %s in %s/%s: CloudSite does not exist in MSO Configuration", + if (!cloudSiteOpt.isPresent()) { + String error = String.format( + "Configuration Error. Stack %s in %s/%s: CloudSite does not exist in MSO Configuration", networkName, cloudSiteId, tenantId); logger.error("{} {} {}", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error); // Set the detailed error as the Exception 'message' @@ -294,443 +211,332 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { } - NetworkResource networkResource = networkCheck (startTime, - networkType, - modelCustomizationUuid, - networkName, - physicalNetworkName, - vlans, - routeTargets, - cloudSiteId, - cloudSiteOpt.get()); - String mode = networkResource.getOrchestrationMode (); - NetworkType neutronNetworkType = NetworkType.valueOf (networkResource.getNeutronNetworkType ()); + NetworkResource networkResource = networkCheck(startTime, networkType, modelCustomizationUuid, networkName, + physicalNetworkName, vlans, routeTargets, cloudSiteId, cloudSiteOpt.get()); + String mode = networkResource.getOrchestrationMode(); + NetworkType neutronNetworkType = NetworkType.valueOf(networkResource.getNeutronNetworkType()); - if (NEUTRON_MODE.equals (mode)) { + if (NEUTRON_MODE.equals(mode)) { - // Use an MsoNeutronUtils for all neutron commands + // Use an MsoNeutronUtils for all neutron commands - // See if the Network already exists (by name) - NetworkInfo netInfo = null; - long queryNetworkStarttime = System.currentTimeMillis (); - try { - netInfo = neutron.queryNetwork (networkName, tenantId, cloudSiteId); - } catch (MsoException me) { - logger.error( + // See if the Network already exists (by name) + NetworkInfo netInfo = null; + long queryNetworkStarttime = System.currentTimeMillis(); + try { + netInfo = neutron.queryNetwork(networkName, tenantId, cloudSiteId); + } catch (MsoException me) { + logger.error( "{} {} Exception while querying network {} for CloudSite {} from Tenant {} from OpenStack ", - MessageEnum.RA_QUERY_NETWORK_EXC, ErrorCode.BusinessProcesssError.getValue(), - networkName, cloudSiteId, tenantId, me); - me.addContext (CREATE_NETWORK_CONTEXT); - throw new NetworkException (me); - } + MessageEnum.RA_QUERY_NETWORK_EXC, ErrorCode.BusinessProcesssError.getValue(), networkName, + cloudSiteId, tenantId, me); + me.addContext(CREATE_NETWORK_CONTEXT); + throw new NetworkException(me); + } - if (netInfo != null) { - // Exists. If that's OK, return success with the network ID. - // Otherwise, return an exception. - if (failIfExists != null && failIfExists) { - String error = String - .format("Create Nework: Network %s already exists in %s/%s with ID %s", networkName, - cloudSiteId, tenantId, netInfo.getId()); - logger.error("{} {} {}", MessageEnum.RA_NETWORK_ALREADY_EXIST, - ErrorCode.DataError.getValue(), error); - throw new NetworkException(error, MsoExceptionCategory.USERDATA); - } else { - // Populate the outputs from the existing network. - networkId.value = netInfo.getId (); - neutronNetworkId.value = netInfo.getId (); - rollback.value = networkRollback; // Default rollback - no updates performed - logger.warn("{} {} Found Existing network, status={} for Neutron mode ", - MessageEnum.RA_NETWORK_ALREADY_EXIST, ErrorCode.DataError.getValue(), - netInfo.getStatus()); - } - return; + if (netInfo != null) { + // Exists. If that's OK, return success with the network ID. + // Otherwise, return an exception. + if (failIfExists != null && failIfExists) { + String error = String.format("Create Nework: Network %s already exists in %s/%s with ID %s", + networkName, cloudSiteId, tenantId, netInfo.getId()); + logger.error("{} {} {}", MessageEnum.RA_NETWORK_ALREADY_EXIST, ErrorCode.DataError.getValue(), + error); + throw new NetworkException(error, MsoExceptionCategory.USERDATA); + } else { + // Populate the outputs from the existing network. + networkId.value = netInfo.getId(); + neutronNetworkId.value = netInfo.getId(); + rollback.value = networkRollback; // Default rollback - no updates performed + logger.warn("{} {} Found Existing network, status={} for Neutron mode ", + MessageEnum.RA_NETWORK_ALREADY_EXIST, ErrorCode.DataError.getValue(), netInfo.getStatus()); } + return; + } - long createNetworkStarttime = System.currentTimeMillis (); - try { - netInfo = neutron.createNetwork (cloudSiteId, - tenantId, - neutronNetworkType, - networkName, - physicalNetworkName, - vlans); - } catch (MsoException me) { - me.addContext(CREATE_NETWORK_CONTEXT); - logger.error("{} {} Create Network: type {} in {}/{}: ", MessageEnum.RA_CREATE_NETWORK_EXC, + long createNetworkStarttime = System.currentTimeMillis(); + try { + netInfo = neutron.createNetwork(cloudSiteId, tenantId, neutronNetworkType, networkName, + physicalNetworkName, vlans); + } catch (MsoException me) { + me.addContext(CREATE_NETWORK_CONTEXT); + logger.error("{} {} Create Network: type {} in {}/{}: ", MessageEnum.RA_CREATE_NETWORK_EXC, ErrorCode.DataError.getValue(), neutronNetworkType, cloudSiteId, tenantId, me); - throw new NetworkException (me); - } + throw new NetworkException(me); + } - // Note: ignoring MsoNetworkAlreadyExists because we already checked. + // Note: ignoring MsoNetworkAlreadyExists because we already checked. - // If reach this point, network creation is successful. - // Since directly created via Neutron, networkId tracked by MSO is the same - // as the neutron network ID. - networkId.value = netInfo.getId (); - neutronNetworkId.value = netInfo.getId (); + // If reach this point, network creation is successful. + // Since directly created via Neutron, networkId tracked by MSO is the same + // as the neutron network ID. + networkId.value = netInfo.getId(); + neutronNetworkId.value = netInfo.getId(); - networkRollback.setNetworkCreated (true); - networkRollback.setNetworkId (netInfo.getId ()); - networkRollback.setNeutronNetworkId (netInfo.getId ()); - networkRollback.setNetworkType (networkType); + networkRollback.setNetworkCreated(true); + networkRollback.setNetworkId(netInfo.getId()); + networkRollback.setNeutronNetworkId(netInfo.getId()); + networkRollback.setNetworkType(networkType); - logger.debug("Network {} created, id = {}", networkName, netInfo.getId()); - } else if ("HEAT".equals (mode)) { + logger.debug("Network {} created, id = {}", networkName, netInfo.getId()); + } else if ("HEAT".equals(mode)) { - HeatTemplate heatTemplate = networkResource.getHeatTemplate(); - if (heatTemplate == null) { - String error = String - .format("Network error - undefined Heat Template. Network Type = %s", networkType); - logger.error("{} {} {}", MessageEnum.RA_PARAM_NOT_FOUND, ErrorCode.DataError.getValue(), - error); - throw new NetworkException (error, MsoExceptionCategory.INTERNAL); - } + HeatTemplate heatTemplate = networkResource.getHeatTemplate(); + if (heatTemplate == null) { + String error = String.format("Network error - undefined Heat Template. Network Type = %s", networkType); + logger.error("{} {} {}", MessageEnum.RA_PARAM_NOT_FOUND, ErrorCode.DataError.getValue(), error); + throw new NetworkException(error, MsoExceptionCategory.INTERNAL); + } - logger.debug("Got HEAT Template from DB: {}", heatTemplate.toString()); + logger.debug("Got HEAT Template from DB: {}", heatTemplate.toString()); - // "Fix" the template if it has CR/LF (getting this from Oracle) - String template = heatTemplate.getHeatTemplate (); - template = template.replaceAll ("\r\n", "\n"); + // "Fix" the template if it has CR/LF (getting this from Oracle) + String template = heatTemplate.getHeatTemplate(); + template = template.replaceAll("\r\n", "\n"); - boolean aic3template=false; - String aic3nw = AIC3_NW; + boolean aic3template = false; + String aic3nw = AIC3_NW; - aic3nw = environment.getProperty(AIC3_NW_PROPERTY, AIC3_NW); + aic3nw = environment.getProperty(AIC3_NW_PROPERTY, AIC3_NW); - if (template.contains(aic3nw)) - aic3template = true; + if (template.contains(aic3nw)) + aic3template = true; - // First, look up to see if the Network already exists (by name). - // For HEAT orchestration of networks, the stack name will always match the network name - StackInfo heatStack = null; - long queryNetworkStarttime = System.currentTimeMillis (); - try { - heatStack = heat.queryStack (cloudSiteId, "CloudOwner", tenantId, networkName); - } catch (MsoException me) { - me.addContext (CREATE_NETWORK_CONTEXT); - logger.error("{} {} Create Network (heat): query network {} in {}/{}: ", - MessageEnum.RA_QUERY_NETWORK_EXC, ErrorCode.DataError.getValue(), networkName, - cloudSiteId, tenantId, me); - throw new NetworkException (me); - } + // First, look up to see if the Network already exists (by name). + // For HEAT orchestration of networks, the stack name will always match the network name + StackInfo heatStack = null; + long queryNetworkStarttime = System.currentTimeMillis(); + try { + heatStack = heat.queryStack(cloudSiteId, "CloudOwner", tenantId, networkName); + } catch (MsoException me) { + me.addContext(CREATE_NETWORK_CONTEXT); + logger.error("{} {} Create Network (heat): query network {} in {}/{}: ", + MessageEnum.RA_QUERY_NETWORK_EXC, ErrorCode.DataError.getValue(), networkName, cloudSiteId, + tenantId, me); + throw new NetworkException(me); + } - if (heatStack != null && (heatStack.getStatus () != HeatStatus.NOTFOUND)) { - // Stack exists. Return success or error depending on input directive - if (failIfExists != null && failIfExists) { - String error = String - .format("CreateNetwork: Stack %s already exists in %s/%s as %s", networkName, cloudSiteId, - tenantId, heatStack.getCanonicalName()); - logger.error("{} {} {}", MessageEnum.RA_NETWORK_ALREADY_EXIST, - ErrorCode.DataError.getValue(), error); - throw new NetworkException(error, MsoExceptionCategory.USERDATA); - } else { - // Populate the outputs from the existing stack. - networkId.value = heatStack.getCanonicalName (); - neutronNetworkId.value = (String) heatStack.getOutputs ().get (NETWORK_ID); - rollback.value = networkRollback; // Default rollback - no updates performed - if (aic3template) - { - networkFqdn.value = (String) heatStack.getOutputs().get(NETWORK_FQDN); - } - Map <String, Object> outputs = heatStack.getOutputs (); - Map <String, String> sMap = new HashMap <> (); - if (outputs != null) { - for (Map.Entry<String, Object> entry : outputs.entrySet()) { - String key=entry.getKey(); - if (key != null && key.startsWith ("subnet")) { - if (aic3template) //one subnet_id output - { - Map <String, String> map = getSubnetUUId(key, outputs, subnets); - sMap.putAll(map); - } - else //multiples subnet_%aaid% outputs - { - String subnetUUId = (String) outputs.get(key); - sMap.put (key.substring("subnet_id_".length()), subnetUUId); - } - } - } + if (heatStack != null && (heatStack.getStatus() != HeatStatus.NOTFOUND)) { + // Stack exists. Return success or error depending on input directive + if (failIfExists != null && failIfExists) { + String error = String.format("CreateNetwork: Stack %s already exists in %s/%s as %s", networkName, + cloudSiteId, tenantId, heatStack.getCanonicalName()); + logger.error("{} {} {}", MessageEnum.RA_NETWORK_ALREADY_EXIST, ErrorCode.DataError.getValue(), + error); + throw new NetworkException(error, MsoExceptionCategory.USERDATA); + } else { + // Populate the outputs from the existing stack. + networkId.value = heatStack.getCanonicalName(); + neutronNetworkId.value = (String) heatStack.getOutputs().get(NETWORK_ID); + rollback.value = networkRollback; // Default rollback - no updates performed + if (aic3template) { + networkFqdn.value = (String) heatStack.getOutputs().get(NETWORK_FQDN); + } + Map<String, Object> outputs = heatStack.getOutputs(); + Map<String, String> sMap = new HashMap<>(); + if (outputs != null) { + for (Map.Entry<String, Object> entry : outputs.entrySet()) { + String key = entry.getKey(); + if (key != null && key.startsWith("subnet")) { + if (aic3template) // one subnet_id output + { + Map<String, String> map = getSubnetUUId(key, outputs, subnets); + sMap.putAll(map); + } else // multiples subnet_%aaid% outputs + { + String subnetUUId = (String) outputs.get(key); + sMap.put(key.substring("subnet_id_".length()), subnetUUId); + } + } } - subnetIdMap.value = sMap; - logger.warn("{} {} Found Existing network stack, status={} networkName={} for {}/{}", - MessageEnum.RA_NETWORK_ALREADY_EXIST, ErrorCode.DataError.getValue(), - heatStack.getStatus(), networkName, cloudSiteId, tenantId); } - return; - } - - // Ready to deploy the new Network - // Build the common set of HEAT template parameters - Map <String, Object> stackParams = populateNetworkParams (neutronNetworkType, - networkName, - physicalNetworkName, - vlans, - routeTargets, - shared, - external, - aic3template); - - // Validate (and update) the input parameters against the DB definition - // Shouldn't happen unless DB config is wrong, since all networks use same inputs - // and inputs were already validated. - try { - stackParams = heat.validateStackParams (stackParams, heatTemplate); - } catch (IllegalArgumentException e) { - String error = "Create Network: Configuration Error: " + e.getMessage (); - logger.error("{} {} {} ", MessageEnum.RA_CONFIG_EXC, - ErrorCode.DataError.getValue(), error,e); - // Input parameters were not valid - throw new NetworkException (error, MsoExceptionCategory.INTERNAL); + subnetIdMap.value = sMap; + logger.warn("{} {} Found Existing network stack, status={} networkName={} for {}/{}", + MessageEnum.RA_NETWORK_ALREADY_EXIST, ErrorCode.DataError.getValue(), heatStack.getStatus(), + networkName, cloudSiteId, tenantId); } + return; + } - if (subnets != null) { - try { - if (aic3template) - { - template = mergeSubnetsAIC3 (template, subnets, stackParams); - } - else - { - template = mergeSubnets (template, subnets); - } - } catch (MsoException me) { - me.addContext (CREATE_NETWORK_CONTEXT); - logger - .error("{} {} Exception Create Network, merging subnets for network (heat) type {} in {}/{} ", - MessageEnum.RA_CREATE_NETWORK_EXC, ErrorCode.DataError.getValue(), - neutronNetworkType.toString(), cloudSiteId, tenantId, me); - throw new NetworkException (me); - } - } + // Ready to deploy the new Network + // Build the common set of HEAT template parameters + Map<String, Object> stackParams = populateNetworkParams(neutronNetworkType, networkName, + physicalNetworkName, vlans, routeTargets, shared, external, aic3template); + + // Validate (and update) the input parameters against the DB definition + // Shouldn't happen unless DB config is wrong, since all networks use same inputs + // and inputs were already validated. + try { + stackParams = heat.validateStackParams(stackParams, heatTemplate); + } catch (IllegalArgumentException e) { + String error = "Create Network: Configuration Error: " + e.getMessage(); + logger.error("{} {} {} ", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error, e); + // Input parameters were not valid + throw new NetworkException(error, MsoExceptionCategory.INTERNAL); + } - if (policyFqdns != null && !policyFqdns.isEmpty() && aic3template) { - try { - mergePolicyRefs (policyFqdns, stackParams); - } catch (MsoException me) { - me.addContext (CREATE_NETWORK_CONTEXT); - logger.error("{} {} Exception Create Network, merging policyRefs type {} in {}/{} ", + if (subnets != null) { + try { + if (aic3template) { + template = mergeSubnetsAIC3(template, subnets, stackParams); + } else { + template = mergeSubnets(template, subnets); + } + } catch (MsoException me) { + me.addContext(CREATE_NETWORK_CONTEXT); + logger.error("{} {} Exception Create Network, merging subnets for network (heat) type {} in {}/{} ", MessageEnum.RA_CREATE_NETWORK_EXC, ErrorCode.DataError.getValue(), neutronNetworkType.toString(), cloudSiteId, tenantId, me); - throw new NetworkException (me); - } + throw new NetworkException(me); } + } - if (routeTableFqdns != null && !routeTableFqdns.isEmpty() && aic3template) { - try { - mergeRouteTableRefs (routeTableFqdns, stackParams); - } catch (MsoException me) { - me.addContext (CREATE_NETWORK_CONTEXT); - logger.error("{} {} Exception Create Network, merging routeTableRefs type {} in {}/{} ", + if (policyFqdns != null && !policyFqdns.isEmpty() && aic3template) { + try { + mergePolicyRefs(policyFqdns, stackParams); + } catch (MsoException me) { + me.addContext(CREATE_NETWORK_CONTEXT); + logger.error("{} {} Exception Create Network, merging policyRefs type {} in {}/{} ", MessageEnum.RA_CREATE_NETWORK_EXC, ErrorCode.DataError.getValue(), neutronNetworkType.toString(), cloudSiteId, tenantId, me); - throw new NetworkException (me); - } + throw new NetworkException(me); } + } - // Deploy the network stack - // Ignore MsoStackAlreadyExists exception because we already checked. + if (routeTableFqdns != null && !routeTableFqdns.isEmpty() && aic3template) { try { - if (backout == null) - backout = true; - heatStack = heat.createStack (cloudSiteId, - "CloudOwner", - tenantId, - networkName, - null, - template, - stackParams, - true, - heatTemplate.getTimeoutMinutes (), - null, - null, - null, - backout.booleanValue()); + mergeRouteTableRefs(routeTableFqdns, stackParams); } catch (MsoException me) { - me.addContext (CREATE_NETWORK_CONTEXT); - logger - .error("{} {} Exception creating network type {} in {}/{} ", MessageEnum.RA_CREATE_NETWORK_EXC, - ErrorCode.DataError.getValue(), networkName, cloudSiteId, tenantId, me); - throw new NetworkException (me); + me.addContext(CREATE_NETWORK_CONTEXT); + logger.error("{} {} Exception Create Network, merging routeTableRefs type {} in {}/{} ", + MessageEnum.RA_CREATE_NETWORK_EXC, ErrorCode.DataError.getValue(), + neutronNetworkType.toString(), cloudSiteId, tenantId, me); + throw new NetworkException(me); } + } - // Reach this point if createStack is successful. + // Deploy the network stack + // Ignore MsoStackAlreadyExists exception because we already checked. + try { + if (backout == null) + backout = true; + heatStack = heat.createStack(cloudSiteId, "CloudOwner", tenantId, networkName, null, template, + stackParams, true, heatTemplate.getTimeoutMinutes(), null, null, null, backout.booleanValue()); + } catch (MsoException me) { + me.addContext(CREATE_NETWORK_CONTEXT); + logger.error("{} {} Exception creating network type {} in {}/{} ", MessageEnum.RA_CREATE_NETWORK_EXC, + ErrorCode.DataError.getValue(), networkName, cloudSiteId, tenantId, me); + throw new NetworkException(me); + } - // For Heat-based orchestration, the MSO-tracked network ID is the heat stack, - // and the neutronNetworkId is the network UUID returned in stack outputs. - networkId.value = heatStack.getCanonicalName (); - neutronNetworkId.value = (String) heatStack.getOutputs ().get (NETWORK_ID); - if (aic3template) - { - networkFqdn.value = (String) heatStack.getOutputs().get(NETWORK_FQDN); - } - Map <String, Object> outputs = heatStack.getOutputs (); - Map <String, String> sMap = new HashMap <> (); - if (outputs != null) { - for (Map.Entry<String, Object> entry : outputs.entrySet()) { - String key = entry.getKey(); - if (key != null && key.startsWith ("subnet")) { - if (aic3template) //one subnet output expected - { - Map <String, String> map = getSubnetUUId(key, outputs, subnets); - sMap.putAll(map); - } - else //multiples subnet_%aaid% outputs allowed - { - String subnetUUId = (String) outputs.get(key); - sMap.put (key.substring("subnet_id_".length()), subnetUUId); - } + // Reach this point if createStack is successful. + + // For Heat-based orchestration, the MSO-tracked network ID is the heat stack, + // and the neutronNetworkId is the network UUID returned in stack outputs. + networkId.value = heatStack.getCanonicalName(); + neutronNetworkId.value = (String) heatStack.getOutputs().get(NETWORK_ID); + if (aic3template) { + networkFqdn.value = (String) heatStack.getOutputs().get(NETWORK_FQDN); + } + Map<String, Object> outputs = heatStack.getOutputs(); + Map<String, String> sMap = new HashMap<>(); + if (outputs != null) { + for (Map.Entry<String, Object> entry : outputs.entrySet()) { + String key = entry.getKey(); + if (key != null && key.startsWith("subnet")) { + if (aic3template) // one subnet output expected + { + Map<String, String> map = getSubnetUUId(key, outputs, subnets); + sMap.putAll(map); + } else // multiples subnet_%aaid% outputs allowed + { + String subnetUUId = (String) outputs.get(key); + sMap.put(key.substring("subnet_id_".length()), subnetUUId); } } } - subnetIdMap.value = sMap; + } + subnetIdMap.value = sMap; - rollback.value = networkRollback; - // Populate remaining rollback info and response parameters. - networkRollback.setNetworkStackId (heatStack.getCanonicalName ()); - networkRollback.setNeutronNetworkId ((String) heatStack.getOutputs ().get (NETWORK_ID)); - networkRollback.setNetworkCreated (true); - networkRollback.setNetworkType (networkType); + rollback.value = networkRollback; + // Populate remaining rollback info and response parameters. + networkRollback.setNetworkStackId(heatStack.getCanonicalName()); + networkRollback.setNeutronNetworkId((String) heatStack.getOutputs().get(NETWORK_ID)); + networkRollback.setNetworkCreated(true); + networkRollback.setNetworkType(networkType); - logger.debug("Network {} successfully created via HEAT", networkName); - } + logger.debug("Network {} successfully created via HEAT", networkName); + } return; } @Override - public void updateNetwork (String cloudSiteId, - String tenantId, - String networkType, - String modelCustomizationUuid, - String networkId, - String networkName, - String physicalNetworkName, - List <Integer> vlans, - String shared, - String external, - List <Subnet> subnets, - Map<String,String> networkParams, - MsoRequest msoRequest, - Holder <Map <String, String>> subnetIdMap, - Holder <NetworkRollback> rollback) throws NetworkException { - updateNetwork (cloudSiteId, - tenantId, - networkType, - modelCustomizationUuid, - networkId, - networkName, - physicalNetworkName, - vlans, - null, - shared, - external, - subnets, - null, - null, - msoRequest, - subnetIdMap, - rollback); + public void updateNetwork(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid, + String networkId, String networkName, String physicalNetworkName, List<Integer> vlans, String shared, + String external, List<Subnet> subnets, Map<String, String> networkParams, MsoRequest msoRequest, + Holder<Map<String, String>> subnetIdMap, Holder<NetworkRollback> rollback) throws NetworkException { + updateNetwork(cloudSiteId, tenantId, networkType, modelCustomizationUuid, networkId, networkName, + physicalNetworkName, vlans, null, shared, external, subnets, null, null, msoRequest, subnetIdMap, + rollback); } @Override - public void updateNetworkContrail (String cloudSiteId, - String tenantId, - String networkType, - String modelCustomizationUuid, - String networkId, - String networkName, - List <RouteTarget> routeTargets, - String shared, - String external, - List <Subnet> subnets, - Map<String, String> networkParams, - List <String> policyFqdns, - List<String> routeTableFqdns, - MsoRequest msoRequest, - Holder <Map <String, String>> subnetIdMap, - Holder <NetworkRollback> rollback) throws NetworkException { - updateNetwork (cloudSiteId, - tenantId, - networkType, - modelCustomizationUuid, - networkId, - networkName, - null, - null, - routeTargets, - shared, - external, - subnets, - policyFqdns, - routeTableFqdns, - msoRequest, - subnetIdMap, - rollback); + public void updateNetworkContrail(String cloudSiteId, String tenantId, String networkType, + String modelCustomizationUuid, String networkId, String networkName, List<RouteTarget> routeTargets, + String shared, String external, List<Subnet> subnets, Map<String, String> networkParams, + List<String> policyFqdns, List<String> routeTableFqdns, MsoRequest msoRequest, + Holder<Map<String, String>> subnetIdMap, Holder<NetworkRollback> rollback) throws NetworkException { + updateNetwork(cloudSiteId, tenantId, networkType, modelCustomizationUuid, networkId, networkName, null, null, + routeTargets, shared, external, subnets, policyFqdns, routeTableFqdns, msoRequest, subnetIdMap, + rollback); } /** - * This is the "Update Network" web service implementation. - * It will update an existing Network of the requested type in the specified cloud - * and tenant. The typical use will be to replace the VLANs with the supplied - * list (to add or remove a VLAN), but other properties may be updated as well. + * This is the "Update Network" web service implementation. It will update an existing Network of the requested type + * in the specified cloud and tenant. The typical use will be to replace the VLANs with the supplied list (to add or + * remove a VLAN), but other properties may be updated as well. * - * There will be a pre-defined set of network types defined in the MSO Catalog. - * All such networks will have a similar configuration, based on the allowable - * Openstack networking definitions. This includes basic networks, provider - * networks (with a single VLAN), and multi-provider networks (one or more VLANs). + * There will be a pre-defined set of network types defined in the MSO Catalog. All such networks will have a + * similar configuration, based on the allowable Openstack networking definitions. This includes basic networks, + * provider networks (with a single VLAN), and multi-provider networks (one or more VLANs). * - * Initially, all provider networks must currently be "vlan" type, and multi-provider - * networks must be multiple VLANs on the same physical network. + * Initially, all provider networks must currently be "vlan" type, and multi-provider networks must be multiple + * VLANs on the same physical network. * - * This service supports two modes of Network update: - * - via Heat Templates - * - via Neutron API - * The network orchestration mode for each network type is declared in its - * catalog definition. All Heat-based templates must support some subset of - * the same input parameters: network_name, physical_network, vlan, segments. + * This service supports two modes of Network update: - via Heat Templates - via Neutron API The network + * orchestration mode for each network type is declared in its catalog definition. All Heat-based templates must + * support some subset of the same input parameters: network_name, physical_network, vlan, segments. * - * The method returns a NetworkRollback object. This object can be passed - * as-is to the rollbackNetwork operation to undo everything that was updated. - * This is useful if a network is successfully updated but orchestration - * fails on a subsequent operation. + * The method returns a NetworkRollback object. This object can be passed as-is to the rollbackNetwork operation to + * undo everything that was updated. This is useful if a network is successfully updated but orchestration fails on + * a subsequent operation. */ - private void updateNetwork (String cloudSiteId, - String tenantId, - String networkType, - String modelCustomizationUuid, - String networkId, - String networkName, - String physicalNetworkName, - List <Integer> vlans, - List <RouteTarget> routeTargets, - String shared, - String external, - List <Subnet> subnets, - List <String> policyFqdns, - List<String> routeTableFqdns, - MsoRequest msoRequest, - Holder <Map <String, String>> subnetIdMap, - Holder <NetworkRollback> rollback) throws NetworkException { + private void updateNetwork(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid, + String networkId, String networkName, String physicalNetworkName, List<Integer> vlans, + List<RouteTarget> routeTargets, String shared, String external, List<Subnet> subnets, + List<String> policyFqdns, List<String> routeTableFqdns, MsoRequest msoRequest, + Holder<Map<String, String>> subnetIdMap, Holder<NetworkRollback> rollback) throws NetworkException { logger.debug("***UPDATE Network adapter with Network: {} of type {} in {}/{}", networkName, networkType, - cloudSiteId, tenantId); + cloudSiteId, tenantId); // Will capture execution time for metrics - long startTime = System.currentTimeMillis (); + long startTime = System.currentTimeMillis(); // Build a default rollback object (no actions performed) - NetworkRollback networkRollback = new NetworkRollback (); - networkRollback.setCloudId (cloudSiteId); - networkRollback.setTenantId (tenantId); - networkRollback.setMsoRequest (msoRequest); + NetworkRollback networkRollback = new NetworkRollback(); + networkRollback.setCloudId(cloudSiteId); + networkRollback.setTenantId(tenantId); + networkRollback.setMsoRequest(msoRequest); - Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite (cloudSiteId); + Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId); if (!cloudSiteOpt.isPresent()) { String error = String.format( - "UpdateNetwork: Configuration Error. Stack %s in %s/%s: CloudSite does not exist in MSO Configuration", - networkName, cloudSiteId, tenantId); + "UpdateNetwork: Configuration Error. Stack %s in %s/%s: CloudSite does not exist in MSO Configuration", + networkName, cloudSiteId, tenantId); logger.error("{} {} {}", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error); // Set the detailed error as the Exception 'message' throw new NetworkException(error, MsoExceptionCategory.USERDATA); @@ -738,441 +544,364 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { + NetworkResource networkResource = networkCheck(startTime, networkType, modelCustomizationUuid, networkName, + physicalNetworkName, vlans, routeTargets, cloudSiteId, cloudSiteOpt.get()); + String mode = networkResource.getOrchestrationMode(); + NetworkType neutronNetworkType = NetworkType.valueOf(networkResource.getNeutronNetworkType()); - NetworkResource networkResource = networkCheck( - startTime, - networkType, - modelCustomizationUuid, - networkName, - physicalNetworkName, - vlans, - routeTargets, - cloudSiteId, - cloudSiteOpt.get()); - String mode = networkResource.getOrchestrationMode(); - NetworkType neutronNetworkType = NetworkType.valueOf(networkResource.getNeutronNetworkType()); - - // Use an MsoNeutronUtils for all Neutron commands + // Use an MsoNeutronUtils for all Neutron commands - if (NEUTRON_MODE.equals(mode)) { + if (NEUTRON_MODE.equals(mode)) { - // Verify that the Network exists - // For Neutron-based orchestration, the networkId is the Neutron Network UUID. - NetworkInfo netInfo = null; - long queryNetworkStarttime = System.currentTimeMillis(); - try { - netInfo = neutron.queryNetwork(networkId, tenantId, cloudSiteId); - } catch (MsoException me) { - me.addContext(UPDATE_NETWORK_CONTEXT); - logger.error("{} {} Exception - queryNetwork query {} in {}/{} ", MessageEnum.RA_QUERY_NETWORK_EXC, + // Verify that the Network exists + // For Neutron-based orchestration, the networkId is the Neutron Network UUID. + NetworkInfo netInfo = null; + long queryNetworkStarttime = System.currentTimeMillis(); + try { + netInfo = neutron.queryNetwork(networkId, tenantId, cloudSiteId); + } catch (MsoException me) { + me.addContext(UPDATE_NETWORK_CONTEXT); + logger.error("{} {} Exception - queryNetwork query {} in {}/{} ", MessageEnum.RA_QUERY_NETWORK_EXC, ErrorCode.BusinessProcesssError.getValue(), networkId, cloudSiteId, tenantId, me); - throw new NetworkException(me); - } + throw new NetworkException(me); + } - if (netInfo == null) { - String error = String - .format("Update Nework: Network %s does not exist in %s/%s", networkId, cloudSiteId, tenantId); - logger.error("{} {} {}", MessageEnum.RA_NETWORK_NOT_FOUND, - ErrorCode.BusinessProcesssError.getValue(), error); - // Does not exist. Throw an exception (can't update a non-existent network) - throw new NetworkException(error, MsoExceptionCategory.USERDATA); - } - long updateNetworkStarttime = System.currentTimeMillis(); - try { - netInfo = neutron.updateNetwork(cloudSiteId, - tenantId, - networkId, - neutronNetworkType, - physicalNetworkName, - vlans); - } catch (MsoException me) { - me.addContext(UPDATE_NETWORK_CONTEXT); - logger.error("{} {} Exception - updateNetwork {} in {}/{} ", MessageEnum.RA_UPDATE_NETWORK_ERR, + if (netInfo == null) { + String error = String.format("Update Nework: Network %s does not exist in %s/%s", networkId, + cloudSiteId, tenantId); + logger.error("{} {} {}", MessageEnum.RA_NETWORK_NOT_FOUND, ErrorCode.BusinessProcesssError.getValue(), + error); + // Does not exist. Throw an exception (can't update a non-existent network) + throw new NetworkException(error, MsoExceptionCategory.USERDATA); + } + long updateNetworkStarttime = System.currentTimeMillis(); + try { + netInfo = neutron.updateNetwork(cloudSiteId, tenantId, networkId, neutronNetworkType, + physicalNetworkName, vlans); + } catch (MsoException me) { + me.addContext(UPDATE_NETWORK_CONTEXT); + logger.error("{} {} Exception - updateNetwork {} in {}/{} ", MessageEnum.RA_UPDATE_NETWORK_ERR, ErrorCode.DataError.getValue(), networkId, cloudSiteId, tenantId, me); - throw new NetworkException(me); - } - - // Add the network ID and previously queried vlans to the rollback object - networkRollback.setNetworkId(netInfo.getId()); - networkRollback.setNeutronNetworkId(netInfo.getId()); - networkRollback.setNetworkType(networkType); - // Save previous parameters - networkRollback.setNetworkName(netInfo.getName()); - networkRollback.setPhysicalNetwork(netInfo.getProvider()); - networkRollback.setVlans(netInfo.getVlans()); - - logger.debug("Network {} updated, id = {}", networkId, netInfo.getId()); - } else if ("HEAT".equals(mode)) { + throw new NetworkException(me); + } - // First, look up to see that the Network already exists. - // For Heat-based orchestration, the networkId is the network Stack ID. - StackInfo heatStack = null; - long queryStackStarttime = System.currentTimeMillis(); - try { - heatStack = heat.queryStack(cloudSiteId, "CloudOwner", tenantId, networkName); - } catch (MsoException me) { - me.addContext(UPDATE_NETWORK_CONTEXT); - logger.error("{} {} Exception - QueryStack query {} in {}/{} ", MessageEnum.RA_QUERY_NETWORK_EXC, + // Add the network ID and previously queried vlans to the rollback object + networkRollback.setNetworkId(netInfo.getId()); + networkRollback.setNeutronNetworkId(netInfo.getId()); + networkRollback.setNetworkType(networkType); + // Save previous parameters + networkRollback.setNetworkName(netInfo.getName()); + networkRollback.setPhysicalNetwork(netInfo.getProvider()); + networkRollback.setVlans(netInfo.getVlans()); + + logger.debug("Network {} updated, id = {}", networkId, netInfo.getId()); + } else if ("HEAT".equals(mode)) { + + // First, look up to see that the Network already exists. + // For Heat-based orchestration, the networkId is the network Stack ID. + StackInfo heatStack = null; + long queryStackStarttime = System.currentTimeMillis(); + try { + heatStack = heat.queryStack(cloudSiteId, "CloudOwner", tenantId, networkName); + } catch (MsoException me) { + me.addContext(UPDATE_NETWORK_CONTEXT); + logger.error("{} {} Exception - QueryStack query {} in {}/{} ", MessageEnum.RA_QUERY_NETWORK_EXC, ErrorCode.DataError.getValue(), networkId, cloudSiteId, tenantId, me); - throw new NetworkException(me); - } + throw new NetworkException(me); + } - if (heatStack == null || (heatStack.getStatus() == HeatStatus.NOTFOUND)) { - String error = String - .format("UpdateNetwork: Stack %s does not exist in %s/%s", networkName, cloudSiteId, tenantId); - logger.error("{} {} {}", MessageEnum.RA_NETWORK_NOT_FOUND, ErrorCode.DataError.getValue(), - error); - // Network stack does not exist. Return an error - throw new NetworkException(error, MsoExceptionCategory.USERDATA); - } + if (heatStack == null || (heatStack.getStatus() == HeatStatus.NOTFOUND)) { + String error = String.format("UpdateNetwork: Stack %s does not exist in %s/%s", networkName, + cloudSiteId, tenantId); + logger.error("{} {} {}", MessageEnum.RA_NETWORK_NOT_FOUND, ErrorCode.DataError.getValue(), error); + // Network stack does not exist. Return an error + throw new NetworkException(error, MsoExceptionCategory.USERDATA); + } - // Get the previous parameters for rollback - Map<String, Object> heatParams = heatStack.getParameters(); + // Get the previous parameters for rollback + Map<String, Object> heatParams = heatStack.getParameters(); - String previousNetworkName = (String) heatParams.get("network_name"); - String previousPhysicalNetwork = (String) heatParams.get(PHYSICAL_NETWORK); + String previousNetworkName = (String) heatParams.get("network_name"); + String previousPhysicalNetwork = (String) heatParams.get(PHYSICAL_NETWORK); - List<Integer> previousVlans = new ArrayList<>(); - String vlansParam = (String) heatParams.get(VLANS); - if (vlansParam != null) { - for (String vlan : vlansParam.split(",")) { - try { - previousVlans.add(Integer.parseInt(vlan)); - } catch (NumberFormatException e) { - logger.warn("{} {} Exception - VLAN parse for params {} ", MessageEnum.RA_VLAN_PARSE, + List<Integer> previousVlans = new ArrayList<>(); + String vlansParam = (String) heatParams.get(VLANS); + if (vlansParam != null) { + for (String vlan : vlansParam.split(",")) { + try { + previousVlans.add(Integer.parseInt(vlan)); + } catch (NumberFormatException e) { + logger.warn("{} {} Exception - VLAN parse for params {} ", MessageEnum.RA_VLAN_PARSE, ErrorCode.DataError.getValue(), vlansParam, e); - } } } - logger.debug("Update Stack: Previous VLANS: {}", previousVlans); + } + logger.debug("Update Stack: Previous VLANS: {}", previousVlans); - // Ready to deploy the updated Network via Heat + // Ready to deploy the updated Network via Heat - HeatTemplate heatTemplate = networkResource.getHeatTemplate(); - if (heatTemplate == null) { - String error = "Network error - undefined Heat Template. Network Type=" + networkType; - logger.error("{} {} {}", MessageEnum.RA_PARAM_NOT_FOUND, ErrorCode.DataError.getValue(), - error); - throw new NetworkException(error, MsoExceptionCategory.INTERNAL); - } + HeatTemplate heatTemplate = networkResource.getHeatTemplate(); + if (heatTemplate == null) { + String error = "Network error - undefined Heat Template. Network Type=" + networkType; + logger.error("{} {} {}", MessageEnum.RA_PARAM_NOT_FOUND, ErrorCode.DataError.getValue(), error); + throw new NetworkException(error, MsoExceptionCategory.INTERNAL); + } - logger.debug("Got HEAT Template from DB: {}", heatTemplate.toString()); + logger.debug("Got HEAT Template from DB: {}", heatTemplate.toString()); - // "Fix" the template if it has CR/LF (getting this from Oracle) - String template = heatTemplate.getHeatTemplate(); - template = template.replaceAll("\r\n", "\n"); + // "Fix" the template if it has CR/LF (getting this from Oracle) + String template = heatTemplate.getHeatTemplate(); + template = template.replaceAll("\r\n", "\n"); - boolean aic3template = false; - String aic3nw = AIC3_NW; + boolean aic3template = false; + String aic3nw = AIC3_NW; - aic3nw = environment.getProperty(AIC3_NW_PROPERTY, AIC3_NW); + aic3nw = environment.getProperty(AIC3_NW_PROPERTY, AIC3_NW); - if (template.contains(aic3nw)) - aic3template = true; + if (template.contains(aic3nw)) + aic3template = true; - // Build the common set of HEAT template parameters - Map<String, Object> stackParams = populateNetworkParams(neutronNetworkType, - networkName, - physicalNetworkName, - vlans, - routeTargets, - shared, - external, - aic3template); + // Build the common set of HEAT template parameters + Map<String, Object> stackParams = populateNetworkParams(neutronNetworkType, networkName, + physicalNetworkName, vlans, routeTargets, shared, external, aic3template); - // Validate (and update) the input parameters against the DB definition - // Shouldn't happen unless DB config is wrong, since all networks use same inputs - try { - stackParams = heat.validateStackParams(stackParams, heatTemplate); - } catch (IllegalArgumentException e) { - String error = "UpdateNetwork: Configuration Error: Network Type=" + networkType; - logger.error("{} {} {} ", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error); - throw new NetworkException(error, MsoExceptionCategory.INTERNAL, e); - } + // Validate (and update) the input parameters against the DB definition + // Shouldn't happen unless DB config is wrong, since all networks use same inputs + try { + stackParams = heat.validateStackParams(stackParams, heatTemplate); + } catch (IllegalArgumentException e) { + String error = "UpdateNetwork: Configuration Error: Network Type=" + networkType; + logger.error("{} {} {} ", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error); + throw new NetworkException(error, MsoExceptionCategory.INTERNAL, e); + } - if (subnets != null) { - try { - if (aic3template) { - template = mergeSubnetsAIC3(template, subnets, stackParams); - } else { - template = mergeSubnets(template, subnets); - } - } catch (MsoException me) { - me.addContext(UPDATE_NETWORK_CONTEXT); - logger.error("{} {} Exception - UpdateNetwork mergeSubnets for network type {} in {}/{} ", - MessageEnum.RA_UPDATE_NETWORK_ERR, ErrorCode.DataError.getValue(), - neutronNetworkType.toString(), cloudSiteId, tenantId, me); - throw new NetworkException(me); + if (subnets != null) { + try { + if (aic3template) { + template = mergeSubnetsAIC3(template, subnets, stackParams); + } else { + template = mergeSubnets(template, subnets); } - } - - if (policyFqdns != null && aic3template) { - try { - mergePolicyRefs(policyFqdns, stackParams); - } catch (MsoException me) { - me.addContext(UPDATE_NETWORK_CONTEXT); - logger.error("{} {} Exception - UpdateNetwork mergePolicyRefs type {} in {}/{} ", + } catch (MsoException me) { + me.addContext(UPDATE_NETWORK_CONTEXT); + logger.error("{} {} Exception - UpdateNetwork mergeSubnets for network type {} in {}/{} ", MessageEnum.RA_UPDATE_NETWORK_ERR, ErrorCode.DataError.getValue(), neutronNetworkType.toString(), cloudSiteId, tenantId, me); - throw new NetworkException(me); - } + throw new NetworkException(me); } + } - if (routeTableFqdns != null && !routeTableFqdns.isEmpty() && aic3template) { - try { - mergeRouteTableRefs(routeTableFqdns, stackParams); - } catch (MsoException me) { - me.addContext(UPDATE_NETWORK_CONTEXT); - logger.error("{} {} Exception - UpdateNetwork mergeRouteTableRefs type {} in {}/{} ", + if (policyFqdns != null && aic3template) { + try { + mergePolicyRefs(policyFqdns, stackParams); + } catch (MsoException me) { + me.addContext(UPDATE_NETWORK_CONTEXT); + logger.error("{} {} Exception - UpdateNetwork mergePolicyRefs type {} in {}/{} ", MessageEnum.RA_UPDATE_NETWORK_ERR, ErrorCode.DataError.getValue(), neutronNetworkType.toString(), cloudSiteId, tenantId, me); - throw new NetworkException(me); - } + throw new NetworkException(me); } + } - // Update the network stack - // Ignore MsoStackNotFound exception because we already checked. - long updateStackStarttime = System.currentTimeMillis(); + if (routeTableFqdns != null && !routeTableFqdns.isEmpty() && aic3template) { try { - heatStack = heatWithUpdate.updateStack(cloudSiteId, - "CloudOwner", - tenantId, - networkId, - template, - stackParams, - true, - heatTemplate.getTimeoutMinutes()); + mergeRouteTableRefs(routeTableFqdns, stackParams); } catch (MsoException me) { me.addContext(UPDATE_NETWORK_CONTEXT); - logger.error("{} {} Exception - update network {} in {}/{} ", MessageEnum.RA_UPDATE_NETWORK_ERR, - ErrorCode.DataError.getValue(), networkId, cloudSiteId, tenantId, me); + logger.error("{} {} Exception - UpdateNetwork mergeRouteTableRefs type {} in {}/{} ", + MessageEnum.RA_UPDATE_NETWORK_ERR, ErrorCode.DataError.getValue(), + neutronNetworkType.toString(), cloudSiteId, tenantId, me); throw new NetworkException(me); } + } - Map<String, Object> outputs = heatStack.getOutputs(); - Map<String, String> sMap = new HashMap<>(); - if (outputs != null) { - for (Map.Entry<String, Object> entry : outputs.entrySet()) { - String key=entry.getKey(); - if (key != null && key.startsWith("subnet")) { - if (aic3template) //one subnet output expected - { - Map<String, String> map = getSubnetUUId(key, outputs, subnets); - sMap.putAll(map); - } else //multiples subnet_%aaid% outputs allowed - { - String subnetUUId = (String) outputs.get(key); - sMap.put(key.substring("subnet_id_".length()), subnetUUId); - } + // Update the network stack + // Ignore MsoStackNotFound exception because we already checked. + long updateStackStarttime = System.currentTimeMillis(); + try { + heatStack = heatWithUpdate.updateStack(cloudSiteId, "CloudOwner", tenantId, networkId, template, + stackParams, true, heatTemplate.getTimeoutMinutes()); + } catch (MsoException me) { + me.addContext(UPDATE_NETWORK_CONTEXT); + logger.error("{} {} Exception - update network {} in {}/{} ", MessageEnum.RA_UPDATE_NETWORK_ERR, + ErrorCode.DataError.getValue(), networkId, cloudSiteId, tenantId, me); + throw new NetworkException(me); + } + + Map<String, Object> outputs = heatStack.getOutputs(); + Map<String, String> sMap = new HashMap<>(); + if (outputs != null) { + for (Map.Entry<String, Object> entry : outputs.entrySet()) { + String key = entry.getKey(); + if (key != null && key.startsWith("subnet")) { + if (aic3template) // one subnet output expected + { + Map<String, String> map = getSubnetUUId(key, outputs, subnets); + sMap.putAll(map); + } else // multiples subnet_%aaid% outputs allowed + { + String subnetUUId = (String) outputs.get(key); + sMap.put(key.substring("subnet_id_".length()), subnetUUId); } } } - subnetIdMap.value = sMap; + } + subnetIdMap.value = sMap; - // Reach this point if createStack is successful. - // Populate remaining rollback info and response parameters. - networkRollback.setNetworkStackId(heatStack.getCanonicalName()); - if(null != outputs) { - networkRollback.setNeutronNetworkId((String) outputs.get(NETWORK_ID)); - } - else { - logger.debug("outputs is NULL"); - } - networkRollback.setNetworkType(networkType); - // Save previous parameters - networkRollback.setNetworkName(previousNetworkName); - networkRollback.setPhysicalNetwork(previousPhysicalNetwork); - networkRollback.setVlans(previousVlans); + // Reach this point if createStack is successful. + // Populate remaining rollback info and response parameters. + networkRollback.setNetworkStackId(heatStack.getCanonicalName()); + if (null != outputs) { + networkRollback.setNeutronNetworkId((String) outputs.get(NETWORK_ID)); + } else { + logger.debug("outputs is NULL"); + } + networkRollback.setNetworkType(networkType); + // Save previous parameters + networkRollback.setNetworkName(previousNetworkName); + networkRollback.setPhysicalNetwork(previousPhysicalNetwork); + networkRollback.setVlans(previousVlans); - rollback.value = networkRollback; + rollback.value = networkRollback; - logger.debug("Network {} successfully updated via HEAT", networkId); - } + logger.debug("Network {} successfully updated via HEAT", networkId); + } return; } - private NetworkResource networkCheck (long startTime, - String networkType, - String modelCustomizationUuid, - String networkName, - String physicalNetworkName, - List <Integer> vlans, - List <RouteTarget> routeTargets, - String cloudSiteId, - CloudSite cloudSite) throws NetworkException { + private NetworkResource networkCheck(long startTime, String networkType, String modelCustomizationUuid, + String networkName, String physicalNetworkName, List<Integer> vlans, List<RouteTarget> routeTargets, + String cloudSiteId, CloudSite cloudSite) throws NetworkException { // Retrieve the Network Resource definition NetworkResource networkResource = null; NetworkResourceCustomization networkCust = null; CollectionNetworkResourceCustomization collectionNetworkCust = null; - if (commonUtils.isNullOrEmpty(modelCustomizationUuid)) { - if (!commonUtils.isNullOrEmpty(networkType)) { - networkResource = networkResourceRepo.findFirstByModelNameOrderByModelVersionDesc(networkType); - } - } else { - networkCust = networkCustomRepo.findOneByModelCustomizationUUID(modelCustomizationUuid); - if (networkCust == null) { - collectionNetworkCust = collectionNetworkCustomRepo.findOneByModelCustomizationUUID(modelCustomizationUuid); - } - } - if(networkCust != null){ - logger.debug("Got Network Customization definition from Catalog: {}", networkCust.toString()); - - networkResource = networkCust.getNetworkResource(); - } else if (collectionNetworkCust != null) { - logger.debug("Retrieved Collection Network Resource Customization from Catalog: {}", - collectionNetworkCust.toString()); - networkResource = collectionNetworkCust.getNetworkResource(); - } - if (networkResource == null) { - String error = String.format( - "Create/UpdateNetwork: Unable to get network resource with NetworkType: %s or ModelCustomizationUUID:%s", - networkType, modelCustomizationUuid); - logger.error("{} {} {} ", MessageEnum.RA_UNKOWN_PARAM, ErrorCode.DataError.getValue(), error); - - throw new NetworkException(error, MsoExceptionCategory.USERDATA); - } + if (commonUtils.isNullOrEmpty(modelCustomizationUuid)) { + if (!commonUtils.isNullOrEmpty(networkType)) { + networkResource = networkResourceRepo.findFirstByModelNameOrderByModelVersionDesc(networkType); + } + } else { + networkCust = networkCustomRepo.findOneByModelCustomizationUUID(modelCustomizationUuid); + if (networkCust == null) { + collectionNetworkCust = + collectionNetworkCustomRepo.findOneByModelCustomizationUUID(modelCustomizationUuid); + } + } + if (networkCust != null) { + logger.debug("Got Network Customization definition from Catalog: {}", networkCust.toString()); + + networkResource = networkCust.getNetworkResource(); + } else if (collectionNetworkCust != null) { + logger.debug("Retrieved Collection Network Resource Customization from Catalog: {}", + collectionNetworkCust.toString()); + networkResource = collectionNetworkCust.getNetworkResource(); + } + if (networkResource == null) { + String error = String.format( + "Create/UpdateNetwork: Unable to get network resource with NetworkType: %s or ModelCustomizationUUID:%s", + networkType, modelCustomizationUuid); + logger.error("{} {} {} ", MessageEnum.RA_UNKOWN_PARAM, ErrorCode.DataError.getValue(), error); + + throw new NetworkException(error, MsoExceptionCategory.USERDATA); + } logger.debug("Got Network definition from Catalog: {}", networkResource.toString()); - String mode = networkResource.getOrchestrationMode(); - NetworkType neutronNetworkType = NetworkType - .valueOf(networkResource.getNeutronNetworkType()); - - // All Networks are orchestrated via HEAT or Neutron - if (!("HEAT".equals(mode) || NEUTRON_MODE.equals(mode))) { - String error = "CreateNetwork: Configuration Error: Network Type = " + networkType; - logger.error("{} {} {}", MessageEnum.RA_NETWORK_ORCHE_MODE_NOT_SUPPORT, - ErrorCode.DataError.getValue(), error); - throw new NetworkException(error, MsoExceptionCategory.INTERNAL); - } - - MavenLikeVersioning aicV = new MavenLikeVersioning(); - aicV.setVersion(cloudSite.getCloudVersion()); - if ((aicV.isMoreRecentThan(networkResource.getAicVersionMin()) || aicV - .isTheSameVersion(networkResource.getAicVersionMin())) // aic - // >= - // min - && (aicV.isTheSameVersion(networkResource - .getAicVersionMax()) || !(aicV - .isMoreRecentThan(networkResource - .getAicVersionMax())))) // aic <= max - { - logger.debug("Network Type:{} VersionMin:{} VersionMax:{} supported on Cloud:{} with AIC_Version:{}", - networkType, networkResource.getAicVersionMin(), networkResource.getAicVersionMax(), cloudSiteId, - cloudSite.getCloudVersion()); - } else { - String error = String - .format("Network Type:%s Version_Min:%s Version_Max:%s not supported on Cloud:%s with AIC_Version:%s", - networkType, networkType, networkResource.getAicVersionMin(), - networkResource.getAicVersionMax(), cloudSiteId, cloudSite.getCloudVersion()); - logger.error("{} {} {} ", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error); - throw new NetworkException(error, MsoExceptionCategory.USERDATA); - } - - // Validate the Network parameters. - String missing = validateNetworkParams(neutronNetworkType, - networkName, physicalNetworkName, vlans, routeTargets); - if (!missing.isEmpty()) { - String error = "Create Network: Missing parameters: " + missing; - logger.error("{} {} {}", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); - - throw new NetworkException(error, MsoExceptionCategory.USERDATA); - } + String mode = networkResource.getOrchestrationMode(); + NetworkType neutronNetworkType = NetworkType.valueOf(networkResource.getNeutronNetworkType()); + + // All Networks are orchestrated via HEAT or Neutron + if (!("HEAT".equals(mode) || NEUTRON_MODE.equals(mode))) { + String error = "CreateNetwork: Configuration Error: Network Type = " + networkType; + logger.error("{} {} {}", MessageEnum.RA_NETWORK_ORCHE_MODE_NOT_SUPPORT, ErrorCode.DataError.getValue(), + error); + throw new NetworkException(error, MsoExceptionCategory.INTERNAL); + } + + MavenLikeVersioning aicV = new MavenLikeVersioning(); + aicV.setVersion(cloudSite.getCloudVersion()); + if ((aicV.isMoreRecentThan(networkResource.getAicVersionMin()) + || aicV.isTheSameVersion(networkResource.getAicVersionMin())) // aic + // >= + // min + && (aicV.isTheSameVersion(networkResource.getAicVersionMax()) + || !(aicV.isMoreRecentThan(networkResource.getAicVersionMax())))) // aic <= max + { + logger.debug("Network Type:{} VersionMin:{} VersionMax:{} supported on Cloud:{} with AIC_Version:{}", + networkType, networkResource.getAicVersionMin(), networkResource.getAicVersionMax(), cloudSiteId, + cloudSite.getCloudVersion()); + } else { + String error = String.format( + "Network Type:%s Version_Min:%s Version_Max:%s not supported on Cloud:%s with AIC_Version:%s", + networkType, networkType, networkResource.getAicVersionMin(), networkResource.getAicVersionMax(), + cloudSiteId, cloudSite.getCloudVersion()); + logger.error("{} {} {} ", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error); + throw new NetworkException(error, MsoExceptionCategory.USERDATA); + } + + // Validate the Network parameters. + String missing = + validateNetworkParams(neutronNetworkType, networkName, physicalNetworkName, vlans, routeTargets); + if (!missing.isEmpty()) { + String error = "Create Network: Missing parameters: " + missing; + logger.error("{} {} {}", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); + + throw new NetworkException(error, MsoExceptionCategory.USERDATA); + } return networkResource; } @Override - public void queryNetwork (String cloudSiteId, - String tenantId, - String networkNameOrId, - MsoRequest msoRequest, - Holder <Boolean> networkExists, - Holder <String> networkId, - Holder <String> neutronNetworkId, - Holder <NetworkStatus> status, - Holder <List <Integer>> vlans, - Holder <Map <String, String>> subnetIdMap) throws NetworkException { - queryNetwork (cloudSiteId, - tenantId, - networkNameOrId, - msoRequest, - networkExists, - networkId, - neutronNetworkId, - status, - vlans, - null, - subnetIdMap); + public void queryNetwork(String cloudSiteId, String tenantId, String networkNameOrId, MsoRequest msoRequest, + Holder<Boolean> networkExists, Holder<String> networkId, Holder<String> neutronNetworkId, + Holder<NetworkStatus> status, Holder<List<Integer>> vlans, Holder<Map<String, String>> subnetIdMap) + throws NetworkException { + queryNetwork(cloudSiteId, tenantId, networkNameOrId, msoRequest, networkExists, networkId, neutronNetworkId, + status, vlans, null, subnetIdMap); } @Override - public void queryNetworkContrail (String cloudSiteId, - String tenantId, - String networkNameOrId, - MsoRequest msoRequest, - Holder <Boolean> networkExists, - Holder <String> networkId, - Holder <String> neutronNetworkId, - Holder <NetworkStatus> status, - Holder <List <RouteTarget>> routeTargets, - Holder <Map <String, String>> subnetIdMap) throws NetworkException { - queryNetwork (cloudSiteId, - tenantId, - networkNameOrId, - msoRequest, - networkExists, - networkId, - neutronNetworkId, - status, - null, - routeTargets, - subnetIdMap); + public void queryNetworkContrail(String cloudSiteId, String tenantId, String networkNameOrId, MsoRequest msoRequest, + Holder<Boolean> networkExists, Holder<String> networkId, Holder<String> neutronNetworkId, + Holder<NetworkStatus> status, Holder<List<RouteTarget>> routeTargets, + Holder<Map<String, String>> subnetIdMap) throws NetworkException { + queryNetwork(cloudSiteId, tenantId, networkNameOrId, msoRequest, networkExists, networkId, neutronNetworkId, + status, null, routeTargets, subnetIdMap); } /** - * This is the queryNetwork method. It returns the existence and status of - * the specified network, along with its Neutron UUID and list of VLANs. - * This method attempts to find the network using both Heat and Neutron. - * Heat stacks are first searched based on the provided network name/id. - * If none is found, the Neutron is directly queried. + * This is the queryNetwork method. It returns the existence and status of the specified network, along with its + * Neutron UUID and list of VLANs. This method attempts to find the network using both Heat and Neutron. Heat stacks + * are first searched based on the provided network name/id. If none is found, the Neutron is directly queried. */ - private void queryNetwork (String cloudSiteId, - String tenantId, - String networkNameOrId, - MsoRequest msoRequest, - Holder <Boolean> networkExists, - Holder <String> networkId, - Holder <String> neutronNetworkId, - Holder <NetworkStatus> status, - Holder <List <Integer>> vlans, - Holder <List <RouteTarget>> routeTargets, - Holder <Map <String, String>> subnetIdMap) throws NetworkException { + private void queryNetwork(String cloudSiteId, String tenantId, String networkNameOrId, MsoRequest msoRequest, + Holder<Boolean> networkExists, Holder<String> networkId, Holder<String> neutronNetworkId, + Holder<NetworkStatus> status, Holder<List<Integer>> vlans, Holder<List<RouteTarget>> routeTargets, + Holder<Map<String, String>> subnetIdMap) throws NetworkException { logger.debug("*** QUERY Network with Network: {} in {}/{}", networkNameOrId, cloudSiteId, tenantId); // Will capture execution time for metrics - long startTime = System.currentTimeMillis (); + long startTime = System.currentTimeMillis(); - if (commonUtils.isNullOrEmpty (cloudSiteId) - || commonUtils.isNullOrEmpty(tenantId) - || commonUtils.isNullOrEmpty(networkNameOrId)) { + if (commonUtils.isNullOrEmpty(cloudSiteId) || commonUtils.isNullOrEmpty(tenantId) + || commonUtils.isNullOrEmpty(networkNameOrId)) { String error = "Missing mandatory parameter cloudSiteId, tenantId or networkId"; logger.error("{} {} {}", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); - throw new NetworkException (error, MsoExceptionCategory.USERDATA); + throw new NetworkException(error, MsoExceptionCategory.USERDATA); } Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId); - if (!cloudSiteOpt.isPresent()) - { - String error = String - .format("Configuration Error. Stack %s in %s/%s: CloudSite does not exist in MSO Configuration", + if (!cloudSiteOpt.isPresent()) { + String error = String.format( + "Configuration Error. Stack %s in %s/%s: CloudSite does not exist in MSO Configuration", networkNameOrId, cloudSiteId, tenantId); logger.error("{} {} {}", MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error); - // Set the detailed error as the Exception 'message' - throw new NetworkException (error, MsoExceptionCategory.USERDATA); + // Set the detailed error as the Exception 'message' + throw new NetworkException(error, MsoExceptionCategory.USERDATA); } // Use MsoNeutronUtils for all NEUTRON commands @@ -1181,38 +910,37 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { String neutronId; // Try Heat first, since networks may be named the same as the Heat stack StackInfo heatStack = null; - long queryStackStarttime = System.currentTimeMillis (); + long queryStackStarttime = System.currentTimeMillis(); try { - heatStack = heat.queryStack (cloudSiteId, "CloudOwner", tenantId, networkNameOrId); + heatStack = heat.queryStack(cloudSiteId, "CloudOwner", tenantId, networkNameOrId); } catch (MsoException me) { - me.addContext ("QueryNetwork"); + me.addContext("QueryNetwork"); logger.error("{} {} Exception - Query Network (heat): {} in {}/{} ", MessageEnum.RA_QUERY_NETWORK_EXC, - ErrorCode.DataError.getValue(), networkNameOrId, cloudSiteId, tenantId, me); - throw new NetworkException (me); + ErrorCode.DataError.getValue(), networkNameOrId, cloudSiteId, tenantId, me); + throw new NetworkException(me); } // Populate the outputs based on the returned Stack information - if (heatStack != null && heatStack.getStatus () != HeatStatus.NOTFOUND) { + if (heatStack != null && heatStack.getStatus() != HeatStatus.NOTFOUND) { // Found it. Get the neutronNetworkId for further query - Map <String, Object> outputs = heatStack.getOutputs (); - neutronId = (String) outputs.get (NETWORK_ID); + Map<String, Object> outputs = heatStack.getOutputs(); + neutronId = (String) outputs.get(NETWORK_ID); mode = "HEAT"; - Map <String, String> sMap = new HashMap <> (); + Map<String, String> sMap = new HashMap<>(); if (outputs != null) { - for (String key : outputs.keySet ()) { - if (key != null && key.startsWith ("subnet_id_")) //multiples subnet_%aaid% outputs - { - String subnetUUId = (String) outputs.get(key); - sMap.put (key.substring("subnet_id_".length()), subnetUUId); - } - else if (key != null && key.startsWith ("subnet")) //one subnet output expected - { - Map <String, String> map = getSubnetUUId(key, outputs, null); - sMap.putAll(map); - } - - } + for (String key : outputs.keySet()) { + if (key != null && key.startsWith("subnet_id_")) // multiples subnet_%aaid% outputs + { + String subnetUUId = (String) outputs.get(key); + sMap.put(key.substring("subnet_id_".length()), subnetUUId); + } else if (key != null && key.startsWith("subnet")) // one subnet output expected + { + Map<String, String> map = getSubnetUUId(key, outputs, null); + sMap.putAll(map); + } + + } } subnetIdMap.value = sMap; } else { @@ -1224,143 +952,133 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { // Query directly against the Neutron Network for the details // no RouteTargets available for ContrailV2 in neutron net-show // networkId is heatStackId - long queryNetworkStarttime = System.currentTimeMillis (); + long queryNetworkStarttime = System.currentTimeMillis(); try { - NetworkInfo netInfo = neutron.queryNetwork (neutronId, tenantId, cloudSiteId); + NetworkInfo netInfo = neutron.queryNetwork(neutronId, tenantId, cloudSiteId); if (netInfo != null) { // Found. Populate the output elements networkExists.value = Boolean.TRUE; - if ("HEAT".equals (mode)) { - networkId.value = heatStack.getCanonicalName (); + if ("HEAT".equals(mode)) { + networkId.value = heatStack.getCanonicalName(); } else { - networkId.value = netInfo.getId (); + networkId.value = netInfo.getId(); } - neutronNetworkId.value = netInfo.getId (); - status.value = netInfo.getStatus (); + neutronNetworkId.value = netInfo.getId(); + status.value = netInfo.getStatus(); if (vlans != null) - vlans.value = netInfo.getVlans (); + vlans.value = netInfo.getVlans(); logger.debug("Network {} found({}), ID = {}{}", networkNameOrId, mode, networkId.value, - ("HEAT".equals(mode) ? ",NeutronId = " + neutronNetworkId.value : "")); + ("HEAT".equals(mode) ? ",NeutronId = " + neutronNetworkId.value : "")); } else { // Not found. Populate the status fields, leave the rest null networkExists.value = Boolean.FALSE; status.value = NetworkStatus.NOTFOUND; neutronNetworkId.value = null; if (vlans != null) - vlans.value = new ArrayList<>(); + vlans.value = new ArrayList<>(); logger.debug("Network {} not found", networkNameOrId); } } catch (MsoException me) { - me.addContext ("QueryNetwork"); + me.addContext("QueryNetwork"); logger.error("{} {} Exception - Query Network (neutron): {} in {}/{} ", MessageEnum.RA_QUERY_NETWORK_EXC, - ErrorCode.DataError.getValue(), networkNameOrId, cloudSiteId, tenantId, me); - throw new NetworkException (me); + ErrorCode.DataError.getValue(), networkNameOrId, cloudSiteId, tenantId, me); + throw new NetworkException(me); } return; } /** - * This is the "Delete Network" web service implementation. - * It will delete a Network in the specified cloud and tenant. + * This is the "Delete Network" web service implementation. It will delete a Network in the specified cloud and + * tenant. * * If the network is not found, it is treated as a success. * - * This service supports two modes of Network creation/update/delete: - * - via Heat Templates - * - via Neutron API - * The network orchestration mode for each network type is declared in its - * catalog definition. + * This service supports two modes of Network creation/update/delete: - via Heat Templates - via Neutron API The + * network orchestration mode for each network type is declared in its catalog definition. * - * For Heat-based orchestration, the networkId should be the stack ID. - * For Neutron-based orchestration, the networkId should be the Neutron network UUID. + * For Heat-based orchestration, the networkId should be the stack ID. For Neutron-based orchestration, the + * networkId should be the Neutron network UUID. * - * The method returns nothing on success. Rollback is not possible for delete - * commands, so any failure on delete will require manual fallout in the client. + * The method returns nothing on success. Rollback is not possible for delete commands, so any failure on delete + * will require manual fallout in the client. */ @Override - public void deleteNetwork (String cloudSiteId, - String tenantId, - String networkType, - String modelCustomizationUuid, - String networkId, - MsoRequest msoRequest, - Holder <Boolean> networkDeleted) throws NetworkException { + public void deleteNetwork(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid, + String networkId, MsoRequest msoRequest, Holder<Boolean> networkDeleted) throws NetworkException { logger.debug("*** DELETE Network adapter with Network: {} in {}/{}", networkId, cloudSiteId, tenantId); // Will capture execution time for metrics - long startTime = System.currentTimeMillis (); + long startTime = System.currentTimeMillis(); - if (commonUtils.isNullOrEmpty (cloudSiteId) - || commonUtils.isNullOrEmpty(tenantId) - || commonUtils.isNullOrEmpty(networkId)) { - String error = "Missing mandatory parameter cloudSiteId, tenantId or networkId"; - logger.error("{} {} {} ", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); - throw new NetworkException (error, MsoExceptionCategory.USERDATA); - } + if (commonUtils.isNullOrEmpty(cloudSiteId) || commonUtils.isNullOrEmpty(tenantId) + || commonUtils.isNullOrEmpty(networkId)) { + String error = "Missing mandatory parameter cloudSiteId, tenantId or networkId"; + logger.error("{} {} {} ", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); + throw new NetworkException(error, MsoExceptionCategory.USERDATA); + } + + // Retrieve the Network Resource definition + NetworkResource networkResource = null; - // Retrieve the Network Resource definition - NetworkResource networkResource = null; - - if (commonUtils.isNullOrEmpty(modelCustomizationUuid)) { - if (!commonUtils.isNullOrEmpty(networkType)) { - networkResource = networkResourceRepo.findFirstByModelNameOrderByModelVersionDesc(networkType); - } - } else { - NetworkResourceCustomization nrc = networkCustomRepo.findOneByModelCustomizationUUID(modelCustomizationUuid); - if (nrc != null) { - networkResource = nrc.getNetworkResource(); - } - } - String mode = ""; - if (networkResource != null) { - logger.debug("Got Network definition from Catalog: {}", networkResource.toString()); - - mode = networkResource.getOrchestrationMode (); + if (commonUtils.isNullOrEmpty(modelCustomizationUuid)) { + if (!commonUtils.isNullOrEmpty(networkType)) { + networkResource = networkResourceRepo.findFirstByModelNameOrderByModelVersionDesc(networkType); } + } else { + NetworkResourceCustomization nrc = + networkCustomRepo.findOneByModelCustomizationUUID(modelCustomizationUuid); + if (nrc != null) { + networkResource = nrc.getNetworkResource(); + } + } + String mode = ""; + if (networkResource != null) { + logger.debug("Got Network definition from Catalog: {}", networkResource.toString()); - if (NEUTRON_MODE.equals (mode)) { + mode = networkResource.getOrchestrationMode(); + } - // Use MsoNeutronUtils for all NEUTRON commands - long deleteNetworkStarttime = System.currentTimeMillis (); - try { - // The deleteNetwork function in MsoNeutronUtils returns success if the network - // was not found. So don't bother to query first. - boolean deleted = neutron.deleteNetwork (networkId, tenantId, cloudSiteId); - networkDeleted.value = deleted; - } catch (MsoException me) { - me.addContext ("DeleteNetwork"); - logger.error("{} {} Delete Network (neutron): {} in {}/{} ", MessageEnum.RA_DELETE_NETWORK_EXC, + if (NEUTRON_MODE.equals(mode)) { + + // Use MsoNeutronUtils for all NEUTRON commands + long deleteNetworkStarttime = System.currentTimeMillis(); + try { + // The deleteNetwork function in MsoNeutronUtils returns success if the network + // was not found. So don't bother to query first. + boolean deleted = neutron.deleteNetwork(networkId, tenantId, cloudSiteId); + networkDeleted.value = deleted; + } catch (MsoException me) { + me.addContext("DeleteNetwork"); + logger.error("{} {} Delete Network (neutron): {} in {}/{} ", MessageEnum.RA_DELETE_NETWORK_EXC, ErrorCode.DataError.getValue(), networkId, cloudSiteId, tenantId, me); - throw new NetworkException (me); - } - } else { // DEFAULT to ("HEAT".equals (mode)) - long deleteStackStarttime = System.currentTimeMillis (); + throw new NetworkException(me); + } + } else { // DEFAULT to ("HEAT".equals (mode)) + long deleteStackStarttime = System.currentTimeMillis(); - try { - // The deleteStack function in MsoHeatUtils returns NOTFOUND if the stack was not found or if the stack was deleted. - // So query first to report back if stack WAS deleted or just NOTOFUND - StackInfo heatStack = null; - heatStack = heat.queryStack(cloudSiteId, "CloudOwner", tenantId, networkId); - if (heatStack != null && heatStack.getStatus() != HeatStatus.NOTFOUND) - { - heat.deleteStack (tenantId, "CloudOwner", cloudSiteId, networkId, true); - networkDeleted.value = true; - } - else - { - networkDeleted.value = false; - } - } catch (MsoException me) { - me.addContext ("DeleteNetwork"); - logger.error("{} {} Delete Network (heat): {} in {}/{} ", MessageEnum.RA_DELETE_NETWORK_EXC, - ErrorCode.DataError.getValue(), networkId, cloudSiteId, tenantId, me); - throw new NetworkException (me); + try { + // The deleteStack function in MsoHeatUtils returns NOTFOUND if the stack was not found or if the stack + // was deleted. + // So query first to report back if stack WAS deleted or just NOTOFUND + StackInfo heatStack = null; + heatStack = heat.queryStack(cloudSiteId, "CloudOwner", tenantId, networkId); + if (heatStack != null && heatStack.getStatus() != HeatStatus.NOTFOUND) { + heat.deleteStack(tenantId, "CloudOwner", cloudSiteId, networkId, true); + networkDeleted.value = true; + } else { + networkDeleted.value = false; } + } catch (MsoException me) { + me.addContext("DeleteNetwork"); + logger.error("{} {} Delete Network (heat): {} in {}/{} ", MessageEnum.RA_DELETE_NETWORK_EXC, + ErrorCode.DataError.getValue(), networkId, cloudSiteId, tenantId, me); + throw new NetworkException(me); } + } // On success, nothing is returned. @@ -1368,126 +1086,117 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { } /** - * This web service endpoint will rollback a previous Create VNF operation. - * A rollback object is returned to the client in a successful creation - * response. The client can pass that object as-is back to the rollbackVnf - * operation to undo the creation. + * This web service endpoint will rollback a previous Create VNF operation. A rollback object is returned to the + * client in a successful creation response. The client can pass that object as-is back to the rollbackVnf operation + * to undo the creation. * - * The rollback includes removing the VNF and deleting the tenant if the - * tenant did not exist prior to the VNF creation. + * The rollback includes removing the VNF and deleting the tenant if the tenant did not exist prior to the VNF + * creation. */ @Override - public void rollbackNetwork (NetworkRollback rollback) throws NetworkException { + public void rollbackNetwork(NetworkRollback rollback) throws NetworkException { // Will capture execution time for metrics - long startTime = System.currentTimeMillis (); + long startTime = System.currentTimeMillis(); if (rollback == null) { - logger - .error("{} {} rollback is null", MessageEnum.RA_ROLLBACK_NULL, ErrorCode.DataError.getValue()); + logger.error("{} {} rollback is null", MessageEnum.RA_ROLLBACK_NULL, ErrorCode.DataError.getValue()); return; } // Get the elements of the VnfRollback object for easier access - String cloudSiteId = rollback.getCloudId (); - String tenantId = rollback.getTenantId (); - String networkId = rollback.getNetworkStackId (); - String networkType = rollback.getNetworkType (); + String cloudSiteId = rollback.getCloudId(); + String tenantId = rollback.getTenantId(); + String networkId = rollback.getNetworkStackId(); + String networkType = rollback.getNetworkType(); String modelCustomizationUuid = rollback.getModelCustomizationUuid(); logger.debug("*** ROLLBACK Network {} in {}/{}", networkId, cloudSiteId, tenantId); - // Retrieve the Network Resource definition - NetworkResource networkResource = null; - if (commonUtils.isNullOrEmpty(modelCustomizationUuid)) { - networkResource = networkCustomRepo.findOneByNetworkType(networkType).getNetworkResource(); - } else { - networkResource = networkCustomRepo.findOneByModelCustomizationUUID(modelCustomizationUuid).getNetworkResource(); - } - String mode = ""; - if (networkResource != null) { + // Retrieve the Network Resource definition + NetworkResource networkResource = null; + if (commonUtils.isNullOrEmpty(modelCustomizationUuid)) { + networkResource = networkCustomRepo.findOneByNetworkType(networkType).getNetworkResource(); + } else { + networkResource = + networkCustomRepo.findOneByModelCustomizationUUID(modelCustomizationUuid).getNetworkResource(); + } + String mode = ""; + if (networkResource != null) { - logger.debug("Got Network definition from Catalog: {}", networkResource.toString()); + logger.debug("Got Network definition from Catalog: {}", networkResource.toString()); - mode = networkResource.getOrchestrationMode (); - } + mode = networkResource.getOrchestrationMode(); + } - if (rollback.getNetworkCreated ()) { - // Rolling back a newly created network, so delete it. - if (NEUTRON_MODE.equals (mode)) { - // Use MsoNeutronUtils for all NEUTRON commands - long deleteNetworkStarttime = System.currentTimeMillis (); - try { - // The deleteNetwork function in MsoNeutronUtils returns success if the network - // was not found. So don't bother to query first. - neutron.deleteNetwork (networkId, tenantId, cloudSiteId); - } catch (MsoException me) { - me.addContext ("RollbackNetwork"); - logger.error("{} {} Exception - Rollback Network (neutron): {} in {}/{} ", - MessageEnum.RA_DELETE_NETWORK_EXC, ErrorCode.BusinessProcesssError.getValue(), - networkId, cloudSiteId, tenantId, me); - throw new NetworkException (me); - } - } else { // DEFAULT to if ("HEAT".equals (mode)) - long deleteStackStarttime = System.currentTimeMillis (); - try { - // The deleteStack function in MsoHeatUtils returns success if the stack - // was not found. So don't bother to query first. - heat.deleteStack (tenantId, "CloudOwner", cloudSiteId, networkId, true); - } catch (MsoException me) { - me.addContext ("RollbackNetwork"); - logger.error("{} {} Exception - Rollback Network (heat): {} in {}/{} ", - MessageEnum.RA_DELETE_NETWORK_EXC, ErrorCode.BusinessProcesssError.getValue(), - networkId, cloudSiteId, tenantId, me); - throw new NetworkException (me); - } + if (rollback.getNetworkCreated()) { + // Rolling back a newly created network, so delete it. + if (NEUTRON_MODE.equals(mode)) { + // Use MsoNeutronUtils for all NEUTRON commands + long deleteNetworkStarttime = System.currentTimeMillis(); + try { + // The deleteNetwork function in MsoNeutronUtils returns success if the network + // was not found. So don't bother to query first. + neutron.deleteNetwork(networkId, tenantId, cloudSiteId); + } catch (MsoException me) { + me.addContext("RollbackNetwork"); + logger.error("{} {} Exception - Rollback Network (neutron): {} in {}/{} ", + MessageEnum.RA_DELETE_NETWORK_EXC, ErrorCode.BusinessProcesssError.getValue(), networkId, + cloudSiteId, tenantId, me); + throw new NetworkException(me); + } + } else { // DEFAULT to if ("HEAT".equals (mode)) + long deleteStackStarttime = System.currentTimeMillis(); + try { + // The deleteStack function in MsoHeatUtils returns success if the stack + // was not found. So don't bother to query first. + heat.deleteStack(tenantId, "CloudOwner", cloudSiteId, networkId, true); + } catch (MsoException me) { + me.addContext("RollbackNetwork"); + logger.error("{} {} Exception - Rollback Network (heat): {} in {}/{} ", + MessageEnum.RA_DELETE_NETWORK_EXC, ErrorCode.BusinessProcesssError.getValue(), networkId, + cloudSiteId, tenantId, me); + throw new NetworkException(me); } } + } return; } - private String validateNetworkParams (NetworkType neutronNetworkType, - String networkName, - String physicalNetwork, - List <Integer> vlans, - List <RouteTarget> routeTargets) { + private String validateNetworkParams(NetworkType neutronNetworkType, String networkName, String physicalNetwork, + List<Integer> vlans, List<RouteTarget> routeTargets) { String sep = ""; - StringBuilder missing = new StringBuilder (); + StringBuilder missing = new StringBuilder(); if (commonUtils.isNullOrEmpty(networkName)) { - missing.append ("networkName"); + missing.append("networkName"); sep = ","; } if (neutronNetworkType == NetworkType.PROVIDER || neutronNetworkType == NetworkType.MULTI_PROVIDER) { if (commonUtils.isNullOrEmpty(physicalNetwork)) { - missing.append (sep).append ("physicalNetworkName"); + missing.append(sep).append("physicalNetworkName"); sep = ","; } - if (vlans == null || vlans.isEmpty ()) { - missing.append (sep).append (VLANS); + if (vlans == null || vlans.isEmpty()) { + missing.append(sep).append(VLANS); } } - return missing.toString (); + return missing.toString(); } - private Map <String, Object> populateNetworkParams (NetworkType neutronNetworkType, - String networkName, - String physicalNetwork, - List <Integer> vlans, - List <RouteTarget> routeTargets, - String shared, - String external, - boolean aic3template) { + private Map<String, Object> populateNetworkParams(NetworkType neutronNetworkType, String networkName, + String physicalNetwork, List<Integer> vlans, List<RouteTarget> routeTargets, String shared, String external, + boolean aic3template) { // Build the common set of HEAT template parameters - Map <String, Object> stackParams = new HashMap <> (); - stackParams.put ("network_name", networkName); + Map<String, Object> stackParams = new HashMap<>(); + stackParams.put("network_name", networkName); if (neutronNetworkType == NetworkType.PROVIDER) { // For Provider type - stackParams.put (PHYSICAL_NETWORK, physicalNetwork); - stackParams.put ("vlan", vlans.get (0).toString ()); + stackParams.put(PHYSICAL_NETWORK, physicalNetwork); + stackParams.put("vlan", vlans.get(0).toString()); } else if (neutronNetworkType == NetworkType.MULTI_PROVIDER) { // For Multi-provider, PO supports a custom resource extension of ProviderNet. // It supports all ProviderNet properties except segmentation_id, and adds a @@ -1495,16 +1204,16 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { // Note that this does not match the Neutron definition of Multi-Provider network, // which contains a list of 'segments', each having physical_network, network_type, // and segmentation_id. - StringBuilder buf = new StringBuilder (); + StringBuilder buf = new StringBuilder(); String sep = ""; for (Integer vlan : vlans) { - buf.append (sep).append (vlan.toString ()); + buf.append(sep).append(vlan.toString()); sep = ","; } - String csl = buf.toString (); + String csl = buf.toString(); - stackParams.put (PHYSICAL_NETWORK, physicalNetwork); - stackParams.put (VLANS, csl); + stackParams.put(PHYSICAL_NETWORK, physicalNetwork); + stackParams.put(VLANS, csl); } if (routeTargets != null) { @@ -1513,402 +1222,319 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { String rtExport = ""; String sep = ""; for (RouteTarget rt : routeTargets) { - boolean rtIsNull = false; - if (rt != null) - { - String routeTarget = rt.getRouteTarget(); - String routeTargetRole = rt.getRouteTargetRole(); - logger.debug("Checking for an actually null route target: {}", rt); - if (routeTarget == null || routeTarget.equals("") || routeTarget.equalsIgnoreCase("null")) - rtIsNull = true; - if (routeTargetRole == null || routeTargetRole.equals("") || routeTargetRole.equalsIgnoreCase("null")) - rtIsNull = true; - } else { - rtIsNull = true; - } - if (!rtIsNull) { - logger.debug("Input RT:{}", rt); - String role = rt.getRouteTargetRole(); - String rtValue = rt.getRouteTarget(); - - if ("IMPORT".equalsIgnoreCase(role)) - { - sep = rtImport.isEmpty() ? "" : ","; - rtImport = aic3template ? rtImport + sep + "target:" + rtValue : rtImport + sep + rtValue ; - } - else if ("EXPORT".equalsIgnoreCase(role)) - { - sep = rtExport.isEmpty() ? "" : ","; - rtExport = aic3template ? rtExport + sep + "target:" + rtValue : rtExport + sep + rtValue ; - } - else // covers BOTH, empty etc - { - sep = rtGlobal.isEmpty() ? "" : ","; - rtGlobal = aic3template ? rtGlobal + sep + "target:" + rtValue : rtGlobal + sep + rtValue ; - } - - } + boolean rtIsNull = false; + if (rt != null) { + String routeTarget = rt.getRouteTarget(); + String routeTargetRole = rt.getRouteTargetRole(); + logger.debug("Checking for an actually null route target: {}", rt); + if (routeTarget == null || routeTarget.equals("") || routeTarget.equalsIgnoreCase("null")) + rtIsNull = true; + if (routeTargetRole == null || routeTargetRole.equals("") + || routeTargetRole.equalsIgnoreCase("null")) + rtIsNull = true; + } else { + rtIsNull = true; + } + if (!rtIsNull) { + logger.debug("Input RT:{}", rt); + String role = rt.getRouteTargetRole(); + String rtValue = rt.getRouteTarget(); + + if ("IMPORT".equalsIgnoreCase(role)) { + sep = rtImport.isEmpty() ? "" : ","; + rtImport = aic3template ? rtImport + sep + "target:" + rtValue : rtImport + sep + rtValue; + } else if ("EXPORT".equalsIgnoreCase(role)) { + sep = rtExport.isEmpty() ? "" : ","; + rtExport = aic3template ? rtExport + sep + "target:" + rtValue : rtExport + sep + rtValue; + } else // covers BOTH, empty etc + { + sep = rtGlobal.isEmpty() ? "" : ","; + rtGlobal = aic3template ? rtGlobal + sep + "target:" + rtValue : rtGlobal + sep + rtValue; + } + + } } - if (!rtImport.isEmpty()) - { - stackParams.put ("route_targets_import", rtImport); + if (!rtImport.isEmpty()) { + stackParams.put("route_targets_import", rtImport); } - if (!rtExport.isEmpty()) - { - stackParams.put ("route_targets_export", rtExport); + if (!rtExport.isEmpty()) { + stackParams.put("route_targets_export", rtExport); } - if (!rtGlobal.isEmpty()) - { - stackParams.put ("route_targets", rtGlobal); + if (!rtGlobal.isEmpty()) { + stackParams.put("route_targets", rtGlobal); } } if (commonUtils.isNullOrEmpty(shared)) { - stackParams.put ("shared", "False"); + stackParams.put("shared", "False"); } else { - stackParams.put ("shared", shared); + stackParams.put("shared", shared); } if (commonUtils.isNullOrEmpty(external)) { - stackParams.put ("external", "False"); + stackParams.put("external", "False"); } else { - stackParams.put ("external", external); + stackParams.put("external", external); } return stackParams; } - /** policyRef_list structure in stackParams - [ - { - "network_policy_refs_data_sequence": { - "network_policy_refs_data_sequence_major": "1", - "network_policy_refs_data_sequence_minor": "0" - } - }, - { - "network_policy_refs_data_sequence": { - "network_policy_refs_data_sequence_major": "2", - "network_policy_refs_data_sequence_minor": "0" - } - } - ] - **/ - private void mergePolicyRefs(List <String> pFqdns, Map <String, Object> stackParams) throws MsoException { - //Resource Property - List<ContrailPolicyRef> prlist = new ArrayList <> (); - int index = 1; - for (String pf : pFqdns) { - if (!commonUtils.isNullOrEmpty(pf)) - { - ContrailPolicyRef pr = new ContrailPolicyRef(); - ContrailPolicyRefSeq refSeq = new ContrailPolicyRefSeq(String.valueOf(index), "0"); - pr.setSeq(refSeq); - index++; - logger.debug("Contrail PolicyRefs Data:{}", pr); - prlist.add(pr); - } - } - - JsonNode node = null; - try - { - ObjectMapper mapper = new ObjectMapper(); - node = mapper.convertValue(prlist, JsonNode.class); - String jsonString = mapper.writeValueAsString(prlist); - logger.debug("Json PolicyRefs Data:{}", jsonString); - } - catch (Exception e) - { - String error = "Error creating JsonNode for policyRefs Data"; - logger.error("{} {} {} ", MessageEnum.RA_MARSHING_ERROR, ErrorCode.BusinessProcesssError.getValue(), - error, e); - throw new MsoAdapterException (error); - } - //update parameters - if (pFqdns != null && node != null) - { - StringBuilder buf = new StringBuilder (); - String sep = ""; - for (String pf : pFqdns) { - if (!commonUtils.isNullOrEmpty(pf)) - { - buf.append (sep).append (pf); - sep = ","; - } - } - String csl = buf.toString (); - stackParams.put ("policy_refs", csl); - stackParams.put ("policy_refsdata", node); - } + /** + * policyRef_list structure in stackParams [ { "network_policy_refs_data_sequence": { + * "network_policy_refs_data_sequence_major": "1", "network_policy_refs_data_sequence_minor": "0" } }, { + * "network_policy_refs_data_sequence": { "network_policy_refs_data_sequence_major": "2", + * "network_policy_refs_data_sequence_minor": "0" } } ] + **/ + private void mergePolicyRefs(List<String> pFqdns, Map<String, Object> stackParams) throws MsoException { + // Resource Property + List<ContrailPolicyRef> prlist = new ArrayList<>(); + int index = 1; + for (String pf : pFqdns) { + if (!commonUtils.isNullOrEmpty(pf)) { + ContrailPolicyRef pr = new ContrailPolicyRef(); + ContrailPolicyRefSeq refSeq = new ContrailPolicyRefSeq(String.valueOf(index), "0"); + pr.setSeq(refSeq); + index++; + logger.debug("Contrail PolicyRefs Data:{}", pr); + prlist.add(pr); + } + } + + JsonNode node = null; + try { + ObjectMapper mapper = new ObjectMapper(); + node = mapper.convertValue(prlist, JsonNode.class); + String jsonString = mapper.writeValueAsString(prlist); + logger.debug("Json PolicyRefs Data:{}", jsonString); + } catch (Exception e) { + String error = "Error creating JsonNode for policyRefs Data"; + logger.error("{} {} {} ", MessageEnum.RA_MARSHING_ERROR, ErrorCode.BusinessProcesssError.getValue(), error, + e); + throw new MsoAdapterException(error); + } + // update parameters + if (pFqdns != null && node != null) { + StringBuilder buf = new StringBuilder(); + String sep = ""; + for (String pf : pFqdns) { + if (!commonUtils.isNullOrEmpty(pf)) { + buf.append(sep).append(pf); + sep = ","; + } + } + String csl = buf.toString(); + stackParams.put("policy_refs", csl); + stackParams.put("policy_refsdata", node); + } logger.debug("StackParams updated with policy refs"); - return; + return; } - private void mergeRouteTableRefs(List <String> rtFqdns, Map <String, Object> stackParams) throws MsoException { - - //update parameters - if (rtFqdns != null) - { - StringBuilder buf = new StringBuilder (); - String sep = ""; - for (String rtf : rtFqdns) { - if (!commonUtils.isNullOrEmpty(rtf)) - { - buf.append (sep).append (rtf); - sep = ","; - } - } - String csl = buf.toString (); - stackParams.put ("route_table_refs", csl); - } + private void mergeRouteTableRefs(List<String> rtFqdns, Map<String, Object> stackParams) throws MsoException { + + // update parameters + if (rtFqdns != null) { + StringBuilder buf = new StringBuilder(); + String sep = ""; + for (String rtf : rtFqdns) { + if (!commonUtils.isNullOrEmpty(rtf)) { + buf.append(sep).append(rtf); + sep = ","; + } + } + String csl = buf.toString(); + stackParams.put("route_table_refs", csl); + } logger.debug("StackParams updated with route_table refs"); - return; + return; } - /*** Subnet Output structure from Juniper - { - "ipam_subnets": [ - { - "subnet": { - "ip_prefix": "10.100.1.0", - "ip_prefix_len": 28 - }, - "addr_from_start": null, - "enable_dhcp": false, - "default_gateway": "10.100.1.1", - "dns_nameservers": [], - "dhcp_option_list": null, - "subnet_uuid": "10391fbf-6b9c-4160-825d-2d018b7649cf", - "allocation_pools": [ - { - "start": "10.100.1.3", - "end": "10.100.1.5" - }, - { - "start": "10.100.1.6", - "end": "10.100.1.9" - } - ], - "host_routes": null, - "dns_server_address": "10.100.1.13", - "subnet_name": "subnet_MsoNW1_692c9032-e1a2-4d64-828c-7b9a4fcc05b0" - }, - { - "subnet": { - "ip_prefix": "10.100.2.16", - "ip_prefix_len": 28 - }, - "addr_from_start": null, - "enable_dhcp": true, - "default_gateway": "10.100.2.17", - "dns_nameservers": [], - "dhcp_option_list": null, - "subnet_uuid": "c7aac5ea-66fe-443a-85f9-9c38a608c0f6", - "allocation_pools": [ - { - "start": "10.100.2.18", - "end": "10.100.2.20" - } - ], - "host_routes": null, - "dns_server_address": "10.100.2.29", - "subnet_name": "subnet_MsoNW1_692c9032-e1a2-4d64-828c-7b9a4fcc05b1" + /*** + * Subnet Output structure from Juniper { "ipam_subnets": [ { "subnet": { "ip_prefix": "10.100.1.0", + * "ip_prefix_len": 28 }, "addr_from_start": null, "enable_dhcp": false, "default_gateway": "10.100.1.1", + * "dns_nameservers": [], "dhcp_option_list": null, "subnet_uuid": "10391fbf-6b9c-4160-825d-2d018b7649cf", + * "allocation_pools": [ { "start": "10.100.1.3", "end": "10.100.1.5" }, { "start": "10.100.1.6", "end": + * "10.100.1.9" } ], "host_routes": null, "dns_server_address": "10.100.1.13", "subnet_name": + * "subnet_MsoNW1_692c9032-e1a2-4d64-828c-7b9a4fcc05b0" }, { "subnet": { "ip_prefix": "10.100.2.16", + * "ip_prefix_len": 28 }, "addr_from_start": null, "enable_dhcp": true, "default_gateway": "10.100.2.17", + * "dns_nameservers": [], "dhcp_option_list": null, "subnet_uuid": "c7aac5ea-66fe-443a-85f9-9c38a608c0f6", + * "allocation_pools": [ { "start": "10.100.2.18", "end": "10.100.2.20" } ], "host_routes": null, + * "dns_server_address": "10.100.2.29", "subnet_name": "subnet_MsoNW1_692c9032-e1a2-4d64-828c-7b9a4fcc05b1" } ], + * "host_routes": null } + ***/ + private String mergeSubnetsAIC3(String heatTemplate, List<Subnet> subnets, Map<String, Object> stackParams) + throws MsoException { + + // Resource Property + List<ContrailSubnet> cslist = new ArrayList<>(); + for (Subnet subnet : subnets) { + logger.debug("Input Subnet:{}", subnet.toString()); + ContrailSubnet cs = new ContrailSubnetMapper(subnet).map(); + logger.debug("Contrail Subnet:{}", cs.toString()); + cslist.add(cs); } - ], - "host_routes": null - } - ***/ - private String mergeSubnetsAIC3 (String heatTemplate, List <Subnet> subnets, Map <String, Object> stackParams) throws MsoException { - - //Resource Property - List<ContrailSubnet> cslist = new ArrayList <> (); - for (Subnet subnet : subnets) { - logger.debug("Input Subnet:{}", subnet.toString()); - ContrailSubnet cs = new ContrailSubnetMapper(subnet).map(); - logger.debug("Contrail Subnet:{}", cs.toString()); - cslist.add(cs); - } - - JsonNode node = null; - try - { - ObjectMapper mapper = new ObjectMapper(); - node = mapper.convertValue(cslist, JsonNode.class); - String jsonString = mapper.writeValueAsString(cslist); - logger.debug("Json Subnet List:{}", jsonString); - } - catch (Exception e) - { - String error = "Error creating JsonNode from input subnets"; - logger.error("{} {} {} ", MessageEnum.RA_MARSHING_ERROR, ErrorCode.DataError.getValue(), error, e); - throw new MsoAdapterException (error); - } - //update parameters - if (node != null) - { - stackParams.put ("subnet_list", node); - } - //Outputs - All subnets are in one ipam_subnets structure - String outputTempl = " subnet:\n" + " description: Openstack subnet identifier\n" - + " value: { get_attr: [network, network_ipam_refs, 0, attr]}\n"; - - // append outputs in heatTemplate - int outputsIdx = heatTemplate.indexOf ("outputs:"); - heatTemplate = insertStr (heatTemplate, outputTempl, outputsIdx + 8); + + JsonNode node = null; + try { + ObjectMapper mapper = new ObjectMapper(); + node = mapper.convertValue(cslist, JsonNode.class); + String jsonString = mapper.writeValueAsString(cslist); + logger.debug("Json Subnet List:{}", jsonString); + } catch (Exception e) { + String error = "Error creating JsonNode from input subnets"; + logger.error("{} {} {} ", MessageEnum.RA_MARSHING_ERROR, ErrorCode.DataError.getValue(), error, e); + throw new MsoAdapterException(error); + } + // update parameters + if (node != null) { + stackParams.put("subnet_list", node); + } + // Outputs - All subnets are in one ipam_subnets structure + String outputTempl = " subnet:\n" + " description: Openstack subnet identifier\n" + + " value: { get_attr: [network, network_ipam_refs, 0, attr]}\n"; + + // append outputs in heatTemplate + int outputsIdx = heatTemplate.indexOf("outputs:"); + heatTemplate = insertStr(heatTemplate, outputTempl, outputsIdx + 8); logger.debug("Template updated with all AIC3.0 subnets:{}", heatTemplate); - return heatTemplate; + return heatTemplate; } - private String mergeSubnets (String heatTemplate, List <Subnet> subnets) throws MsoException { - - String resourceTempl = " subnet_%subnetId%:\n" + " type: OS::Neutron::Subnet\n" - + " properties:\n" - + " name: %name%\n" - + " network_id: { get_resource: network }\n" - + " cidr: %cidr%\n"; - - /* make these optional - + " ip_version: %ipversion%\n" - + " enable_dhcp: %enabledhcp%\n" - + " gateway_ip: %gatewayip%\n" - + " allocation_pools:\n" - + " - start: %poolstart%\n" - + " end: %poolend%\n"; - - */ - - String outputTempl = " subnet_id_%subnetId%:\n" + " description: Openstack subnet identifier\n" - + " value: {get_resource: subnet_%subnetId%}\n"; - - String curR; - String curO; - StringBuilder resourcesBuf = new StringBuilder (); - StringBuilder outputsBuf = new StringBuilder (); - for (Subnet subnet : subnets) { - - // build template for each subnet - curR = resourceTempl; - if (subnet.getSubnetId () != null) { - curR = curR.replace ("%subnetId%", subnet.getSubnetId ()); - } else { - String error = "Missing Required AAI SubnetId for subnet in HEAT Template"; - logger.error("{} {} {} ", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); - throw new MsoAdapterException (error); - } - - if (subnet.getSubnetName () != null) { - curR = curR.replace ("%name%", subnet.getSubnetName ()); - } else { - curR = curR.replace ("%name%", subnet.getSubnetId ()); - } - - if (subnet.getCidr () != null) { - curR = curR.replace ("%cidr%", subnet.getCidr ()); - } else { - String error = "Missing Required cidr for subnet in HEAT Template"; - logger.error("{} {} {} ", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); - throw new MsoAdapterException (error); - } - - if (subnet.getIpVersion () != null) { - curR = curR + " ip_version: " + subnet.getIpVersion () + "\n"; - } - if (subnet.getEnableDHCP () != null) { - curR = curR + " enable_dhcp: " + Boolean.toString (subnet.getEnableDHCP ()) + "\n"; - } - if (subnet.getGatewayIp () != null && !subnet.getGatewayIp ().isEmpty() ) { - curR = curR + " gateway_ip: " + subnet.getGatewayIp () + "\n"; - } - - if (subnet.getAllocationPools() != null) { - curR = curR + " allocation_pools:\n"; - for (Pool pool : subnet.getAllocationPools()) - { - if (!commonUtils.isNullOrEmpty(pool.getStart()) && !commonUtils.isNullOrEmpty(pool.getEnd())) - { - curR = curR + " - start: " + pool.getStart () + "\n"; - curR = curR + " end: " + pool.getEnd () + "\n"; - } - } - } - - resourcesBuf.append (curR); - - curO = outputTempl; - curO = curO.replace ("%subnetId%", subnet.getSubnetId ()); - - outputsBuf.append (curO); - - } - // append resources and outputs in heatTemplate + private String mergeSubnets(String heatTemplate, List<Subnet> subnets) throws MsoException { + + String resourceTempl = " subnet_%subnetId%:\n" + " type: OS::Neutron::Subnet\n" + " properties:\n" + + " name: %name%\n" + " network_id: { get_resource: network }\n" + " cidr: %cidr%\n"; + + /* + * make these optional + " ip_version: %ipversion%\n" + " enable_dhcp: %enabledhcp%\n" + + * " gateway_ip: %gatewayip%\n" + " allocation_pools:\n" + " - start: %poolstart%\n" + + * " end: %poolend%\n"; + * + */ + + String outputTempl = " subnet_id_%subnetId%:\n" + " description: Openstack subnet identifier\n" + + " value: {get_resource: subnet_%subnetId%}\n"; + + String curR; + String curO; + StringBuilder resourcesBuf = new StringBuilder(); + StringBuilder outputsBuf = new StringBuilder(); + for (Subnet subnet : subnets) { + + // build template for each subnet + curR = resourceTempl; + if (subnet.getSubnetId() != null) { + curR = curR.replace("%subnetId%", subnet.getSubnetId()); + } else { + String error = "Missing Required AAI SubnetId for subnet in HEAT Template"; + logger.error("{} {} {} ", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); + throw new MsoAdapterException(error); + } + + if (subnet.getSubnetName() != null) { + curR = curR.replace("%name%", subnet.getSubnetName()); + } else { + curR = curR.replace("%name%", subnet.getSubnetId()); + } + + if (subnet.getCidr() != null) { + curR = curR.replace("%cidr%", subnet.getCidr()); + } else { + String error = "Missing Required cidr for subnet in HEAT Template"; + logger.error("{} {} {} ", MessageEnum.RA_MISSING_PARAM, ErrorCode.DataError.getValue(), error); + throw new MsoAdapterException(error); + } + + if (subnet.getIpVersion() != null) { + curR = curR + " ip_version: " + subnet.getIpVersion() + "\n"; + } + if (subnet.getEnableDHCP() != null) { + curR = curR + " enable_dhcp: " + Boolean.toString(subnet.getEnableDHCP()) + "\n"; + } + if (subnet.getGatewayIp() != null && !subnet.getGatewayIp().isEmpty()) { + curR = curR + " gateway_ip: " + subnet.getGatewayIp() + "\n"; + } + + if (subnet.getAllocationPools() != null) { + curR = curR + " allocation_pools:\n"; + for (Pool pool : subnet.getAllocationPools()) { + if (!commonUtils.isNullOrEmpty(pool.getStart()) && !commonUtils.isNullOrEmpty(pool.getEnd())) { + curR = curR + " - start: " + pool.getStart() + "\n"; + curR = curR + " end: " + pool.getEnd() + "\n"; + } + } + } + + resourcesBuf.append(curR); + + curO = outputTempl; + curO = curO.replace("%subnetId%", subnet.getSubnetId()); + + outputsBuf.append(curO); + + } + // append resources and outputs in heatTemplate logger.debug("Tempate initial:{}", heatTemplate); - int outputsIdx = heatTemplate.indexOf ("outputs:"); - heatTemplate = insertStr (heatTemplate, outputsBuf.toString (), outputsIdx + 8); - int resourcesIdx = heatTemplate.indexOf ("resources:"); - heatTemplate = insertStr (heatTemplate, resourcesBuf.toString (), resourcesIdx + 10); + int outputsIdx = heatTemplate.indexOf("outputs:"); + heatTemplate = insertStr(heatTemplate, outputsBuf.toString(), outputsIdx + 8); + int resourcesIdx = heatTemplate.indexOf("resources:"); + heatTemplate = insertStr(heatTemplate, resourcesBuf.toString(), resourcesIdx + 10); logger.debug("Template updated with all subnets:{}", heatTemplate); - return heatTemplate; + return heatTemplate; } - private Map <String, String> getSubnetUUId(String key, Map <String, Object> outputs, List <Subnet> subnets) { - - Map <String, String> sMap = new HashMap <> (); - - try{ - Object obj = outputs.get(key); - ObjectMapper mapper = new ObjectMapper(); - String jStr = mapper.writeValueAsString(obj); - logger.debug("Subnet_Ipam Output JSON String:{} {}", obj.getClass(), jStr); - - JsonNode rootNode = mapper.readTree(jStr); - for (JsonNode sNode : rootNode.path("ipam_subnets")) - { - logger.debug("Output Subnet Node {}", sNode.toString()); - String name = sNode.path("subnet_name").textValue(); - String uuid = sNode.path("subnet_uuid").textValue(); - String aaiId = name; // default - // try to find aaiId for name in input subnetList - if (subnets != null) - { - for (Subnet subnet : subnets) - { - if ( subnet != null && !commonUtils.isNullOrEmpty(subnet.getSubnetName())) - { - if (subnet.getSubnetName().equals(name)) - { - aaiId = subnet.getSubnetId(); - break; - } - } - } - } - sMap.put(aaiId, uuid); //bpmn needs aaid to uuid map - } - } - catch (Exception e) - { - logger.error("{} {} Exception getting subnet-uuids ", MessageEnum.RA_MARSHING_ERROR, - ErrorCode.DataError.getValue(), e); - } + private Map<String, String> getSubnetUUId(String key, Map<String, Object> outputs, List<Subnet> subnets) { + + Map<String, String> sMap = new HashMap<>(); + + try { + Object obj = outputs.get(key); + ObjectMapper mapper = new ObjectMapper(); + String jStr = mapper.writeValueAsString(obj); + logger.debug("Subnet_Ipam Output JSON String:{} {}", obj.getClass(), jStr); + + JsonNode rootNode = mapper.readTree(jStr); + for (JsonNode sNode : rootNode.path("ipam_subnets")) { + logger.debug("Output Subnet Node {}", sNode.toString()); + String name = sNode.path("subnet_name").textValue(); + String uuid = sNode.path("subnet_uuid").textValue(); + String aaiId = name; // default + // try to find aaiId for name in input subnetList + if (subnets != null) { + for (Subnet subnet : subnets) { + if (subnet != null && !commonUtils.isNullOrEmpty(subnet.getSubnetName())) { + if (subnet.getSubnetName().equals(name)) { + aaiId = subnet.getSubnetId(); + break; + } + } + } + } + sMap.put(aaiId, uuid); // bpmn needs aaid to uuid map + } + } catch (Exception e) { + logger.error("{} {} Exception getting subnet-uuids ", MessageEnum.RA_MARSHING_ERROR, + ErrorCode.DataError.getValue(), e); + } logger.debug("Return sMap {}", sMap.toString()); - return sMap; + return sMap; } - private static String insertStr (String template, String snippet, int index) { + private static String insertStr(String template, String snippet, int index) { String updatedTemplate; logger.debug("Index:{} Snippet:{}", index, snippet); - String templateBeg = template.substring (0, index); - String templateEnd = template.substring (index); + String templateBeg = template.substring(0, index); + String templateEnd = template.substring(index); updatedTemplate = templateBeg + "\n" + snippet + templateEnd; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/NetworkAdapterRest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/NetworkAdapterRest.java index 4a6d591977..b44704d1cf 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/NetworkAdapterRest.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/NetworkAdapterRest.java @@ -85,652 +85,552 @@ import org.springframework.transaction.annotation.Transactional; public class NetworkAdapterRest { private static final Logger logger = LoggerFactory.getLogger(NetworkAdapterRest.class); - private static final String TESTING_KEYWORD = "___TESTING___"; - private String EXCEPTION = "Exception:"; - - @Autowired - private MsoNetworkAdapterImpl adapter; - - @Autowired - private Provider<BpelRestClient> bpelRestClientProvider; - - - @POST - @Path("") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "CreateNetwork", - response = Response.class, - notes = "Creates a new network, CreateNetworkRquest JSON is required") - @ApiResponses({ - @ApiResponse(code = 200, message = "network has been successfully created"), - @ApiResponse(code = 202, message = "create network request has been accepted (async only)"), - @ApiResponse(code = 500, message = "create network failed, examine entity object for details") }) - public Response createNetwork( - @ApiParam(value = "details of network being created", required = true) - CreateNetworkRequest req) { - logger.debug("createNetwork enter: {}", req.toJsonString()); - CreateNetworkTask task = new CreateNetworkTask(req); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} Exception while create network ", MessageEnum.RA_CREATE_NETWORK_EXC, - ErrorCode.BusinessProcesssError.getValue(), e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("createNetwork exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class CreateNetworkTask implements Runnable { - private final CreateNetworkRequest req; - private CreateNetworkResponse response = null; - private CreateNetworkError eresp = null; - private boolean sendxml; - - public CreateNetworkTask(CreateNetworkRequest req) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<CreateNetworkResponse>(response) {} - : new GenericEntity<CreateNetworkError>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - @Override - public void run() { - logger.debug("CreateNetworkTask start"); - try { - // Synchronous Web Service Outputs - Holder<String> networkId = new Holder<>(); - Holder<String> neutronNetworkId = new Holder<>(); - Holder<String> networkFqdn = new Holder<>(); - Holder<Map<String, String>> subnetIdMap = new Holder<>(); - Holder<NetworkRollback> rollback = new Holder<>(); - - HashMap<String, String> params = (HashMap<String, String>) req.getNetworkParams(); - if (params == null) { - params = new HashMap<String,String>(); - } - String shared = null; - String external = null; - - String cloudsite = req.getCloudSiteId(); - if (cloudsite != null && cloudsite.equals(TESTING_KEYWORD)) { - String tenant = req.getTenantId(); - if (tenant != null && tenant.equals(TESTING_KEYWORD)) { - throw new NetworkException("testing."); - } - networkId.value = "479D3D8B-6360-47BC-AB75-21CC91981484"; - neutronNetworkId.value = "55e55884-28fa-11e6-8971-0017f20fe1b8"; - networkFqdn.value = "086f70b6-28fb-11e6-8260-0017f20fe1b8"; - subnetIdMap.value = testMap(); - rollback.value = new NetworkRollback(); - } else if (req.isContrailRequest()) { - ContrailNetwork ctn = req.getContrailNetwork(); - if (ctn == null) { - ctn = new ContrailNetwork(); - req.setContrailNetwork(ctn); - } - if (params.containsKey("shared")) { - shared = params.get("shared"); - } else { - if (ctn.getShared() != null) { - shared = ctn.getShared(); - } - } - if (params.containsKey("external")) { - external = params.get("external"); - } else { - if (ctn.getExternal() != null) { - external = ctn.getExternal(); - } - } - adapter.createNetworkContrail( - req.getCloudSiteId(), - req.getTenantId(), - req.getNetworkType(), - req.getModelCustomizationUuid(), - req.getNetworkName(), - req.getContrailNetwork().getRouteTargets(), - shared, - external, - req.getFailIfExists(), - req.getBackout(), - req.getSubnets(), - params, - req.getContrailNetwork().getPolicyFqdns(), - req.getContrailNetwork().getRouteTableFqdns(), - req.getMsoRequest(), - networkId, - neutronNetworkId, - networkFqdn, - subnetIdMap, - rollback); - } else { - ProviderVlanNetwork pvn = req.getProviderVlanNetwork(); - if (pvn == null) { - pvn = new ProviderVlanNetwork(); - req.setProviderVlanNetwork(pvn); - } - if (params.containsKey("shared")) - shared = params.get("shared"); - if (params.containsKey("external")) - external = params.get("external"); - adapter.createNetwork( - req.getCloudSiteId(), - req.getTenantId(), - req.getNetworkType(), - req.getModelCustomizationUuid(), - req.getNetworkName(), - req.getProviderVlanNetwork().getPhysicalNetworkName(), - req.getProviderVlanNetwork().getVlans(), - shared, - external, - req.getFailIfExists(), - req.getBackout(), - req.getSubnets(), - params, - req.getMsoRequest(), - networkId, - neutronNetworkId, - subnetIdMap, - rollback); - } - response = new CreateNetworkResponse( - req.getNetworkId(), - neutronNetworkId.value, - rollback.value.getNetworkStackId(), - networkFqdn.value, - rollback.value.getNetworkCreated(), - subnetIdMap.value, - rollback.value, - req.getMessageId()); - } catch (NetworkException e) { - logger.debug(EXCEPTION, e); - eresp = new CreateNetworkError( - e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); - } - if (!req.isSynchronous()) { - // This is asynch, so POST response back to caller - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("CreateNetworkTask exit: code={}, resp={}", getStatusCode(), getResponse()); - } - } - - @DELETE - @Path("{aaiNetworkId}") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "DeleteNetwork", - response = Response.class, - notes = "Deletes an existing network, aaiNetworkId and DeleteNetworkRequest JSON are required") - @ApiResponses({ - @ApiResponse(code = 200, message = "network has been successfully deleted"), - @ApiResponse(code = 202, message = "request to delete network has been accepted (async only)"), - @ApiResponse(code = 500, message = "delete network failed, examine entity object for details") }) - public Response deleteNetwork( - @ApiParam(value = "aaiNetworkId to be deleted ", required = true) - @PathParam("aaiNetworkId") String aaiNetworkId, - @ApiParam(value = "details of network being deleted", required = true) - DeleteNetworkRequest req) - { - logger.debug("deleteNetwork enter: {}", req.toJsonString()); - if (aaiNetworkId == null || !aaiNetworkId.equals(req.getNetworkId())) { - return Response - .status(HttpStatus.SC_BAD_REQUEST) - .type(MediaType.TEXT_PLAIN) - .entity("A&AI NetworkId in URL ("+aaiNetworkId+") does not match content ("+req.getNetworkId()+")") - .build(); - } - DeleteNetworkTask task = new DeleteNetworkTask(req); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} Exception while delete network ", MessageEnum.RA_DELETE_NETWORK_EXC, - ErrorCode.BusinessProcesssError.getValue(), e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("deleteNetwork exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class DeleteNetworkTask implements Runnable { - private final DeleteNetworkRequest req; - private DeleteNetworkResponse response = null; - private DeleteNetworkError eresp = null; - private boolean sendxml; - - public DeleteNetworkTask(DeleteNetworkRequest req) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<DeleteNetworkResponse>(response) {} - : new GenericEntity<DeleteNetworkError>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - @Override - public void run() { - logger.debug("DeleteNetworkTask start"); - try { - Holder<Boolean> networkDeleted = new Holder<>(); - if (req.getCloudSiteId().equals(TESTING_KEYWORD)) { - networkDeleted.value = true; - } else { - adapter.deleteNetwork( - req.getCloudSiteId(), - req.getTenantId(), - req.getNetworkType(), - req.getModelCustomizationUuid(), - req.getNetworkStackId(), - req.getMsoRequest(), - networkDeleted); - } - response = new DeleteNetworkResponse(req.getNetworkId(), networkDeleted.value, req.getMessageId()); - } catch (NetworkException e) { - logger.debug(EXCEPTION, e); - eresp = new DeleteNetworkError(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); - } - if (!req.isSynchronous()) { - // This is asynch, so POST response back to caller - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("DeleteNetworkTask exit: code={}, resp={}", getStatusCode(), getResponse()); - } - } - - @GET - @Path("{aaiNetworkId}") - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "QueryNetwork", - response = Response.class, - notes = "Queries an existing network") - @ApiResponses({ - @ApiResponse(code = 200, message = "Query network successful"), - @ApiResponse(code = 500, message = "Query network failed, examine entity object for details") }) - public Response queryNetwork( - @ApiParam(value = "cloudSiteId", required = false) - @QueryParam("cloudSiteId") String cloudSiteId, - @ApiParam(value = "tenantId", required = false) - @QueryParam("tenantId") String tenantId, - @ApiParam(value = "networkStackId", required = false) - @QueryParam("networkStackId") String networkStackId, - @ApiParam(value = "skipAAI", required = false) - @QueryParam("skipAAI") String skipAAI, - @ApiParam(value = "msoRequest.requestId", required = false) - @QueryParam("msoRequest.requestId") String requestId, - @ApiParam(value = "msoRequest.serviceInstanceId", required = false) - @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId, - @ApiParam(value = "aaiNetworkId", required = false) - @PathParam("aaiNetworkId") String aaiNetworkId) - { - //This request responds synchronously only - logger.debug("Query network enter:{}" + aaiNetworkId); - MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId); - - try { - int respStatus = HttpStatus.SC_OK; - QueryNetworkResponse resp = new QueryNetworkResponse(networkStackId, null, networkStackId, null, null); - Holder<Boolean> networkExists = new Holder<>(); + private static final String TESTING_KEYWORD = "___TESTING___"; + private String EXCEPTION = "Exception:"; + + @Autowired + private MsoNetworkAdapterImpl adapter; + + @Autowired + private Provider<BpelRestClient> bpelRestClientProvider; + + + @POST + @Path("") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "CreateNetwork", response = Response.class, + notes = "Creates a new network, CreateNetworkRquest JSON is required") + @ApiResponses({@ApiResponse(code = 200, message = "network has been successfully created"), + @ApiResponse(code = 202, message = "create network request has been accepted (async only)"), + @ApiResponse(code = 500, message = "create network failed, examine entity object for details")}) + public Response createNetwork( + @ApiParam(value = "details of network being created", required = true) CreateNetworkRequest req) { + logger.debug("createNetwork enter: {}", req.toJsonString()); + CreateNetworkTask task = new CreateNetworkTask(req); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling create, send generic failure as sync resp to caller + logger.error("{} {} Exception while create network ", MessageEnum.RA_CREATE_NETWORK_EXC, + ErrorCode.BusinessProcesssError.getValue(), e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("createNetwork exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class CreateNetworkTask implements Runnable { + private final CreateNetworkRequest req; + private CreateNetworkResponse response = null; + private CreateNetworkError eresp = null; + private boolean sendxml; + + public CreateNetworkTask(CreateNetworkRequest req) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<CreateNetworkResponse>(response) {} + : new GenericEntity<CreateNetworkError>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + logger.debug("CreateNetworkTask start"); + try { + // Synchronous Web Service Outputs + Holder<String> networkId = new Holder<>(); + Holder<String> neutronNetworkId = new Holder<>(); + Holder<String> networkFqdn = new Holder<>(); + Holder<Map<String, String>> subnetIdMap = new Holder<>(); + Holder<NetworkRollback> rollback = new Holder<>(); + + HashMap<String, String> params = (HashMap<String, String>) req.getNetworkParams(); + if (params == null) { + params = new HashMap<String, String>(); + } + String shared = null; + String external = null; + + String cloudsite = req.getCloudSiteId(); + if (cloudsite != null && cloudsite.equals(TESTING_KEYWORD)) { + String tenant = req.getTenantId(); + if (tenant != null && tenant.equals(TESTING_KEYWORD)) { + throw new NetworkException("testing."); + } + networkId.value = "479D3D8B-6360-47BC-AB75-21CC91981484"; + neutronNetworkId.value = "55e55884-28fa-11e6-8971-0017f20fe1b8"; + networkFqdn.value = "086f70b6-28fb-11e6-8260-0017f20fe1b8"; + subnetIdMap.value = testMap(); + rollback.value = new NetworkRollback(); + } else if (req.isContrailRequest()) { + ContrailNetwork ctn = req.getContrailNetwork(); + if (ctn == null) { + ctn = new ContrailNetwork(); + req.setContrailNetwork(ctn); + } + if (params.containsKey("shared")) { + shared = params.get("shared"); + } else { + if (ctn.getShared() != null) { + shared = ctn.getShared(); + } + } + if (params.containsKey("external")) { + external = params.get("external"); + } else { + if (ctn.getExternal() != null) { + external = ctn.getExternal(); + } + } + adapter.createNetworkContrail(req.getCloudSiteId(), req.getTenantId(), req.getNetworkType(), + req.getModelCustomizationUuid(), req.getNetworkName(), + req.getContrailNetwork().getRouteTargets(), shared, external, req.getFailIfExists(), + req.getBackout(), req.getSubnets(), params, req.getContrailNetwork().getPolicyFqdns(), + req.getContrailNetwork().getRouteTableFqdns(), req.getMsoRequest(), networkId, + neutronNetworkId, networkFqdn, subnetIdMap, rollback); + } else { + ProviderVlanNetwork pvn = req.getProviderVlanNetwork(); + if (pvn == null) { + pvn = new ProviderVlanNetwork(); + req.setProviderVlanNetwork(pvn); + } + if (params.containsKey("shared")) + shared = params.get("shared"); + if (params.containsKey("external")) + external = params.get("external"); + adapter.createNetwork(req.getCloudSiteId(), req.getTenantId(), req.getNetworkType(), + req.getModelCustomizationUuid(), req.getNetworkName(), + req.getProviderVlanNetwork().getPhysicalNetworkName(), + req.getProviderVlanNetwork().getVlans(), shared, external, req.getFailIfExists(), + req.getBackout(), req.getSubnets(), params, req.getMsoRequest(), networkId, + neutronNetworkId, subnetIdMap, rollback); + } + response = new CreateNetworkResponse(req.getNetworkId(), neutronNetworkId.value, + rollback.value.getNetworkStackId(), networkFqdn.value, rollback.value.getNetworkCreated(), + subnetIdMap.value, rollback.value, req.getMessageId()); + } catch (NetworkException e) { + logger.debug(EXCEPTION, e); + eresp = new CreateNetworkError(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); + } + if (!req.isSynchronous()) { + // This is asynch, so POST response back to caller + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("CreateNetworkTask exit: code={}, resp={}", getStatusCode(), getResponse()); + } + } + + @DELETE + @Path("{aaiNetworkId}") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "DeleteNetwork", response = Response.class, + notes = "Deletes an existing network, aaiNetworkId and DeleteNetworkRequest JSON are required") + @ApiResponses({@ApiResponse(code = 200, message = "network has been successfully deleted"), + @ApiResponse(code = 202, message = "request to delete network has been accepted (async only)"), + @ApiResponse(code = 500, message = "delete network failed, examine entity object for details")}) + public Response deleteNetwork( + @ApiParam(value = "aaiNetworkId to be deleted ", + required = true) @PathParam("aaiNetworkId") String aaiNetworkId, + @ApiParam(value = "details of network being deleted", required = true) DeleteNetworkRequest req) { + logger.debug("deleteNetwork enter: {}", req.toJsonString()); + if (aaiNetworkId == null || !aaiNetworkId.equals(req.getNetworkId())) { + return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity( + "A&AI NetworkId in URL (" + aaiNetworkId + ") does not match content (" + req.getNetworkId() + ")") + .build(); + } + DeleteNetworkTask task = new DeleteNetworkTask(req); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling create, send generic failure as sync resp to caller + logger.error("{} {} Exception while delete network ", MessageEnum.RA_DELETE_NETWORK_EXC, + ErrorCode.BusinessProcesssError.getValue(), e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("deleteNetwork exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class DeleteNetworkTask implements Runnable { + private final DeleteNetworkRequest req; + private DeleteNetworkResponse response = null; + private DeleteNetworkError eresp = null; + private boolean sendxml; + + public DeleteNetworkTask(DeleteNetworkRequest req) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<DeleteNetworkResponse>(response) {} + : new GenericEntity<DeleteNetworkError>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + logger.debug("DeleteNetworkTask start"); + try { + Holder<Boolean> networkDeleted = new Holder<>(); + if (req.getCloudSiteId().equals(TESTING_KEYWORD)) { + networkDeleted.value = true; + } else { + adapter.deleteNetwork(req.getCloudSiteId(), req.getTenantId(), req.getNetworkType(), + req.getModelCustomizationUuid(), req.getNetworkStackId(), req.getMsoRequest(), + networkDeleted); + } + response = new DeleteNetworkResponse(req.getNetworkId(), networkDeleted.value, req.getMessageId()); + } catch (NetworkException e) { + logger.debug(EXCEPTION, e); + eresp = new DeleteNetworkError(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); + } + if (!req.isSynchronous()) { + // This is asynch, so POST response back to caller + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("DeleteNetworkTask exit: code={}, resp={}", getStatusCode(), getResponse()); + } + } + + @GET + @Path("{aaiNetworkId}") + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "QueryNetwork", response = Response.class, notes = "Queries an existing network") + @ApiResponses({@ApiResponse(code = 200, message = "Query network successful"), + @ApiResponse(code = 500, message = "Query network failed, examine entity object for details")}) + public Response queryNetwork( + @ApiParam(value = "cloudSiteId", required = false) @QueryParam("cloudSiteId") String cloudSiteId, + @ApiParam(value = "tenantId", required = false) @QueryParam("tenantId") String tenantId, + @ApiParam(value = "networkStackId", required = false) @QueryParam("networkStackId") String networkStackId, + @ApiParam(value = "skipAAI", required = false) @QueryParam("skipAAI") String skipAAI, + @ApiParam(value = "msoRequest.requestId", + required = false) @QueryParam("msoRequest.requestId") String requestId, + @ApiParam(value = "msoRequest.serviceInstanceId", + required = false) @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId, + @ApiParam(value = "aaiNetworkId", required = false) @PathParam("aaiNetworkId") String aaiNetworkId) { + // This request responds synchronously only + logger.debug("Query network enter:{}" + aaiNetworkId); + MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId); + + try { + int respStatus = HttpStatus.SC_OK; + QueryNetworkResponse resp = new QueryNetworkResponse(networkStackId, null, networkStackId, null, null); + Holder<Boolean> networkExists = new Holder<>(); Holder<String> networkId = new Holder<>(); Holder<String> neutronNetworkId = new Holder<>(); Holder<NetworkStatus> status = new Holder<>(); Holder<List<RouteTarget>> routeTargets = new Holder<>(); Holder<Map<String, String>> subnetIdMap = new Holder<>(); - adapter.queryNetworkContrail(cloudSiteId, tenantId, aaiNetworkId, msoRequest, - networkExists, networkId, neutronNetworkId, status, routeTargets, subnetIdMap); - - if (!networkExists.value) { - logger.debug("network not found"); - respStatus = HttpStatus.SC_NOT_FOUND; - } else { - logger.debug("network found {}, status={}", networkId.value, status.value); - resp.setNetworkExists(networkExists.value); - resp.setNetworkId(networkId.value); - resp.setNeutronNetworkId(neutronNetworkId.value); - resp.setNetworkStatus(status.value); - resp.setRouteTargets(routeTargets.value); - resp.setSubnetIdMap(subnetIdMap.value); - } - logger.debug("Query network exit"); - return Response - .status(respStatus) - .entity(new GenericEntity<QueryNetworkResponse>(resp) {}) - .build(); - } catch (NetworkException e) { - logger.error("{} {} Exception when query VNF ", MessageEnum.RA_QUERY_VNF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); - QueryNetworkError err = new QueryNetworkError(); - err.setMessage(e.getMessage()); - err.setCategory(MsoExceptionCategory.INTERNAL); - return Response - .status(HttpStatus.SC_INTERNAL_SERVER_ERROR) - .entity(new GenericEntity<QueryNetworkError>(err) {}) - .build(); - } - } - - @DELETE - @Path("{aaiNetworkId}/rollback") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "RollbackNetwork", - response = Response.class, - notes = "Rollback an existing network") - @ApiResponses({ - @ApiResponse(code = 200, message = "Rollback network successful"), - @ApiResponse(code = 202, message = "Rollback network request has been accepted (async only)"), - @ApiResponse(code = 500, message = "Rollback network failed, examine entity object for details") }) - public Response rollbackNetwork( - @ApiParam(value = "RollbackNetworkRequest in JSON format", required = true) - RollbackNetworkRequest req) - { - logger.debug("rollbackNetwork enter: {}", req.toJsonString()); - RollbackNetworkTask task = new RollbackNetworkTask(req); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} Exception in rollbackNetwork ", MessageEnum.RA_ROLLBACK_NULL, - ErrorCode.BusinessProcesssError.getValue(), e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("rollbackNetwork exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class RollbackNetworkTask implements Runnable { - private final RollbackNetworkRequest req; - private RollbackNetworkResponse response = null; - private RollbackNetworkError eresp = null; - private boolean sendxml; - - public RollbackNetworkTask(RollbackNetworkRequest req) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<RollbackNetworkResponse>(response) {} - : new GenericEntity<RollbackNetworkError>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - @Override - public void run() { - logger.debug("RollbackNetworkTask start"); - try { - NetworkRollback nwr = req.getNetworkRollback(); - adapter.rollbackNetwork(nwr); - response = new RollbackNetworkResponse(true, req.getMessageId()); - } catch (NetworkException e) { - logger.debug(EXCEPTION, e); - eresp = new RollbackNetworkError(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); - } - if (!req.isSynchronous()) { - // This is asynch, so POST response back to caller - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("RollbackNetworkTask exit: code={}, resp={}", getStatusCode(), getResponse()); - } - } - - @PUT - @Path("{aaiNetworkId}") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "UpdateNetwork", - response = Response.class, - notes = "Update an existing network") - @ApiResponses({ - @ApiResponse(code = 200, message = "Update network successful"), - @ApiResponse(code = 202, message = "Update network request has been accepted (async only)"), - @ApiResponse(code = 500, message = "Update network failed, examine entity object for details") }) - public Response updateNetwork( - @ApiParam(value = "aaiNetworkId", required = true) - @PathParam("aaiNetworkId") String aaiNetworkId, - @ApiParam(value = "UpdateNetworkRequest in JSON format", required = true) - UpdateNetworkRequest req) - { - logger.debug("updateNetwork enter: {}", req.toJsonString()); - if (aaiNetworkId == null || !aaiNetworkId.equals(req.getNetworkId())) { - return Response - .status(HttpStatus.SC_BAD_REQUEST) - .type(MediaType.TEXT_PLAIN) - .entity("A&AI NetworkId in URL ("+aaiNetworkId+") does not match content ("+req.getNetworkId()+")") - .build(); - } - UpdateNetworkTask task = new UpdateNetworkTask(req); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} Exception in updateNetwork ", MessageEnum.RA_UPDATE_NETWORK_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("updateNetwork exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class UpdateNetworkTask implements Runnable { - private final UpdateNetworkRequest req; - private UpdateNetworkResponse response = null; - private UpdateNetworkError eresp = null; - private boolean sendxml; - - public UpdateNetworkTask(UpdateNetworkRequest req) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<UpdateNetworkResponse>(response) {} - : new GenericEntity<UpdateNetworkError>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - @Override - public void run() { - logger.debug("UpdateNetworkTask start"); - try { - Holder<Map<String, String>> subnetIdMap = new Holder<>(); - Holder<NetworkRollback> rollback = new Holder<> (); - HashMap<String, String> params = (HashMap<String, String>) req.getNetworkParams(); - if (params == null) { - params = new HashMap<String,String>(); - } - String shared = null; - String external = null; - - if (req.getCloudSiteId().equals(TESTING_KEYWORD)) { - subnetIdMap.value = testMap(); - NetworkRollback rb = new NetworkRollback (); - rb.setCloudId(req.getCloudSiteId()); - rb.setTenantId(req.getTenantId()); - rb.setMsoRequest(req.getMsoRequest()); - rollback.value = rb; - } else if (req.isContrailRequest()) { - ContrailNetwork ctn = req.getContrailNetwork(); - if (ctn == null) { - ctn = new ContrailNetwork(); - req.setContrailNetwork(ctn); - } - if (params.containsKey("shared")) { - shared = params.get("shared"); - } else { - if (ctn.getShared() != null) { - shared = ctn.getShared(); - } - } - if (params.containsKey("external")) { - external = params.get("external"); - } else { - if (ctn.getExternal() != null) { - external = ctn.getExternal(); - } - } - adapter.updateNetworkContrail( - req.getCloudSiteId(), - req.getTenantId(), - req.getNetworkType(), - req.getModelCustomizationUuid(), - req.getNetworkStackId(), - req.getNetworkName(), - req.getContrailNetwork().getRouteTargets(), - shared, - external, - req.getSubnets(), - params, - req.getContrailNetwork().getPolicyFqdns(), - req.getContrailNetwork().getRouteTableFqdns(), - req.getMsoRequest(), - subnetIdMap, - rollback); - } else { - ProviderVlanNetwork pvn = req.getProviderVlanNetwork(); - if (pvn == null) { - pvn = new ProviderVlanNetwork(); - req.setProviderVlanNetwork(pvn); - } - if (params.containsKey("shared")) { - shared = params.get("shared"); - } - if (params.containsKey("external")) { - external = params.get("external"); - } - adapter.updateNetwork( - req.getCloudSiteId(), - req.getTenantId(), - req.getNetworkType(), - req.getModelCustomizationUuid(), - req.getNetworkStackId(), - req.getNetworkName(), - req.getProviderVlanNetwork().getPhysicalNetworkName(), - req.getProviderVlanNetwork().getVlans(), - shared, - external, - req.getSubnets(), - params, - req.getMsoRequest(), - subnetIdMap, - rollback); - } - response = new UpdateNetworkResponse( - req.getNetworkId(), - null, // NeutronNetworkId is not available from an update - subnetIdMap.value, - req.getMessageId()); - } catch (NetworkException e) { - logger.debug(EXCEPTION, e); - eresp = new UpdateNetworkError(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); - } - if (!req.isSynchronous()) { - // This is asynch, so POST response back to caller - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("UpdateNetworkTask exit: code={}, resp={}", getStatusCode(), getResponse()); - } - } - - public static Map<String, String> testMap() { - Map<String, String> m = new HashMap<>(); - m.put("mickey", "7"); - m.put("clyde", "10"); - m.put("wayne", "99"); - return m; + adapter.queryNetworkContrail(cloudSiteId, tenantId, aaiNetworkId, msoRequest, networkExists, networkId, + neutronNetworkId, status, routeTargets, subnetIdMap); + + if (!networkExists.value) { + logger.debug("network not found"); + respStatus = HttpStatus.SC_NOT_FOUND; + } else { + logger.debug("network found {}, status={}", networkId.value, status.value); + resp.setNetworkExists(networkExists.value); + resp.setNetworkId(networkId.value); + resp.setNeutronNetworkId(neutronNetworkId.value); + resp.setNetworkStatus(status.value); + resp.setRouteTargets(routeTargets.value); + resp.setSubnetIdMap(subnetIdMap.value); + } + logger.debug("Query network exit"); + return Response.status(respStatus).entity(new GenericEntity<QueryNetworkResponse>(resp) {}).build(); + } catch (NetworkException e) { + logger.error("{} {} Exception when query VNF ", MessageEnum.RA_QUERY_VNF_ERR, + ErrorCode.BusinessProcesssError.getValue(), e); + QueryNetworkError err = new QueryNetworkError(); + err.setMessage(e.getMessage()); + err.setCategory(MsoExceptionCategory.INTERNAL); + return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR) + .entity(new GenericEntity<QueryNetworkError>(err) {}).build(); + } + } + + @DELETE + @Path("{aaiNetworkId}/rollback") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "RollbackNetwork", response = Response.class, notes = "Rollback an existing network") + @ApiResponses({@ApiResponse(code = 200, message = "Rollback network successful"), + @ApiResponse(code = 202, message = "Rollback network request has been accepted (async only)"), + @ApiResponse(code = 500, message = "Rollback network failed, examine entity object for details")}) + public Response rollbackNetwork( + @ApiParam(value = "RollbackNetworkRequest in JSON format", required = true) RollbackNetworkRequest req) { + logger.debug("rollbackNetwork enter: {}", req.toJsonString()); + RollbackNetworkTask task = new RollbackNetworkTask(req); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling create, send generic failure as sync resp to caller + logger.error("{} {} Exception in rollbackNetwork ", MessageEnum.RA_ROLLBACK_NULL, + ErrorCode.BusinessProcesssError.getValue(), e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("rollbackNetwork exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class RollbackNetworkTask implements Runnable { + private final RollbackNetworkRequest req; + private RollbackNetworkResponse response = null; + private RollbackNetworkError eresp = null; + private boolean sendxml; + + public RollbackNetworkTask(RollbackNetworkRequest req) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<RollbackNetworkResponse>(response) {} + : new GenericEntity<RollbackNetworkError>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + logger.debug("RollbackNetworkTask start"); + try { + NetworkRollback nwr = req.getNetworkRollback(); + adapter.rollbackNetwork(nwr); + response = new RollbackNetworkResponse(true, req.getMessageId()); + } catch (NetworkException e) { + logger.debug(EXCEPTION, e); + eresp = new RollbackNetworkError(e.getMessage(), MsoExceptionCategory.INTERNAL, true, + req.getMessageId()); + } + if (!req.isSynchronous()) { + // This is asynch, so POST response back to caller + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("RollbackNetworkTask exit: code={}, resp={}", getStatusCode(), getResponse()); + } + } + + @PUT + @Path("{aaiNetworkId}") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "UpdateNetwork", response = Response.class, notes = "Update an existing network") + @ApiResponses({@ApiResponse(code = 200, message = "Update network successful"), + @ApiResponse(code = 202, message = "Update network request has been accepted (async only)"), + @ApiResponse(code = 500, message = "Update network failed, examine entity object for details")}) + public Response updateNetwork( + @ApiParam(value = "aaiNetworkId", required = true) @PathParam("aaiNetworkId") String aaiNetworkId, + @ApiParam(value = "UpdateNetworkRequest in JSON format", required = true) UpdateNetworkRequest req) { + logger.debug("updateNetwork enter: {}", req.toJsonString()); + if (aaiNetworkId == null || !aaiNetworkId.equals(req.getNetworkId())) { + return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity( + "A&AI NetworkId in URL (" + aaiNetworkId + ") does not match content (" + req.getNetworkId() + ")") + .build(); + } + UpdateNetworkTask task = new UpdateNetworkTask(req); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling create, send generic failure as sync resp to caller + logger.error("{} {} Exception in updateNetwork ", MessageEnum.RA_UPDATE_NETWORK_ERR, + ErrorCode.BusinessProcesssError.getValue(), e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("updateNetwork exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class UpdateNetworkTask implements Runnable { + private final UpdateNetworkRequest req; + private UpdateNetworkResponse response = null; + private UpdateNetworkError eresp = null; + private boolean sendxml; + + public UpdateNetworkTask(UpdateNetworkRequest req) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<UpdateNetworkResponse>(response) {} + : new GenericEntity<UpdateNetworkError>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + logger.debug("UpdateNetworkTask start"); + try { + Holder<Map<String, String>> subnetIdMap = new Holder<>(); + Holder<NetworkRollback> rollback = new Holder<>(); + HashMap<String, String> params = (HashMap<String, String>) req.getNetworkParams(); + if (params == null) { + params = new HashMap<String, String>(); + } + String shared = null; + String external = null; + + if (req.getCloudSiteId().equals(TESTING_KEYWORD)) { + subnetIdMap.value = testMap(); + NetworkRollback rb = new NetworkRollback(); + rb.setCloudId(req.getCloudSiteId()); + rb.setTenantId(req.getTenantId()); + rb.setMsoRequest(req.getMsoRequest()); + rollback.value = rb; + } else if (req.isContrailRequest()) { + ContrailNetwork ctn = req.getContrailNetwork(); + if (ctn == null) { + ctn = new ContrailNetwork(); + req.setContrailNetwork(ctn); + } + if (params.containsKey("shared")) { + shared = params.get("shared"); + } else { + if (ctn.getShared() != null) { + shared = ctn.getShared(); + } + } + if (params.containsKey("external")) { + external = params.get("external"); + } else { + if (ctn.getExternal() != null) { + external = ctn.getExternal(); + } + } + adapter.updateNetworkContrail(req.getCloudSiteId(), req.getTenantId(), req.getNetworkType(), + req.getModelCustomizationUuid(), req.getNetworkStackId(), req.getNetworkName(), + req.getContrailNetwork().getRouteTargets(), shared, external, req.getSubnets(), params, + req.getContrailNetwork().getPolicyFqdns(), req.getContrailNetwork().getRouteTableFqdns(), + req.getMsoRequest(), subnetIdMap, rollback); + } else { + ProviderVlanNetwork pvn = req.getProviderVlanNetwork(); + if (pvn == null) { + pvn = new ProviderVlanNetwork(); + req.setProviderVlanNetwork(pvn); + } + if (params.containsKey("shared")) { + shared = params.get("shared"); + } + if (params.containsKey("external")) { + external = params.get("external"); + } + adapter.updateNetwork(req.getCloudSiteId(), req.getTenantId(), req.getNetworkType(), + req.getModelCustomizationUuid(), req.getNetworkStackId(), req.getNetworkName(), + req.getProviderVlanNetwork().getPhysicalNetworkName(), + req.getProviderVlanNetwork().getVlans(), shared, external, req.getSubnets(), params, + req.getMsoRequest(), subnetIdMap, rollback); + } + response = new UpdateNetworkResponse(req.getNetworkId(), null, // NeutronNetworkId is not available from + // an update + subnetIdMap.value, req.getMessageId()); + } catch (NetworkException e) { + logger.debug(EXCEPTION, e); + eresp = new UpdateNetworkError(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); + } + if (!req.isSynchronous()) { + // This is asynch, so POST response back to caller + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("UpdateNetworkTask exit: code={}, resp={}", getStatusCode(), getResponse()); + } + } + + public static Map<String, String> testMap() { + Map<String, String> m = new HashMap<>(); + m.put("mickey", "7"); + m.put("clyde", "10"); + m.put("wayne", "99"); + return m; } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/CreateNetworkNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/CreateNetworkNotification.java index fcce165d27..f30ccf2214 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/CreateNetworkNotification.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/CreateNetworkNotification.java @@ -24,7 +24,6 @@ package org.onap.so.adapters.network.async.client; import java.util.ArrayList; import java.util.List; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -32,9 +31,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for createNetworkNotification complex type. + * <p> + * Java class for createNetworkNotification complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="createNetworkNotification"> @@ -79,16 +80,8 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "createNetworkNotification", propOrder = { - "messageId", - "completed", - "exception", - "errorMessage", - "networkId", - "neutronNetworkId", - "subnetIdMap", - "rollback" -}) +@XmlType(name = "createNetworkNotification", propOrder = {"messageId", "completed", "exception", "errorMessage", + "networkId", "neutronNetworkId", "subnetIdMap", "rollback"}) public class CreateNetworkNotification { @XmlElement(required = true) @@ -104,10 +97,8 @@ public class CreateNetworkNotification { /** * Gets the value of the messageId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getMessageId() { return messageId; @@ -116,10 +107,8 @@ public class CreateNetworkNotification { /** * Sets the value of the messageId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setMessageId(String value) { this.messageId = value; @@ -144,10 +133,8 @@ public class CreateNetworkNotification { /** * Gets the value of the exception property. * - * @return - * possible object is - * {@link MsoExceptionCategory } - * + * @return possible object is {@link MsoExceptionCategory } + * */ public MsoExceptionCategory getException() { return exception; @@ -156,10 +143,8 @@ public class CreateNetworkNotification { /** * Sets the value of the exception property. * - * @param value - * allowed object is - * {@link MsoExceptionCategory } - * + * @param value allowed object is {@link MsoExceptionCategory } + * */ public void setException(MsoExceptionCategory value) { this.exception = value; @@ -168,10 +153,8 @@ public class CreateNetworkNotification { /** * Gets the value of the errorMessage property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getErrorMessage() { return errorMessage; @@ -180,10 +163,8 @@ public class CreateNetworkNotification { /** * Sets the value of the errorMessage property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setErrorMessage(String value) { this.errorMessage = value; @@ -192,10 +173,8 @@ public class CreateNetworkNotification { /** * Gets the value of the networkId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getNetworkId() { return networkId; @@ -204,10 +183,8 @@ public class CreateNetworkNotification { /** * Sets the value of the networkId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setNetworkId(String value) { this.networkId = value; @@ -216,10 +193,8 @@ public class CreateNetworkNotification { /** * Gets the value of the neutronNetworkId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getNeutronNetworkId() { return neutronNetworkId; @@ -228,10 +203,8 @@ public class CreateNetworkNotification { /** * Sets the value of the neutronNetworkId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setNeutronNetworkId(String value) { this.neutronNetworkId = value; @@ -240,10 +213,8 @@ public class CreateNetworkNotification { /** * Gets the value of the subnetIdMap property. * - * @return - * possible object is - * {@link CreateNetworkNotification.SubnetIdMap } - * + * @return possible object is {@link CreateNetworkNotification.SubnetIdMap } + * */ public CreateNetworkNotification.SubnetIdMap getSubnetIdMap() { return subnetIdMap; @@ -252,10 +223,8 @@ public class CreateNetworkNotification { /** * Sets the value of the subnetIdMap property. * - * @param value - * allowed object is - * {@link CreateNetworkNotification.SubnetIdMap } - * + * @param value allowed object is {@link CreateNetworkNotification.SubnetIdMap } + * */ public void setSubnetIdMap(CreateNetworkNotification.SubnetIdMap value) { this.subnetIdMap = value; @@ -264,10 +233,8 @@ public class CreateNetworkNotification { /** * Gets the value of the rollback property. * - * @return - * possible object is - * {@link NetworkRollback } - * + * @return possible object is {@link NetworkRollback } + * */ public NetworkRollback getRollback() { return rollback; @@ -276,10 +243,8 @@ public class CreateNetworkNotification { /** * Sets the value of the rollback property. * - * @param value - * allowed object is - * {@link NetworkRollback } - * + * @param value allowed object is {@link NetworkRollback } + * */ public void setRollback(NetworkRollback value) { this.rollback = value; @@ -287,9 +252,11 @@ public class CreateNetworkNotification { /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -317,9 +284,7 @@ public class CreateNetworkNotification { * */ @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "entry" - }) + @XmlType(name = "", propOrder = {"entry"}) public static class SubnetIdMap { protected List<CreateNetworkNotification.SubnetIdMap.Entry> entry; @@ -328,21 +293,20 @@ public class CreateNetworkNotification { * Gets the value of the entry property. * * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the entry property. + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you + * make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> + * method for the entry property. * * <p> * For example, to add a new item, do as follows: + * * <pre> - * getEntry().add(newItem); + * getEntry().add(newItem); * </pre> * * * <p> - * Objects of the following type(s) are allowed in the list - * {@link CreateNetworkNotification.SubnetIdMap.Entry } + * Objects of the following type(s) are allowed in the list {@link CreateNetworkNotification.SubnetIdMap.Entry } * * */ @@ -355,9 +319,11 @@ public class CreateNetworkNotification { /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -375,10 +341,7 @@ public class CreateNetworkNotification { * */ @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "key", - "value" - }) + @XmlType(name = "", propOrder = {"key", "value"}) public static class Entry { protected String key; @@ -387,10 +350,8 @@ public class CreateNetworkNotification { /** * Gets the value of the key property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getKey() { return key; @@ -399,10 +360,8 @@ public class CreateNetworkNotification { /** * Sets the value of the key property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setKey(String value) { this.key = value; @@ -411,10 +370,8 @@ public class CreateNetworkNotification { /** * Gets the value of the value property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getValue() { return value; @@ -423,10 +380,8 @@ public class CreateNetworkNotification { /** * Sets the value of the value property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setValue(String value) { this.value = value; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/CreateNetworkNotificationResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/CreateNetworkNotificationResponse.java index a0e40c0e6a..4ade875193 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/CreateNetworkNotificationResponse.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/CreateNetworkNotificationResponse.java @@ -26,9 +26,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for createNetworkNotificationResponse complex type. + * <p> + * Java class for createNetworkNotificationResponse complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="createNetworkNotificationResponse"> diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/DeleteNetworkNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/DeleteNetworkNotification.java index d4f992a9b4..ff94be9156 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/DeleteNetworkNotification.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/DeleteNetworkNotification.java @@ -27,9 +27,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for deleteNetworkNotification complex type. + * <p> + * Java class for deleteNetworkNotification complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="deleteNetworkNotification"> @@ -50,13 +52,8 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "deleteNetworkNotification", propOrder = { - "messageId", - "completed", - "exception", - "errorMessage", - "networkDeleted" -}) +@XmlType(name = "deleteNetworkNotification", + propOrder = {"messageId", "completed", "exception", "errorMessage", "networkDeleted"}) public class DeleteNetworkNotification { @XmlElement(required = true) @@ -69,10 +66,8 @@ public class DeleteNetworkNotification { /** * Gets the value of the messageId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getMessageId() { return messageId; @@ -81,10 +76,8 @@ public class DeleteNetworkNotification { /** * Sets the value of the messageId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setMessageId(String value) { this.messageId = value; @@ -109,10 +102,8 @@ public class DeleteNetworkNotification { /** * Gets the value of the exception property. * - * @return - * possible object is - * {@link MsoExceptionCategory } - * + * @return possible object is {@link MsoExceptionCategory } + * */ public MsoExceptionCategory getException() { return exception; @@ -121,10 +112,8 @@ public class DeleteNetworkNotification { /** * Sets the value of the exception property. * - * @param value - * allowed object is - * {@link MsoExceptionCategory } - * + * @param value allowed object is {@link MsoExceptionCategory } + * */ public void setException(MsoExceptionCategory value) { this.exception = value; @@ -133,10 +122,8 @@ public class DeleteNetworkNotification { /** * Gets the value of the errorMessage property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getErrorMessage() { return errorMessage; @@ -145,10 +132,8 @@ public class DeleteNetworkNotification { /** * Sets the value of the errorMessage property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setErrorMessage(String value) { this.errorMessage = value; @@ -157,10 +142,8 @@ public class DeleteNetworkNotification { /** * Gets the value of the networkDeleted property. * - * @return - * possible object is - * {@link Boolean } - * + * @return possible object is {@link Boolean } + * */ public Boolean isNetworkDeleted() { return networkDeleted; @@ -169,10 +152,8 @@ public class DeleteNetworkNotification { /** * Sets the value of the networkDeleted property. * - * @param value - * allowed object is - * {@link Boolean } - * + * @param value allowed object is {@link Boolean } + * */ public void setNetworkDeleted(Boolean value) { this.networkDeleted = value; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/DeleteNetworkNotificationResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/DeleteNetworkNotificationResponse.java index 76eb8115d5..7f7d0ae569 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/DeleteNetworkNotificationResponse.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/DeleteNetworkNotificationResponse.java @@ -26,9 +26,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for deleteNetworkNotificationResponse complex type. + * <p> + * Java class for deleteNetworkNotificationResponse complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="deleteNetworkNotificationResponse"> diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/MsoExceptionCategory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/MsoExceptionCategory.java index 8c18a59e68..ad3c541730 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/MsoExceptionCategory.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/MsoExceptionCategory.java @@ -25,10 +25,13 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for msoExceptionCategory. + * <p> + * Java class for msoExceptionCategory. * - * <p>The following schema fragment specifies the expected content contained within this class. * <p> + * The following schema fragment specifies the expected content contained within this class. + * <p> + * * <pre> * <simpleType name="msoExceptionCategory"> * <restriction base="{http://www.w3.org/2001/XMLSchema}string"> @@ -45,10 +48,7 @@ import javax.xml.bind.annotation.XmlType; @XmlEnum public enum MsoExceptionCategory { - OPENSTACK, - IO, - INTERNAL, - USERDATA; + OPENSTACK, IO, INTERNAL, USERDATA; public String value() { return name(); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/MsoRequest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/MsoRequest.java index aa6f34f2e0..90ae448660 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/MsoRequest.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/MsoRequest.java @@ -26,9 +26,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for msoRequest complex type. + * <p> + * Java class for msoRequest complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="msoRequest"> @@ -46,10 +48,7 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "msoRequest", propOrder = { - "requestId", - "serviceInstanceId" -}) +@XmlType(name = "msoRequest", propOrder = {"requestId", "serviceInstanceId"}) public class MsoRequest { protected String requestId; @@ -58,10 +57,8 @@ public class MsoRequest { /** * Gets the value of the requestId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getRequestId() { return requestId; @@ -70,10 +67,8 @@ public class MsoRequest { /** * Sets the value of the requestId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setRequestId(String value) { this.requestId = value; @@ -82,10 +77,8 @@ public class MsoRequest { /** * Gets the value of the serviceInstanceId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getServiceInstanceId() { return serviceInstanceId; @@ -94,10 +87,8 @@ public class MsoRequest { /** * Sets the value of the serviceInstanceId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setServiceInstanceId(String value) { this.serviceInstanceId = value; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkAdapterNotify.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkAdapterNotify.java index 0433aab0cc..8fb62cc32e 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkAdapterNotify.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkAdapterNotify.java @@ -21,7 +21,6 @@ package org.onap.so.adapters.network.async.client; import java.util.List; - import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; @@ -32,15 +31,11 @@ import javax.xml.ws.ResponseWrapper; /** - * This class was generated by the JAX-WS RI. - * JAX-WS RI 2.2.9-b14002 - * Generated source version: 2.2 + * This class was generated by the JAX-WS RI. JAX-WS RI 2.2.9-b14002 Generated source version: 2.2 * */ @WebService(name = "networkAdapterNotify", targetNamespace = "http://org.onap.so/networkNotify") -@XmlSeeAlso({ - ObjectFactory.class -}) +@XmlSeeAlso({ObjectFactory.class}) public interface NetworkAdapterNotify { @@ -52,18 +47,17 @@ public interface NetworkAdapterNotify { * @param completed */ @WebMethod - @RequestWrapper(localName = "rollbackNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.RollbackNetworkNotification") - @ResponseWrapper(localName = "rollbackNetworkNotificationResponse", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.RollbackNetworkNotificationResponse") - @Action(input = "http://org.onap.so/notify/adapterNotify/rollbackNetworkNotificationRequest", output = "http://org.onap.so/notify/adapterNotify/rollbackNetworkNotificationResponse") - public void rollbackNetworkNotification( - @WebParam(name = "messageId", targetNamespace = "") - String messageId, - @WebParam(name = "completed", targetNamespace = "") - boolean completed, - @WebParam(name = "exception", targetNamespace = "") - MsoExceptionCategory exception, - @WebParam(name = "errorMessage", targetNamespace = "") - String errorMessage); + @RequestWrapper(localName = "rollbackNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify", + className = "org.onap.so.adapters.network.async.client.RollbackNetworkNotification") + @ResponseWrapper(localName = "rollbackNetworkNotificationResponse", + targetNamespace = "http://org.onap.so/networkNotify", + className = "org.onap.so.adapters.network.async.client.RollbackNetworkNotificationResponse") + @Action(input = "http://org.onap.so/notify/adapterNotify/rollbackNetworkNotificationRequest", + output = "http://org.onap.so/notify/adapterNotify/rollbackNetworkNotificationResponse") + public void rollbackNetworkNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId, + @WebParam(name = "completed", targetNamespace = "") boolean completed, + @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception, + @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage); /** * @@ -79,30 +73,23 @@ public interface NetworkAdapterNotify { * @param subnetIdMap */ @WebMethod - @RequestWrapper(localName = "queryNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.QueryNetworkNotification") - @ResponseWrapper(localName = "queryNetworkNotificationResponse", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.QueryNetworkNotificationResponse") - @Action(input = "http://org.onap.so/notify/adapterNotify/queryNetworkNotificationRequest", output = "http://org.onap.so/notify/adapterNotify/queryNetworkNotificationResponse") - public void queryNetworkNotification( - @WebParam(name = "messageId", targetNamespace = "") - String messageId, - @WebParam(name = "completed", targetNamespace = "") - boolean completed, - @WebParam(name = "exception", targetNamespace = "") - MsoExceptionCategory exception, - @WebParam(name = "errorMessage", targetNamespace = "") - String errorMessage, - @WebParam(name = "networkExists", targetNamespace = "") - Boolean networkExists, - @WebParam(name = "networkId", targetNamespace = "") - String networkId, - @WebParam(name = "neutronNetworkId", targetNamespace = "") - String neutronNetworkId, - @WebParam(name = "status", targetNamespace = "") - NetworkStatus status, - @WebParam(name = "vlans", targetNamespace = "") - List<Integer> vlans, - @WebParam(name = "subnetIdMap", targetNamespace = "") - org.onap.so.adapters.network.async.client.QueryNetworkNotification.SubnetIdMap subnetIdMap); + @RequestWrapper(localName = "queryNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify", + className = "org.onap.so.adapters.network.async.client.QueryNetworkNotification") + @ResponseWrapper(localName = "queryNetworkNotificationResponse", + targetNamespace = "http://org.onap.so/networkNotify", + className = "org.onap.so.adapters.network.async.client.QueryNetworkNotificationResponse") + @Action(input = "http://org.onap.so/notify/adapterNotify/queryNetworkNotificationRequest", + output = "http://org.onap.so/notify/adapterNotify/queryNetworkNotificationResponse") + public void queryNetworkNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId, + @WebParam(name = "completed", targetNamespace = "") boolean completed, + @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception, + @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage, + @WebParam(name = "networkExists", targetNamespace = "") Boolean networkExists, + @WebParam(name = "networkId", targetNamespace = "") String networkId, + @WebParam(name = "neutronNetworkId", targetNamespace = "") String neutronNetworkId, + @WebParam(name = "status", targetNamespace = "") NetworkStatus status, + @WebParam(name = "vlans", targetNamespace = "") List<Integer> vlans, @WebParam(name = "subnetIdMap", + targetNamespace = "") org.onap.so.adapters.network.async.client.QueryNetworkNotification.SubnetIdMap subnetIdMap); /** * @@ -116,26 +103,22 @@ public interface NetworkAdapterNotify { * @param subnetIdMap */ @WebMethod - @RequestWrapper(localName = "createNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.CreateNetworkNotification") - @ResponseWrapper(localName = "createNetworkNotificationResponse", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.CreateNetworkNotificationResponse") - @Action(input = "http://org.onap.so/notify/adapterNotify/createNetworkNotificationRequest", output = "http://org.onap.so/notify/adapterNotify/createNetworkNotificationResponse") - public void createNetworkNotification( - @WebParam(name = "messageId", targetNamespace = "") - String messageId, - @WebParam(name = "completed", targetNamespace = "") - boolean completed, - @WebParam(name = "exception", targetNamespace = "") - MsoExceptionCategory exception, - @WebParam(name = "errorMessage", targetNamespace = "") - String errorMessage, - @WebParam(name = "networkId", targetNamespace = "") - String networkId, - @WebParam(name = "neutronNetworkId", targetNamespace = "") - String neutronNetworkId, - @WebParam(name = "subnetIdMap", targetNamespace = "") - org.onap.so.adapters.network.async.client.CreateNetworkNotification.SubnetIdMap subnetIdMap, - @WebParam(name = "rollback", targetNamespace = "") - NetworkRollback rollback); + @RequestWrapper(localName = "createNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify", + className = "org.onap.so.adapters.network.async.client.CreateNetworkNotification") + @ResponseWrapper(localName = "createNetworkNotificationResponse", + targetNamespace = "http://org.onap.so/networkNotify", + className = "org.onap.so.adapters.network.async.client.CreateNetworkNotificationResponse") + @Action(input = "http://org.onap.so/notify/adapterNotify/createNetworkNotificationRequest", + output = "http://org.onap.so/notify/adapterNotify/createNetworkNotificationResponse") + public void createNetworkNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId, + @WebParam(name = "completed", targetNamespace = "") boolean completed, + @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception, + @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage, + @WebParam(name = "networkId", targetNamespace = "") String networkId, + @WebParam(name = "neutronNetworkId", targetNamespace = "") String neutronNetworkId, + @WebParam(name = "subnetIdMap", + targetNamespace = "") org.onap.so.adapters.network.async.client.CreateNetworkNotification.SubnetIdMap subnetIdMap, + @WebParam(name = "rollback", targetNamespace = "") NetworkRollback rollback); /** * @@ -146,20 +129,18 @@ public interface NetworkAdapterNotify { * @param completed */ @WebMethod - @RequestWrapper(localName = "deleteNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.DeleteNetworkNotification") - @ResponseWrapper(localName = "deleteNetworkNotificationResponse", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.DeleteNetworkNotificationResponse") - @Action(input = "http://org.onap.so/notify/adapterNotify/deleteNetworkNotificationRequest", output = "http://org.onap.so/notify/adapterNotify/deleteNetworkNotificationResponse") - public void deleteNetworkNotification( - @WebParam(name = "messageId", targetNamespace = "") - String messageId, - @WebParam(name = "completed", targetNamespace = "") - boolean completed, - @WebParam(name = "exception", targetNamespace = "") - MsoExceptionCategory exception, - @WebParam(name = "errorMessage", targetNamespace = "") - String errorMessage, - @WebParam(name = "networkDeleted", targetNamespace = "") - Boolean networkDeleted); + @RequestWrapper(localName = "deleteNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify", + className = "org.onap.so.adapters.network.async.client.DeleteNetworkNotification") + @ResponseWrapper(localName = "deleteNetworkNotificationResponse", + targetNamespace = "http://org.onap.so/networkNotify", + className = "org.onap.so.adapters.network.async.client.DeleteNetworkNotificationResponse") + @Action(input = "http://org.onap.so/notify/adapterNotify/deleteNetworkNotificationRequest", + output = "http://org.onap.so/notify/adapterNotify/deleteNetworkNotificationResponse") + public void deleteNetworkNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId, + @WebParam(name = "completed", targetNamespace = "") boolean completed, + @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception, + @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage, + @WebParam(name = "networkDeleted", targetNamespace = "") Boolean networkDeleted); /** * @@ -171,21 +152,19 @@ public interface NetworkAdapterNotify { * @param subnetIdMap */ @WebMethod - @RequestWrapper(localName = "updateNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.UpdateNetworkNotification") - @ResponseWrapper(localName = "updateNetworkNotificationResponse", targetNamespace = "http://org.onap.so/networkNotify", className = "org.onap.so.adapters.network.async.client.UpdateNetworkNotificationResponse") - @Action(input = "http://org.onap.so/notify/adapterNotify/updateNetworkNotificationRequest", output = "http://org.onap.so/notify/adapterNotify/updateNetworkNotificationResponse") - public void updateNetworkNotification( - @WebParam(name = "messageId", targetNamespace = "") - String messageId, - @WebParam(name = "completed", targetNamespace = "") - boolean completed, - @WebParam(name = "exception", targetNamespace = "") - MsoExceptionCategory exception, - @WebParam(name = "errorMessage", targetNamespace = "") - String errorMessage, - @WebParam(name = "subnetIdMap", targetNamespace = "") - org.onap.so.adapters.network.async.client.UpdateNetworkNotification.SubnetIdMap subnetIdMap, - @WebParam(name = "rollback", targetNamespace = "") - NetworkRollback rollback); + @RequestWrapper(localName = "updateNetworkNotification", targetNamespace = "http://org.onap.so/networkNotify", + className = "org.onap.so.adapters.network.async.client.UpdateNetworkNotification") + @ResponseWrapper(localName = "updateNetworkNotificationResponse", + targetNamespace = "http://org.onap.so/networkNotify", + className = "org.onap.so.adapters.network.async.client.UpdateNetworkNotificationResponse") + @Action(input = "http://org.onap.so/notify/adapterNotify/updateNetworkNotificationRequest", + output = "http://org.onap.so/notify/adapterNotify/updateNetworkNotificationResponse") + public void updateNetworkNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId, + @WebParam(name = "completed", targetNamespace = "") boolean completed, + @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception, + @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage, + @WebParam(name = "subnetIdMap", + targetNamespace = "") org.onap.so.adapters.network.async.client.UpdateNetworkNotification.SubnetIdMap subnetIdMap, + @WebParam(name = "rollback", targetNamespace = "") NetworkRollback rollback); } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkAdapterNotify_Service.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkAdapterNotify_Service.java index f408f227c6..c275073c46 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkAdapterNotify_Service.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkAdapterNotify_Service.java @@ -23,7 +23,6 @@ package org.onap.so.adapters.network.async.client; import java.net.URL; - import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.WebEndpoint; @@ -33,26 +32,26 @@ import javax.xml.ws.WebServiceFeature; /** - * This class was generated by the JAX-WS RI. - * JAX-WS RI 2.2.9-b14002 - * Generated source version: 2.2 + * This class was generated by the JAX-WS RI. JAX-WS RI 2.2.9-b14002 Generated source version: 2.2 * */ -@WebServiceClient(name = "networkAdapterNotify", targetNamespace = "http://org.onap.so/networkNotify", wsdlLocation = "/NetworkAdapterNotify.wsdl") -public class NetworkAdapterNotify_Service - extends Service -{ +@WebServiceClient(name = "networkAdapterNotify", targetNamespace = "http://org.onap.so/networkNotify", + wsdlLocation = "/NetworkAdapterNotify.wsdl") +public class NetworkAdapterNotify_Service extends Service { private static final URL NETWORKADAPTERNOTIFY_WSDL_LOCATION; private static final WebServiceException NETWORKADAPTERNOTIFY_EXCEPTION; - private static final String URL="http://org.onap.so/networkNotify"; + private static final String URL = "http://org.onap.so/networkNotify"; private static final QName NETWORKADAPTERNOTIFY_QNAME = new QName(URL, "networkAdapterNotify"); static { - NETWORKADAPTERNOTIFY_WSDL_LOCATION = org.onap.so.adapters.network.async.client.NetworkAdapterNotify_Service.class.getResource("/NetworkAdapterNotify.wsdl"); + NETWORKADAPTERNOTIFY_WSDL_LOCATION = + org.onap.so.adapters.network.async.client.NetworkAdapterNotify_Service.class + .getResource("/NetworkAdapterNotify.wsdl"); WebServiceException e = null; if (NETWORKADAPTERNOTIFY_WSDL_LOCATION == null) { - e = new WebServiceException("Cannot find '/NetworkAdapterNotify.wsdl' wsdl. Place the resource correctly in the classpath."); + e = new WebServiceException( + "Cannot find '/NetworkAdapterNotify.wsdl' wsdl. Place the resource correctly in the classpath."); } NETWORKADAPTERNOTIFY_EXCEPTION = e; } @@ -83,8 +82,7 @@ public class NetworkAdapterNotify_Service /** * - * @return - * returns NetworkAdapterNotify + * @return returns NetworkAdapterNotify */ @WebEndpoint(name = "MsoNetworkAdapterAsyncImplPort") public NetworkAdapterNotify getMsoNetworkAdapterAsyncImplPort() { @@ -93,10 +91,9 @@ public class NetworkAdapterNotify_Service /** * - * @param features - * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. - * @return - * returns NetworkAdapterNotify + * @param features A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features + * not in the <code>features</code> parameter will have their default values. + * @return returns NetworkAdapterNotify */ @WebEndpoint(name = "MsoNetworkAdapterAsyncImplPort") public NetworkAdapterNotify getMsoNetworkAdapterAsyncImplPort(WebServiceFeature... features) { @@ -104,7 +101,7 @@ public class NetworkAdapterNotify_Service } private static URL __getWsdlLocation() { - if (NETWORKADAPTERNOTIFY_EXCEPTION!= null) { + if (NETWORKADAPTERNOTIFY_EXCEPTION != null) { throw NETWORKADAPTERNOTIFY_EXCEPTION; } return NETWORKADAPTERNOTIFY_WSDL_LOCATION; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkRollback.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkRollback.java index e7ace110ac..c51a21d5f0 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkRollback.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkRollback.java @@ -24,7 +24,6 @@ package org.onap.so.adapters.network.async.client; import java.util.ArrayList; import java.util.List; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -32,9 +31,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for networkRollback complex type. + * <p> + * Java class for networkRollback complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="networkRollback"> @@ -62,20 +63,9 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "networkRollback", propOrder = { - "cloudId", - "msoRequest", - "networkCreated", - "networkId", - "networkStackId", - "networkName", - "networkType", - "networkUpdated", - "neutronNetworkId", - "physicalNetwork", - "tenantId", - "vlans" -}) +@XmlType(name = "networkRollback", + propOrder = {"cloudId", "msoRequest", "networkCreated", "networkId", "networkStackId", "networkName", + "networkType", "networkUpdated", "neutronNetworkId", "physicalNetwork", "tenantId", "vlans"}) public class NetworkRollback { protected String cloudId; @@ -95,10 +85,8 @@ public class NetworkRollback { /** * Gets the value of the cloudId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getCloudId() { return cloudId; @@ -107,10 +95,8 @@ public class NetworkRollback { /** * Sets the value of the cloudId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setCloudId(String value) { this.cloudId = value; @@ -119,10 +105,8 @@ public class NetworkRollback { /** * Gets the value of the msoRequest property. * - * @return - * possible object is - * {@link MsoRequest } - * + * @return possible object is {@link MsoRequest } + * */ public MsoRequest getMsoRequest() { return msoRequest; @@ -131,10 +115,8 @@ public class NetworkRollback { /** * Sets the value of the msoRequest property. * - * @param value - * allowed object is - * {@link MsoRequest } - * + * @param value allowed object is {@link MsoRequest } + * */ public void setMsoRequest(MsoRequest value) { this.msoRequest = value; @@ -159,10 +141,8 @@ public class NetworkRollback { /** * Gets the value of the networkId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getNetworkId() { return networkId; @@ -171,10 +151,8 @@ public class NetworkRollback { /** * Sets the value of the networkId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setNetworkId(String value) { this.networkId = value; @@ -183,10 +161,8 @@ public class NetworkRollback { /** * Gets the value of the networkStackId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getNetworkStackId() { return networkStackId; @@ -195,10 +171,8 @@ public class NetworkRollback { /** * Sets the value of the networkStackId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setNetworkStackId(String value) { this.networkStackId = value; @@ -207,10 +181,8 @@ public class NetworkRollback { /** * Gets the value of the networkName property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getNetworkName() { return networkName; @@ -219,10 +191,8 @@ public class NetworkRollback { /** * Sets the value of the networkName property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setNetworkName(String value) { this.networkName = value; @@ -231,10 +201,8 @@ public class NetworkRollback { /** * Gets the value of the networkType property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getNetworkType() { return networkType; @@ -243,10 +211,8 @@ public class NetworkRollback { /** * Sets the value of the networkType property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setNetworkType(String value) { this.networkType = value; @@ -271,10 +237,8 @@ public class NetworkRollback { /** * Gets the value of the neutronNetworkId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getNeutronNetworkId() { return neutronNetworkId; @@ -283,10 +247,8 @@ public class NetworkRollback { /** * Sets the value of the neutronNetworkId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setNeutronNetworkId(String value) { this.neutronNetworkId = value; @@ -295,10 +257,8 @@ public class NetworkRollback { /** * Gets the value of the physicalNetwork property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getPhysicalNetwork() { return physicalNetwork; @@ -307,10 +267,8 @@ public class NetworkRollback { /** * Sets the value of the physicalNetwork property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setPhysicalNetwork(String value) { this.physicalNetwork = value; @@ -319,10 +277,8 @@ public class NetworkRollback { /** * Gets the value of the tenantId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getTenantId() { return tenantId; @@ -331,10 +287,8 @@ public class NetworkRollback { /** * Sets the value of the tenantId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setTenantId(String value) { this.tenantId = value; @@ -344,21 +298,20 @@ public class NetworkRollback { * Gets the value of the vlans property. * * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the vlans property. + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to + * the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for + * the vlans property. * * <p> * For example, to add a new item, do as follows: + * * <pre> - * getVlans().add(newItem); + * getVlans().add(newItem); * </pre> * * * <p> - * Objects of the following type(s) are allowed in the list - * {@link Integer } + * Objects of the following type(s) are allowed in the list {@link Integer } * * */ diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkStatus.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkStatus.java index 982f214bd8..36641477c0 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkStatus.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/NetworkStatus.java @@ -25,10 +25,13 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for networkStatus. + * <p> + * Java class for networkStatus. * - * <p>The following schema fragment specifies the expected content contained within this class. * <p> + * The following schema fragment specifies the expected content contained within this class. + * <p> + * * <pre> * <simpleType name="networkStatus"> * <restriction base="{http://www.w3.org/2001/XMLSchema}string"> @@ -47,12 +50,7 @@ import javax.xml.bind.annotation.XmlType; @XmlEnum public enum NetworkStatus { - NOTFOUND, - ACTIVE, - DOWN, - BUILD, - ERROR, - UNKNOWN; + NOTFOUND, ACTIVE, DOWN, BUILD, ERROR, UNKNOWN; public String value() { return name(); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/ObjectFactory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/ObjectFactory.java index f2238fce78..81ccd8aa04 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/ObjectFactory.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/ObjectFactory.java @@ -27,40 +27,41 @@ import javax.xml.namespace.QName; /** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the org.onap.so.adapters.network.async.client package. - * <p>An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. + * This object contains factory methods for each Java content interface and Java element interface generated in the + * org.onap.so.adapters.network.async.client package. + * <p> + * An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content. + * The Java representation of XML content can consist of schema derived interfaces and classes representing the binding + * of schema type definitions, element declarations and model groups. Factory methods for each of these are provided in + * this class. * */ @XmlRegistry public class ObjectFactory { - - private static final String Url= "http://org.onap.so/networkNotify"; + + private static final String Url = "http://org.onap.so/networkNotify"; private static final QName _RollbackNetworkNotification_QNAME = new QName(Url, "rollbackNetworkNotification"); private static final QName _UpdateNetworkNotification_QNAME = new QName(Url, "updateNetworkNotification"); - private static final QName _QueryNetworkNotificationResponse_QNAME = new QName(Url, "queryNetworkNotificationResponse"); - private static final QName _UpdateNetworkNotificationResponse_QNAME = new QName(Url, "updateNetworkNotificationResponse"); - private static final QName _CreateNetworkNotificationResponse_QNAME = new QName(Url, "createNetworkNotificationResponse"); + private static final QName _QueryNetworkNotificationResponse_QNAME = + new QName(Url, "queryNetworkNotificationResponse"); + private static final QName _UpdateNetworkNotificationResponse_QNAME = + new QName(Url, "updateNetworkNotificationResponse"); + private static final QName _CreateNetworkNotificationResponse_QNAME = + new QName(Url, "createNetworkNotificationResponse"); private static final QName _DeleteNetworkNotification_QNAME = new QName(Url, "deleteNetworkNotification"); - private static final QName _DeleteNetworkNotificationResponse_QNAME = new QName(Url, "deleteNetworkNotificationResponse"); + private static final QName _DeleteNetworkNotificationResponse_QNAME = + new QName(Url, "deleteNetworkNotificationResponse"); private static final QName _CreateNetworkNotification_QNAME = new QName(Url, "createNetworkNotification"); private static final QName _QueryNetworkNotification_QNAME = new QName(Url, "queryNetworkNotification"); - private static final QName _RollbackNetworkNotificationResponse_QNAME = new QName(Url, "rollbackNetworkNotificationResponse"); + private static final QName _RollbackNetworkNotificationResponse_QNAME = + new QName(Url, "rollbackNetworkNotificationResponse"); /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onap.so.adapters.network.async.client + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: + * org.onap.so.adapters.network.async.client * */ - public ObjectFactory() { - } + public ObjectFactory() {} /** * Create an instance of {@link QueryNetworkNotification } @@ -211,7 +212,8 @@ public class ObjectFactory { * */ @XmlElementDecl(namespace = Url, name = "rollbackNetworkNotification") - public JAXBElement<RollbackNetworkNotification> createRollbackNetworkNotification(RollbackNetworkNotification value) { + public JAXBElement<RollbackNetworkNotification> createRollbackNetworkNotification( + RollbackNetworkNotification value) { return new JAXBElement<>(_RollbackNetworkNotification_QNAME, RollbackNetworkNotification.class, null, value); } @@ -229,8 +231,10 @@ public class ObjectFactory { * */ @XmlElementDecl(namespace = Url, name = "queryNetworkNotificationResponse") - public JAXBElement<QueryNetworkNotificationResponse> createQueryNetworkNotificationResponse(QueryNetworkNotificationResponse value) { - return new JAXBElement<>(_QueryNetworkNotificationResponse_QNAME, QueryNetworkNotificationResponse.class, null, value); + public JAXBElement<QueryNetworkNotificationResponse> createQueryNetworkNotificationResponse( + QueryNetworkNotificationResponse value) { + return new JAXBElement<>(_QueryNetworkNotificationResponse_QNAME, QueryNetworkNotificationResponse.class, null, + value); } /** @@ -238,8 +242,10 @@ public class ObjectFactory { * */ @XmlElementDecl(namespace = Url, name = "updateNetworkNotificationResponse") - public JAXBElement<UpdateNetworkNotificationResponse> createUpdateNetworkNotificationResponse(UpdateNetworkNotificationResponse value) { - return new JAXBElement<>(_UpdateNetworkNotificationResponse_QNAME, UpdateNetworkNotificationResponse.class, null, value); + public JAXBElement<UpdateNetworkNotificationResponse> createUpdateNetworkNotificationResponse( + UpdateNetworkNotificationResponse value) { + return new JAXBElement<>(_UpdateNetworkNotificationResponse_QNAME, UpdateNetworkNotificationResponse.class, + null, value); } /** @@ -247,8 +253,10 @@ public class ObjectFactory { * */ @XmlElementDecl(namespace = Url, name = "createNetworkNotificationResponse") - public JAXBElement<CreateNetworkNotificationResponse> createCreateNetworkNotificationResponse(CreateNetworkNotificationResponse value) { - return new JAXBElement<>(_CreateNetworkNotificationResponse_QNAME, CreateNetworkNotificationResponse.class, null, value); + public JAXBElement<CreateNetworkNotificationResponse> createCreateNetworkNotificationResponse( + CreateNetworkNotificationResponse value) { + return new JAXBElement<>(_CreateNetworkNotificationResponse_QNAME, CreateNetworkNotificationResponse.class, + null, value); } /** @@ -265,8 +273,10 @@ public class ObjectFactory { * */ @XmlElementDecl(namespace = Url, name = "deleteNetworkNotificationResponse") - public JAXBElement<DeleteNetworkNotificationResponse> createDeleteNetworkNotificationResponse(DeleteNetworkNotificationResponse value) { - return new JAXBElement<>(_DeleteNetworkNotificationResponse_QNAME, DeleteNetworkNotificationResponse.class, null, value); + public JAXBElement<DeleteNetworkNotificationResponse> createDeleteNetworkNotificationResponse( + DeleteNetworkNotificationResponse value) { + return new JAXBElement<>(_DeleteNetworkNotificationResponse_QNAME, DeleteNetworkNotificationResponse.class, + null, value); } /** @@ -292,8 +302,10 @@ public class ObjectFactory { * */ @XmlElementDecl(namespace = Url, name = "rollbackNetworkNotificationResponse") - public JAXBElement<RollbackNetworkNotificationResponse> createRollbackNetworkNotificationResponse(RollbackNetworkNotificationResponse value) { - return new JAXBElement<>(_RollbackNetworkNotificationResponse_QNAME, RollbackNetworkNotificationResponse.class, null, value); + public JAXBElement<RollbackNetworkNotificationResponse> createRollbackNetworkNotificationResponse( + RollbackNetworkNotificationResponse value) { + return new JAXBElement<>(_RollbackNetworkNotificationResponse_QNAME, RollbackNetworkNotificationResponse.class, + null, value); } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/QueryNetworkNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/QueryNetworkNotification.java index 87aa2183f1..d9adbf2ad2 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/QueryNetworkNotification.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/QueryNetworkNotification.java @@ -24,7 +24,6 @@ package org.onap.so.adapters.network.async.client; import java.util.ArrayList; import java.util.List; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -32,9 +31,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for queryNetworkNotification complex type. + * <p> + * Java class for queryNetworkNotification complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="queryNetworkNotification"> @@ -81,18 +82,8 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "queryNetworkNotification", propOrder = { - "messageId", - "completed", - "exception", - "errorMessage", - "networkExists", - "networkId", - "neutronNetworkId", - "status", - "vlans", - "subnetIdMap" -}) +@XmlType(name = "queryNetworkNotification", propOrder = {"messageId", "completed", "exception", "errorMessage", + "networkExists", "networkId", "neutronNetworkId", "status", "vlans", "subnetIdMap"}) public class QueryNetworkNotification { @XmlElement(required = true) @@ -111,10 +102,8 @@ public class QueryNetworkNotification { /** * Gets the value of the messageId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getMessageId() { return messageId; @@ -123,10 +112,8 @@ public class QueryNetworkNotification { /** * Sets the value of the messageId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setMessageId(String value) { this.messageId = value; @@ -151,10 +138,8 @@ public class QueryNetworkNotification { /** * Gets the value of the exception property. * - * @return - * possible object is - * {@link MsoExceptionCategory } - * + * @return possible object is {@link MsoExceptionCategory } + * */ public MsoExceptionCategory getException() { return exception; @@ -163,10 +148,8 @@ public class QueryNetworkNotification { /** * Sets the value of the exception property. * - * @param value - * allowed object is - * {@link MsoExceptionCategory } - * + * @param value allowed object is {@link MsoExceptionCategory } + * */ public void setException(MsoExceptionCategory value) { this.exception = value; @@ -175,10 +158,8 @@ public class QueryNetworkNotification { /** * Gets the value of the errorMessage property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getErrorMessage() { return errorMessage; @@ -187,10 +168,8 @@ public class QueryNetworkNotification { /** * Sets the value of the errorMessage property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setErrorMessage(String value) { this.errorMessage = value; @@ -199,10 +178,8 @@ public class QueryNetworkNotification { /** * Gets the value of the networkExists property. * - * @return - * possible object is - * {@link Boolean } - * + * @return possible object is {@link Boolean } + * */ public Boolean isNetworkExists() { return networkExists; @@ -211,10 +188,8 @@ public class QueryNetworkNotification { /** * Sets the value of the networkExists property. * - * @param value - * allowed object is - * {@link Boolean } - * + * @param value allowed object is {@link Boolean } + * */ public void setNetworkExists(Boolean value) { this.networkExists = value; @@ -223,10 +198,8 @@ public class QueryNetworkNotification { /** * Gets the value of the networkId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getNetworkId() { return networkId; @@ -235,10 +208,8 @@ public class QueryNetworkNotification { /** * Sets the value of the networkId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setNetworkId(String value) { this.networkId = value; @@ -247,10 +218,8 @@ public class QueryNetworkNotification { /** * Gets the value of the neutronNetworkId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getNeutronNetworkId() { return neutronNetworkId; @@ -259,10 +228,8 @@ public class QueryNetworkNotification { /** * Sets the value of the neutronNetworkId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setNeutronNetworkId(String value) { this.neutronNetworkId = value; @@ -271,10 +238,8 @@ public class QueryNetworkNotification { /** * Gets the value of the status property. * - * @return - * possible object is - * {@link NetworkStatus } - * + * @return possible object is {@link NetworkStatus } + * */ public NetworkStatus getStatus() { return status; @@ -283,10 +248,8 @@ public class QueryNetworkNotification { /** * Sets the value of the status property. * - * @param value - * allowed object is - * {@link NetworkStatus } - * + * @param value allowed object is {@link NetworkStatus } + * */ public void setStatus(NetworkStatus value) { this.status = value; @@ -296,21 +259,20 @@ public class QueryNetworkNotification { * Gets the value of the vlans property. * * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the vlans property. + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to + * the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for + * the vlans property. * * <p> * For example, to add a new item, do as follows: + * * <pre> - * getVlans().add(newItem); + * getVlans().add(newItem); * </pre> * * * <p> - * Objects of the following type(s) are allowed in the list - * {@link Integer } + * Objects of the following type(s) are allowed in the list {@link Integer } * * */ @@ -324,10 +286,8 @@ public class QueryNetworkNotification { /** * Gets the value of the subnetIdMap property. * - * @return - * possible object is - * {@link QueryNetworkNotification.SubnetIdMap } - * + * @return possible object is {@link QueryNetworkNotification.SubnetIdMap } + * */ public QueryNetworkNotification.SubnetIdMap getSubnetIdMap() { return subnetIdMap; @@ -336,10 +296,8 @@ public class QueryNetworkNotification { /** * Sets the value of the subnetIdMap property. * - * @param value - * allowed object is - * {@link QueryNetworkNotification.SubnetIdMap } - * + * @param value allowed object is {@link QueryNetworkNotification.SubnetIdMap } + * */ public void setSubnetIdMap(QueryNetworkNotification.SubnetIdMap value) { this.subnetIdMap = value; @@ -347,9 +305,11 @@ public class QueryNetworkNotification { /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -377,9 +337,7 @@ public class QueryNetworkNotification { * */ @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "entry" - }) + @XmlType(name = "", propOrder = {"entry"}) public static class SubnetIdMap { protected List<QueryNetworkNotification.SubnetIdMap.Entry> entry; @@ -388,21 +346,20 @@ public class QueryNetworkNotification { * Gets the value of the entry property. * * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the entry property. + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you + * make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> + * method for the entry property. * * <p> * For example, to add a new item, do as follows: + * * <pre> - * getEntry().add(newItem); + * getEntry().add(newItem); * </pre> * * * <p> - * Objects of the following type(s) are allowed in the list - * {@link QueryNetworkNotification.SubnetIdMap.Entry } + * Objects of the following type(s) are allowed in the list {@link QueryNetworkNotification.SubnetIdMap.Entry } * * */ @@ -415,9 +372,11 @@ public class QueryNetworkNotification { /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -435,10 +394,7 @@ public class QueryNetworkNotification { * */ @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "key", - "value" - }) + @XmlType(name = "", propOrder = {"key", "value"}) public static class Entry { protected String key; @@ -447,10 +403,8 @@ public class QueryNetworkNotification { /** * Gets the value of the key property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getKey() { return key; @@ -459,10 +413,8 @@ public class QueryNetworkNotification { /** * Sets the value of the key property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setKey(String value) { this.key = value; @@ -471,10 +423,8 @@ public class QueryNetworkNotification { /** * Gets the value of the value property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getValue() { return value; @@ -483,10 +433,8 @@ public class QueryNetworkNotification { /** * Sets the value of the value property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setValue(String value) { this.value = value; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/QueryNetworkNotificationResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/QueryNetworkNotificationResponse.java index 0320df27fc..2e18e05860 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/QueryNetworkNotificationResponse.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/QueryNetworkNotificationResponse.java @@ -26,9 +26,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for queryNetworkNotificationResponse complex type. + * <p> + * Java class for queryNetworkNotificationResponse complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="queryNetworkNotificationResponse"> diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/RollbackNetworkNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/RollbackNetworkNotification.java index 08f37fc85d..7b5d0f0f2a 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/RollbackNetworkNotification.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/RollbackNetworkNotification.java @@ -27,9 +27,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for rollbackNetworkNotification complex type. + * <p> + * Java class for rollbackNetworkNotification complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="rollbackNetworkNotification"> @@ -49,12 +51,7 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "rollbackNetworkNotification", propOrder = { - "messageId", - "completed", - "exception", - "errorMessage" -}) +@XmlType(name = "rollbackNetworkNotification", propOrder = {"messageId", "completed", "exception", "errorMessage"}) public class RollbackNetworkNotification { @XmlElement(required = true) @@ -66,10 +63,8 @@ public class RollbackNetworkNotification { /** * Gets the value of the messageId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getMessageId() { return messageId; @@ -78,10 +73,8 @@ public class RollbackNetworkNotification { /** * Sets the value of the messageId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setMessageId(String value) { this.messageId = value; @@ -106,10 +99,8 @@ public class RollbackNetworkNotification { /** * Gets the value of the exception property. * - * @return - * possible object is - * {@link MsoExceptionCategory } - * + * @return possible object is {@link MsoExceptionCategory } + * */ public MsoExceptionCategory getException() { return exception; @@ -118,10 +109,8 @@ public class RollbackNetworkNotification { /** * Sets the value of the exception property. * - * @param value - * allowed object is - * {@link MsoExceptionCategory } - * + * @param value allowed object is {@link MsoExceptionCategory } + * */ public void setException(MsoExceptionCategory value) { this.exception = value; @@ -130,10 +119,8 @@ public class RollbackNetworkNotification { /** * Gets the value of the errorMessage property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getErrorMessage() { return errorMessage; @@ -142,10 +129,8 @@ public class RollbackNetworkNotification { /** * Sets the value of the errorMessage property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setErrorMessage(String value) { this.errorMessage = value; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/RollbackNetworkNotificationResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/RollbackNetworkNotificationResponse.java index 44db3a1583..7ddc8d75de 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/RollbackNetworkNotificationResponse.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/RollbackNetworkNotificationResponse.java @@ -26,9 +26,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for rollbackNetworkNotificationResponse complex type. + * <p> + * Java class for rollbackNetworkNotificationResponse complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="rollbackNetworkNotificationResponse"> diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/UpdateNetworkNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/UpdateNetworkNotification.java index daff548b45..1a464d3250 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/UpdateNetworkNotification.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/UpdateNetworkNotification.java @@ -24,7 +24,6 @@ package org.onap.so.adapters.network.async.client; import java.util.ArrayList; import java.util.List; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -32,9 +31,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for updateNetworkNotification complex type. + * <p> + * Java class for updateNetworkNotification complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="updateNetworkNotification"> @@ -77,14 +78,8 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "updateNetworkNotification", propOrder = { - "messageId", - "completed", - "exception", - "errorMessage", - "subnetIdMap", - "rollback" -}) +@XmlType(name = "updateNetworkNotification", + propOrder = {"messageId", "completed", "exception", "errorMessage", "subnetIdMap", "rollback"}) public class UpdateNetworkNotification { @XmlElement(required = true) @@ -98,10 +93,8 @@ public class UpdateNetworkNotification { /** * Gets the value of the messageId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getMessageId() { return messageId; @@ -110,10 +103,8 @@ public class UpdateNetworkNotification { /** * Sets the value of the messageId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setMessageId(String value) { this.messageId = value; @@ -138,10 +129,8 @@ public class UpdateNetworkNotification { /** * Gets the value of the exception property. * - * @return - * possible object is - * {@link MsoExceptionCategory } - * + * @return possible object is {@link MsoExceptionCategory } + * */ public MsoExceptionCategory getException() { return exception; @@ -150,10 +139,8 @@ public class UpdateNetworkNotification { /** * Sets the value of the exception property. * - * @param value - * allowed object is - * {@link MsoExceptionCategory } - * + * @param value allowed object is {@link MsoExceptionCategory } + * */ public void setException(MsoExceptionCategory value) { this.exception = value; @@ -162,10 +149,8 @@ public class UpdateNetworkNotification { /** * Gets the value of the errorMessage property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getErrorMessage() { return errorMessage; @@ -174,10 +159,8 @@ public class UpdateNetworkNotification { /** * Sets the value of the errorMessage property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setErrorMessage(String value) { this.errorMessage = value; @@ -186,10 +169,8 @@ public class UpdateNetworkNotification { /** * Gets the value of the subnetIdMap property. * - * @return - * possible object is - * {@link UpdateNetworkNotification.SubnetIdMap } - * + * @return possible object is {@link UpdateNetworkNotification.SubnetIdMap } + * */ public UpdateNetworkNotification.SubnetIdMap getSubnetIdMap() { return subnetIdMap; @@ -198,10 +179,8 @@ public class UpdateNetworkNotification { /** * Sets the value of the subnetIdMap property. * - * @param value - * allowed object is - * {@link UpdateNetworkNotification.SubnetIdMap } - * + * @param value allowed object is {@link UpdateNetworkNotification.SubnetIdMap } + * */ public void setSubnetIdMap(UpdateNetworkNotification.SubnetIdMap value) { this.subnetIdMap = value; @@ -210,10 +189,8 @@ public class UpdateNetworkNotification { /** * Gets the value of the rollback property. * - * @return - * possible object is - * {@link NetworkRollback } - * + * @return possible object is {@link NetworkRollback } + * */ public NetworkRollback getRollback() { return rollback; @@ -222,10 +199,8 @@ public class UpdateNetworkNotification { /** * Sets the value of the rollback property. * - * @param value - * allowed object is - * {@link NetworkRollback } - * + * @param value allowed object is {@link NetworkRollback } + * */ public void setRollback(NetworkRollback value) { this.rollback = value; @@ -233,9 +208,11 @@ public class UpdateNetworkNotification { /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -263,9 +240,7 @@ public class UpdateNetworkNotification { * */ @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "entry" - }) + @XmlType(name = "", propOrder = {"entry"}) public static class SubnetIdMap { protected List<UpdateNetworkNotification.SubnetIdMap.Entry> entry; @@ -274,21 +249,20 @@ public class UpdateNetworkNotification { * Gets the value of the entry property. * * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the entry property. + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you + * make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> + * method for the entry property. * * <p> * For example, to add a new item, do as follows: + * * <pre> - * getEntry().add(newItem); + * getEntry().add(newItem); * </pre> * * * <p> - * Objects of the following type(s) are allowed in the list - * {@link UpdateNetworkNotification.SubnetIdMap.Entry } + * Objects of the following type(s) are allowed in the list {@link UpdateNetworkNotification.SubnetIdMap.Entry } * * */ @@ -301,9 +275,11 @@ public class UpdateNetworkNotification { /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -321,10 +297,7 @@ public class UpdateNetworkNotification { * */ @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "key", - "value" - }) + @XmlType(name = "", propOrder = {"key", "value"}) public static class Entry { protected String key; @@ -333,10 +306,8 @@ public class UpdateNetworkNotification { /** * Gets the value of the key property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getKey() { return key; @@ -345,10 +316,8 @@ public class UpdateNetworkNotification { /** * Sets the value of the key property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setKey(String value) { this.key = value; @@ -357,10 +326,8 @@ public class UpdateNetworkNotification { /** * Gets the value of the value property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getValue() { return value; @@ -369,10 +336,8 @@ public class UpdateNetworkNotification { /** * Sets the value of the value property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setValue(String value) { this.value = value; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/UpdateNetworkNotificationResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/UpdateNetworkNotificationResponse.java index e0016d9b8e..0ffcb5e9e6 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/UpdateNetworkNotificationResponse.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/async/client/UpdateNetworkNotificationResponse.java @@ -26,9 +26,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for updateNetworkNotificationResponse complex type. + * <p> + * Java class for updateNetworkNotificationResponse complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="updateNetworkNotificationResponse"> diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/exceptions/NetworkException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/exceptions/NetworkException.java index cb4cd8b927..175535fef3 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/exceptions/NetworkException.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/exceptions/NetworkException.java @@ -23,58 +23,58 @@ package org.onap.so.adapters.network.exceptions; import javax.xml.ws.WebFault; - import org.onap.so.openstack.exceptions.MsoException; import org.onap.so.openstack.exceptions.MsoExceptionCategory; /** - * This class simply extends Exception (without addition additional functionality) - * to provide an identifier for Network related exceptions on create, delete, query. + * This class simply extends Exception (without addition additional functionality) to provide an identifier for Network + * related exceptions on create, delete, query. * * */ -@WebFault (name="NetworkException", faultBean="org.onap.so.adapters.network.exceptions.NetworkExceptionBean", targetNamespace="http://org.onap.so/network") +@WebFault(name = "NetworkException", faultBean = "org.onap.so.adapters.network.exceptions.NetworkExceptionBean", + targetNamespace = "http://org.onap.so/network") public class NetworkException extends Exception { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; + + private NetworkExceptionBean faultInfo; + + public NetworkException(String msg) { + super(msg); + faultInfo = new NetworkExceptionBean(msg); + } + + public NetworkException(Throwable e) { + super(e); + faultInfo = new NetworkExceptionBean(e.getMessage()); + } + + public NetworkException(String msg, Throwable e) { + super(msg, e); + faultInfo = new NetworkExceptionBean(msg); + } + + public NetworkException(String msg, MsoExceptionCategory category) { + super(msg); + faultInfo = new NetworkExceptionBean(msg, category); + } + + public NetworkException(String msg, MsoExceptionCategory category, Throwable e) { + super(msg, e); + faultInfo = new NetworkExceptionBean(msg, category); + } - private NetworkExceptionBean faultInfo; - - public NetworkException (String msg) { - super(msg); - faultInfo = new NetworkExceptionBean (msg); - } - - public NetworkException (Throwable e) { - super(e); - faultInfo = new NetworkExceptionBean (e.getMessage()); - } - - public NetworkException (String msg, Throwable e) { - super (msg, e); - faultInfo = new NetworkExceptionBean (msg); - } + public NetworkException(MsoException e) { + super(e); + faultInfo = new NetworkExceptionBean(e.getContextMessage(), e.getCategory()); + } - public NetworkException (String msg, MsoExceptionCategory category) { - super(msg); - faultInfo = new NetworkExceptionBean (msg, category); - } - - public NetworkException (String msg, MsoExceptionCategory category, Throwable e) { - super (msg, e); - faultInfo = new NetworkExceptionBean (msg, category); - } - - public NetworkException (MsoException e) { - super (e); - faultInfo = new NetworkExceptionBean (e.getContextMessage(), e.getCategory()); - } - - public NetworkExceptionBean getFaultInfo() { - return faultInfo; - } + public NetworkExceptionBean getFaultInfo() { + return faultInfo; + } - public void setFaultInfo(NetworkExceptionBean faultInfo) { - this.faultInfo = faultInfo; - } + public void setFaultInfo(NetworkExceptionBean faultInfo) { + this.faultInfo = faultInfo; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/exceptions/NetworkExceptionBean.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/exceptions/NetworkExceptionBean.java index 5256891ffa..6a3d567ebd 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/exceptions/NetworkExceptionBean.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/exceptions/NetworkExceptionBean.java @@ -22,7 +22,6 @@ package org.onap.so.adapters.network.exceptions; import java.io.Serializable; - import org.onap.so.openstack.exceptions.MsoExceptionCategory; /** @@ -33,41 +32,41 @@ public class NetworkExceptionBean implements Serializable { private static final long serialVersionUID = 1655343530371342871L; private String message; - private MsoExceptionCategory category; - private Boolean rolledBack; + private MsoExceptionCategory category; + private Boolean rolledBack; - public NetworkExceptionBean () {} + public NetworkExceptionBean() {} - public NetworkExceptionBean (String message) { - this.message = message; - } + public NetworkExceptionBean(String message) { + this.message = message; + } - public NetworkExceptionBean (String message, MsoExceptionCategory category) { - this.message = message; - this.category = category; - } + public NetworkExceptionBean(String message, MsoExceptionCategory category) { + this.message = message; + this.category = category; + } - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } - public void setMessage(String message) { - this.message = message; - } + public void setMessage(String message) { + this.message = message; + } - public MsoExceptionCategory getCategory () { - return category; - } + public MsoExceptionCategory getCategory() { + return category; + } - public void setCategory (MsoExceptionCategory category) { - this.category = category; - } + public void setCategory(MsoExceptionCategory category) { + this.category = category; + } - public Boolean isRolledBack() { - return rolledBack; - } + public Boolean isRolledBack() { + return rolledBack; + } - public void setRolledBack(Boolean rolledBack) { - this.rolledBack = rolledBack; - } + public void setRolledBack(Boolean rolledBack) { + this.rolledBack = rolledBack; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/AaiClientPropertiesImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/AaiClientPropertiesImpl.java index c529413891..68b8598267 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/AaiClientPropertiesImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/AaiClientPropertiesImpl.java @@ -22,7 +22,6 @@ package org.onap.so.adapters.openstack; import java.net.MalformedURLException; import java.net.URL; - import org.onap.so.client.aai.AAIProperties; import org.onap.so.client.aai.AAIVersion; import org.onap.so.spring.SpringContextHelper; @@ -30,40 +29,40 @@ import org.springframework.context.ApplicationContext; public class AaiClientPropertiesImpl implements AAIProperties { - private String aaiEndpoint; - private String auth; - private String key; - private static final String SYSTEM_NAME = "MSO"; - - public AaiClientPropertiesImpl() { - ApplicationContext context = SpringContextHelper.getAppContext(); - aaiEndpoint = context.getEnvironment().getProperty("aai.endpoint"); - this.auth = context.getEnvironment().getProperty("aai.auth"); - this.key = context.getEnvironment().getProperty("mso.msoKey"); - } + private String aaiEndpoint; + private String auth; + private String key; + private static final String SYSTEM_NAME = "MSO"; + + public AaiClientPropertiesImpl() { + ApplicationContext context = SpringContextHelper.getAppContext(); + aaiEndpoint = context.getEnvironment().getProperty("aai.endpoint"); + this.auth = context.getEnvironment().getProperty("aai.auth"); + this.key = context.getEnvironment().getProperty("mso.msoKey"); + } + + @Override + public URL getEndpoint() throws MalformedURLException { + return new URL(aaiEndpoint); + } + + @Override + public String getSystemName() { + return SYSTEM_NAME; + } - @Override - public URL getEndpoint() throws MalformedURLException { - return new URL(aaiEndpoint); - } + @Override + public AAIVersion getDefaultVersion() { + return AAIVersion.LATEST; + } - @Override - public String getSystemName() { - return SYSTEM_NAME; - } - - @Override - public AAIVersion getDefaultVersion() { - return AAIVersion.LATEST; - } - - @Override - public String getAuth() { - return this.auth; - } + @Override + public String getAuth() { + return this.auth; + } - @Override - public String getKey() { - return this.key; - } + @Override + public String getKey() { + return this.key; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/CXFConfiguration.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/CXFConfiguration.java index 72c74ccaf9..4396fc035d 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/CXFConfiguration.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/CXFConfiguration.java @@ -23,9 +23,7 @@ package org.onap.so.adapters.openstack; import java.util.Arrays; - import javax.xml.ws.Endpoint; - import org.apache.cxf.Bus; import org.apache.cxf.bus.spring.SpringBus; import org.apache.cxf.endpoint.Server; @@ -47,62 +45,59 @@ import org.onap.so.adapters.vnf.VnfAdapterRestV2; import org.onap.so.adapters.vnf.VolumeAdapterRest; import org.onap.so.adapters.vnf.VolumeAdapterRestV2; import org.onap.so.client.policy.JettisonStyleMapperProvider; - import org.onap.so.logging.cxf.interceptor.SOAPLoggingInInterceptor; import org.onap.so.logging.cxf.interceptor.SOAPLoggingOutInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; - import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; @Configuration public class CXFConfiguration { - @Autowired - private NetworkAdapterRest networkAdapterRest; - @Autowired - private TenantAdapterRest tenantAdapterRest; - @Autowired - private VnfAdapterRest vnfAdapterRest; - @Autowired - private VnfAdapterRestV2 vnfAdapterRestV2; - @Autowired - private VolumeAdapterRest volumeAdapterRest; - @Autowired - private VolumeAdapterRestV2 volumeAdapterRestV2; - @Autowired - private MsoNetworkAdapterImpl networkAdapterImpl; - @Autowired - private MsoNetworkAdapterAsyncImpl networkAdapterAsyncImpl; - @Autowired - private MsoTenantAdapterImpl tenantAdapterImpl; - @Autowired - private MsoVnfAdapterImpl vnfAdapterImpl; - @Autowired - private MsoVnfAdapterAsyncImpl vnfAdapterAsyncImpl; - @Autowired - private MsoVnfCloudifyAdapterImpl vnfCloudifyAdapterImpl; - @Autowired - private JettisonStyleMapperProvider jettisonStyleObjectMapper; + @Autowired + private NetworkAdapterRest networkAdapterRest; + @Autowired + private TenantAdapterRest tenantAdapterRest; + @Autowired + private VnfAdapterRest vnfAdapterRest; + @Autowired + private VnfAdapterRestV2 vnfAdapterRestV2; + @Autowired + private VolumeAdapterRest volumeAdapterRest; + @Autowired + private VolumeAdapterRestV2 volumeAdapterRestV2; + @Autowired + private MsoNetworkAdapterImpl networkAdapterImpl; + @Autowired + private MsoNetworkAdapterAsyncImpl networkAdapterAsyncImpl; + @Autowired + private MsoTenantAdapterImpl tenantAdapterImpl; + @Autowired + private MsoVnfAdapterImpl vnfAdapterImpl; + @Autowired + private MsoVnfAdapterAsyncImpl vnfAdapterAsyncImpl; + @Autowired + private MsoVnfCloudifyAdapterImpl vnfCloudifyAdapterImpl; + @Autowired + private JettisonStyleMapperProvider jettisonStyleObjectMapper; - @Bean(name=Bus.DEFAULT_BUS_ID) - public SpringBus springBus() { + @Bean(name = Bus.DEFAULT_BUS_ID) + public SpringBus springBus() { return new SpringBus(); - } - - @Bean - public ServletRegistrationBean SoapDispatcherServlet() { - ServletRegistrationBean servletRegistrationBean = - new ServletRegistrationBean(new CXFServlet(), "/services/*"); + } + + @Bean + public ServletRegistrationBean SoapDispatcherServlet() { + ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new CXFServlet(), "/services/*"); servletRegistrationBean.setName("services"); - return servletRegistrationBean; - } + return servletRegistrationBean; + } - /* - * network adapter endpoint - */ + /* + * network adapter endpoint + */ @Bean public Endpoint networkAdapterEndpoint() { EndpointImpl endpoint = new EndpointImpl(springBus(), networkAdapterImpl); @@ -112,8 +107,8 @@ public class CXFConfiguration { endpoint.getOutInterceptors().add(new SOAPLoggingOutInterceptor()); endpoint.getOutFaultInterceptors().add(new SOAPLoggingOutInterceptor()); return endpoint; - } - + } + @Bean public Endpoint networkAdapterAsyncEndpoint() { EndpointImpl endpoint = new EndpointImpl(springBus(), networkAdapterAsyncImpl); @@ -123,8 +118,8 @@ public class CXFConfiguration { endpoint.getOutInterceptors().add(new SOAPLoggingOutInterceptor()); endpoint.getOutFaultInterceptors().add(new SOAPLoggingOutInterceptor()); return endpoint; - } - + } + /* * tenant adapter endpoint */ @@ -138,11 +133,9 @@ public class CXFConfiguration { endpoint.getOutFaultInterceptors().add(new SOAPLoggingOutInterceptor()); return endpoint; } - + /* - * vnfAdapterEndpoint - * VnfAsyncAdapterEndpoint - * VnfCloudAdapterEndpoint + * vnfAdapterEndpoint VnfAsyncAdapterEndpoint VnfCloudAdapterEndpoint */ @Bean public Endpoint vnfAdapterEndpoint() { @@ -154,7 +147,7 @@ public class CXFConfiguration { endpoint.getOutFaultInterceptors().add(new SOAPLoggingOutInterceptor()); return endpoint; } - + @Bean public Endpoint VnfAsyncAdapterEndpoint() { EndpointImpl endpoint = new EndpointImpl(springBus(), vnfAdapterAsyncImpl); @@ -165,7 +158,7 @@ public class CXFConfiguration { endpoint.getOutFaultInterceptors().add(new SOAPLoggingOutInterceptor()); return endpoint; } - + @Bean public Endpoint VnfCloudAdapterEndpoint() { EndpointImpl endpoint = new EndpointImpl(springBus(), vnfCloudifyAdapterImpl); @@ -176,34 +169,31 @@ public class CXFConfiguration { endpoint.getOutFaultInterceptors().add(new SOAPLoggingOutInterceptor()); return endpoint; } - + @Bean public Server rsServer() { JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean(); endpoint.setBus(springBus()); - endpoint.setServiceBeans(Arrays.<Object>asList(networkAdapterRest, - tenantAdapterRest, - vnfAdapterRest, - vnfAdapterRestV2, - volumeAdapterRest, - volumeAdapterRestV2)); + endpoint.setServiceBeans(Arrays.<Object>asList(networkAdapterRest, tenantAdapterRest, vnfAdapterRest, + vnfAdapterRestV2, volumeAdapterRest, volumeAdapterRestV2)); endpoint.setAddress("/rest"); endpoint.setFeatures(Arrays.asList(createSwaggerFeature(), new LoggingFeature())); endpoint.setProvider(new JacksonJsonProvider(jettisonStyleObjectMapper.getMapper())); return endpoint.create(); - } - - + } + + @Bean public Swagger2Feature createSwaggerFeature() { - Swagger2Feature swagger2Feature= new Swagger2Feature(); + Swagger2Feature swagger2Feature = new Swagger2Feature(); swagger2Feature.setPrettyPrint(true); swagger2Feature.setTitle("SO Orchestration Application"); swagger2Feature.setContact("The ONAP SO team"); swagger2Feature.setDescription("This project is the SO Orchestration Engine"); swagger2Feature.setVersion("1.0.0"); - swagger2Feature.setResourcePackage("org.onap.so.adapters.network,org.onap.so.adapters.tenant,org.onap.so.adapters.vnf"); + swagger2Feature.setResourcePackage( + "org.onap.so.adapters.network,org.onap.so.adapters.tenant,org.onap.so.adapters.vnf"); swagger2Feature.setScan(true); return swagger2Feature; - } + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/MsoOpenstackAdaptersApplication.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/MsoOpenstackAdaptersApplication.java index 9408f0d681..97a2500c59 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/MsoOpenstackAdaptersApplication.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/MsoOpenstackAdaptersApplication.java @@ -21,7 +21,6 @@ package org.onap.so.adapters.openstack; import java.util.concurrent.Executor; - import org.onap.so.logging.jaxrs.filter.MDCTaskDecorator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -34,46 +33,45 @@ import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -@SpringBootApplication(scanBasePackages = { "org.onap.so" }) +@SpringBootApplication(scanBasePackages = {"org.onap.so"}) @EnableAsync @EnableScheduling -@EnableJpaRepositories({ "org.onap.so.db.catalog.data.repository", - "org.onap.so.db.request.data.repository"}) -@EntityScan({ "org.onap.so.db.catalog.beans", "org.onap.so.db.request.beans"}) +@EnableJpaRepositories({"org.onap.so.db.catalog.data.repository", "org.onap.so.db.request.data.repository"}) +@EntityScan({"org.onap.so.db.catalog.beans", "org.onap.so.db.request.beans"}) public class MsoOpenstackAdaptersApplication { - @Value("${mso.async.core-pool-size}") - private int corePoolSize; + @Value("${mso.async.core-pool-size}") + private int corePoolSize; - @Value("${mso.async.max-pool-size}") - private int maxPoolSize; + @Value("${mso.async.max-pool-size}") + private int maxPoolSize; - @Value("${mso.async.queue-capacity}") - private int queueCapacity; + @Value("${mso.async.queue-capacity}") + private int queueCapacity; - private static final String LOGS_DIR = "logs_dir"; + private static final String LOGS_DIR = "logs_dir"; - private static void setLogsDir() { - if (System.getProperty(LOGS_DIR) == null) { - System.getProperties().setProperty(LOGS_DIR, "./logs/openstack/"); - } - } + private static void setLogsDir() { + if (System.getProperty(LOGS_DIR) == null) { + System.getProperties().setProperty(LOGS_DIR, "./logs/openstack/"); + } + } - public static void main(String[] args) { - SpringApplication.run(MsoOpenstackAdaptersApplication.class, args); - setLogsDir(); - } + public static void main(String[] args) { + SpringApplication.run(MsoOpenstackAdaptersApplication.class, args); + setLogsDir(); + } - @Bean - public Executor asyncExecutor() { - ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); - executor.setTaskDecorator(new MDCTaskDecorator()); - executor.setCorePoolSize(corePoolSize); - executor.setMaxPoolSize(maxPoolSize); - executor.setQueueCapacity(queueCapacity); - executor.setThreadNamePrefix("OpenstackAdapters-"); - executor.initialize(); - return executor; - } + @Bean + public Executor asyncExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setTaskDecorator(new MDCTaskDecorator()); + executor.setCorePoolSize(corePoolSize); + executor.setMaxPoolSize(maxPoolSize); + executor.setQueueCapacity(queueCapacity); + executor.setThreadNamePrefix("OpenstackAdapters-"); + executor.initialize(); + return executor; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/WebSecurityConfigImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/WebSecurityConfigImpl.java index aca16d9996..97e43d9828 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/WebSecurityConfigImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/WebSecurityConfigImpl.java @@ -19,7 +19,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - + package org.onap.so.adapters.openstack; import org.onap.so.security.MSOSpringFirewall; @@ -33,21 +33,18 @@ import org.springframework.util.StringUtils; @EnableWebSecurity public class WebSecurityConfigImpl extends WebSecurityConfig { - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable() - .authorizeRequests() - .antMatchers("/manage/health","/manage/info").permitAll() - .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(),",")) - .and() - .httpBasic(); - } - - @Override - public void configure(WebSecurity web) throws Exception { - super.configure(web); - StrictHttpFirewall firewall = new MSOSpringFirewall(); - web.httpFirewall(firewall); - } + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() + .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and() + .httpBasic(); + } + + @Override + public void configure(WebSecurity web) throws Exception { + super.configure(web); + StrictHttpFirewall firewall = new MSOSpringFirewall(); + web.httpFirewall(firewall); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/MsoTenantAdapter.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/MsoTenantAdapter.java index d82d478a93..68f7558add 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/MsoTenantAdapter.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/MsoTenantAdapter.java @@ -24,55 +24,48 @@ package org.onap.so.adapters.tenant; import java.util.Map; - import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebParam.Mode; import javax.jws.WebService; import javax.xml.bind.annotation.XmlElement; import javax.xml.ws.Holder; - import org.onap.so.adapters.tenant.exceptions.TenantException; import org.onap.so.adapters.tenantrest.TenantRollback; import org.onap.so.entity.MsoRequest; -@WebService (name="TenantAdapter", targetNamespace="http://org.onap.so/tenant") -public interface MsoTenantAdapter -{ - /** - * This is the "Create Tenant" Web Service Endpoint definition. - */ - @WebMethod - public void createTenant (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="tenantName") @XmlElement(required=true) String tenantName, - @WebParam(name="metadata") Map<String,String> metadata, - @WebParam(name="failIfExists") Boolean failIfExists, - @WebParam(name="backout") Boolean backout, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="tenantId", mode=Mode.OUT) Holder<String> tenantId, - @WebParam(name="rollback", mode=Mode.OUT) Holder<TenantRollback> rollback ) - throws TenantException; - - @WebMethod - public void queryTenant (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="tenantNameOrId") @XmlElement(required=true) String tenantNameOrId, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="tenantId", mode=Mode.OUT) Holder<String> tenantId, - @WebParam(name="tenantName", mode=Mode.OUT) Holder<String> tenantName, - @WebParam(name="metadata", mode=Mode.OUT) Holder<Map<String,String>> metadata ) - throws TenantException; - - @WebMethod - public void deleteTenant (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="tenantDeleted", mode=Mode.OUT) Holder<Boolean> tenantDeleted) - throws TenantException; - - @WebMethod - public void rollbackTenant (@WebParam(name="rollback") @XmlElement(required=true) TenantRollback rollback) - throws TenantException; - - @WebMethod - public void healthCheck (); +@WebService(name = "TenantAdapter", targetNamespace = "http://org.onap.so/tenant") +public interface MsoTenantAdapter { + /** + * This is the "Create Tenant" Web Service Endpoint definition. + */ + @WebMethod + public void createTenant(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "tenantName") @XmlElement(required = true) String tenantName, + @WebParam(name = "metadata") Map<String, String> metadata, + @WebParam(name = "failIfExists") Boolean failIfExists, @WebParam(name = "backout") Boolean backout, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "tenantId", mode = Mode.OUT) Holder<String> tenantId, + @WebParam(name = "rollback", mode = Mode.OUT) Holder<TenantRollback> rollback) throws TenantException; + + @WebMethod + public void queryTenant(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "tenantNameOrId") @XmlElement(required = true) String tenantNameOrId, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "tenantId", mode = Mode.OUT) Holder<String> tenantId, + @WebParam(name = "tenantName", mode = Mode.OUT) Holder<String> tenantName, + @WebParam(name = "metadata", mode = Mode.OUT) Holder<Map<String, String>> metadata) throws TenantException; + + @WebMethod + public void deleteTenant(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "tenantDeleted", mode = Mode.OUT) Holder<Boolean> tenantDeleted) throws TenantException; + + @WebMethod + public void rollbackTenant(@WebParam(name = "rollback") @XmlElement(required = true) TenantRollback rollback) + throws TenantException; + + @WebMethod + public void healthCheck(); } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/MsoTenantAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/MsoTenantAdapterImpl.java index ceae1caca6..04b90b444f 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/MsoTenantAdapterImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/MsoTenantAdapterImpl.java @@ -45,96 +45,93 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -@WebService(serviceName = "TenantAdapter", endpointInterface = "org.onap.so.adapters.tenant.MsoTenantAdapter", targetNamespace = "http://org.onap.so/tenant") +@WebService(serviceName = "TenantAdapter", endpointInterface = "org.onap.so.adapters.tenant.MsoTenantAdapter", + targetNamespace = "http://org.onap.so/tenant") @Component public class MsoTenantAdapterImpl implements MsoTenantAdapter { - public static final String CREATE_TENANT = "createTenant"; + public static final String CREATE_TENANT = "createTenant"; public static final String OPENSTACK = "OpenStack"; public static final String QUERY_TENANT = "QueryTenant"; public static final String DELETE_TENANT = "DeleteTenant"; public static final String ROLLBACK_TENANT = "RollbackTenant"; - private static final String OPENSTACK_COMMUNICATE_EXCEPTION_MSG = "{} {} Exception while communicate with Open Stack "; + private static final String OPENSTACK_COMMUNICATE_EXCEPTION_MSG = + "{} {} Exception while communicate with Open Stack "; @Resource private WebServiceContext wsContext; @Autowired - private MsoTenantUtilsFactory tFactory; + private MsoTenantUtilsFactory tFactory; private static Logger logger = LoggerFactory.getLogger(MsoTenantAdapterImpl.class); + /** * Health Check web method. Does nothing but return to show the adapter is deployed. */ @Override - public void healthCheck () { - logger.debug ("Health check call in Tenant Adapter"); + public void healthCheck() { + logger.debug("Health check call in Tenant Adapter"); } /** - * This is the "Create Tenant" web service implementation. It will create - * a new Tenant in the specified cloud. If the tenant already exists, this - * can be considered a success or failure, depending on the value of the + * This is the "Create Tenant" web service implementation. It will create a new Tenant in the specified cloud. If + * the tenant already exists, this can be considered a success or failure, depending on the value of the * 'failIfExists' parameter. * - * The method returns the tenantId (the Openstack ID), and a TenantRollback - * object. This last object can be passed as-is to the rollbackTenant method - * to undo what (if anything) was created. This is useful if a Tenant is + * The method returns the tenantId (the Openstack ID), and a TenantRollback object. This last object can be passed + * as-is to the rollbackTenant method to undo what (if anything) was created. This is useful if a Tenant is * successfully created but the orchestrator fails on a subsequent operation. */ @Override - public void createTenant (String cloudSiteId, - String tenantName, - Map <String, String> metadata, - Boolean failIfExists, - Boolean backout, - MsoRequest msoRequest, - Holder <String> tenantId, - Holder <TenantRollback> rollback) throws TenantException { + public void createTenant(String cloudSiteId, String tenantName, Map<String, String> metadata, Boolean failIfExists, + Boolean backout, MsoRequest msoRequest, Holder<String> tenantId, Holder<TenantRollback> rollback) + throws TenantException { logger.debug("Call to MSO createTenant adapter. Creating Tenant: {} in {}", tenantName, cloudSiteId); // Start building up rollback object - TenantRollback tenantRollback = new TenantRollback (); - tenantRollback.setCloudId (cloudSiteId); - tenantRollback.setMsoRequest (msoRequest); - + TenantRollback tenantRollback = new TenantRollback(); + tenantRollback.setCloudId(cloudSiteId); + tenantRollback.setMsoRequest(msoRequest); + MsoTenantUtils tUtils; - try { - tUtils = tFactory.getTenantUtils (cloudSiteId); - } catch (MsoCloudSiteNotFound me) { - logger.error("{} {} no implementation found for {}: ", MessageEnum.RA_CREATE_TENANT_ERR, - ErrorCode.DataError.getValue(), cloudSiteId, me); - throw new TenantException (me); - } + try { + tUtils = tFactory.getTenantUtils(cloudSiteId); + } catch (MsoCloudSiteNotFound me) { + logger.error("{} {} no implementation found for {}: ", MessageEnum.RA_CREATE_TENANT_ERR, + ErrorCode.DataError.getValue(), cloudSiteId, me); + throw new TenantException(me); + } MsoTenant newTenant = null; String newTenantId; try { - newTenant = tUtils.queryTenantByName (tenantName, cloudSiteId); + newTenant = tUtils.queryTenantByName(tenantName, cloudSiteId); } catch (MsoException me) { logger.error(OPENSTACK_COMMUNICATE_EXCEPTION_MSG, MessageEnum.RA_CREATE_TENANT_ERR, - ErrorCode.DataError.getValue(), me); - throw new TenantException (me); + ErrorCode.DataError.getValue(), me); + throw new TenantException(me); } if (newTenant == null) { if (backout == null) backout = true; try { - newTenantId = tUtils.createTenant (tenantName, cloudSiteId, metadata, backout.booleanValue ()); + newTenantId = tUtils.createTenant(tenantName, cloudSiteId, metadata, backout.booleanValue()); } catch (MsoException me) { - logger.error (OPENSTACK_COMMUNICATE_EXCEPTION_MSG, MessageEnum.RA_CREATE_TENANT_ERR, ErrorCode.DataError.getValue(), me); - throw new TenantException (me); + logger.error(OPENSTACK_COMMUNICATE_EXCEPTION_MSG, MessageEnum.RA_CREATE_TENANT_ERR, + ErrorCode.DataError.getValue(), me); + throw new TenantException(me); } - tenantRollback.setTenantId (newTenantId); - tenantRollback.setTenantCreated (true); - logger.debug ("Tenant {} successfully created with ID {}", tenantName, newTenantId); + tenantRollback.setTenantId(newTenantId); + tenantRollback.setTenantCreated(true); + logger.debug("Tenant {} successfully created with ID {}", tenantName, newTenantId); } else { if (failIfExists != null && failIfExists) { logger.error("{} {} CreateTenant: Tenant {} already exists in {} ", MessageEnum.RA_TENANT_ALREADY_EXIST, - ErrorCode.DataError.getValue(), tenantName, cloudSiteId); - throw new TenantAlreadyExists (tenantName, cloudSiteId, newTenant.getTenantId ()); + ErrorCode.DataError.getValue(), tenantName, cloudSiteId); + throw new TenantAlreadyExists(tenantName, cloudSiteId, newTenant.getTenantId()); } - newTenantId = newTenant.getTenantId (); - tenantRollback.setTenantCreated (false); + newTenantId = newTenant.getTenantId(); + tenantRollback.setTenantCreated(false); logger.debug("Tenant {} already exists with ID {}", tenantName, newTenantId); } @@ -145,69 +142,63 @@ public class MsoTenantAdapterImpl implements MsoTenantAdapter { } @Override - public void queryTenant (String cloudSiteId, - String tenantNameOrId, - MsoRequest msoRequest, - Holder <String> tenantId, - Holder <String> tenantName, - Holder <Map <String, String>> metadata) throws TenantException { + public void queryTenant(String cloudSiteId, String tenantNameOrId, MsoRequest msoRequest, Holder<String> tenantId, + Holder<String> tenantName, Holder<Map<String, String>> metadata) throws TenantException { - logger.debug ("Querying Tenant {} in {}", tenantNameOrId, cloudSiteId); + logger.debug("Querying Tenant {} in {}", tenantNameOrId, cloudSiteId); MsoTenantUtils tUtils; - try { - tUtils = tFactory.getTenantUtils (cloudSiteId); - } catch (MsoCloudSiteNotFound me) { - logger.error("{} {} no implementation found for {}: ", MessageEnum.RA_CREATE_TENANT_ERR, - ErrorCode.DataError.getValue(), cloudSiteId, me); - throw new TenantException (me); - } - + try { + tUtils = tFactory.getTenantUtils(cloudSiteId); + } catch (MsoCloudSiteNotFound me) { + logger.error("{} {} no implementation found for {}: ", MessageEnum.RA_CREATE_TENANT_ERR, + ErrorCode.DataError.getValue(), cloudSiteId, me); + throw new TenantException(me); + } + MsoTenant qTenant = null; try { - qTenant = tUtils.queryTenant (tenantNameOrId, cloudSiteId); + qTenant = tUtils.queryTenant(tenantNameOrId, cloudSiteId); if (qTenant == null) { // Not found by ID, Try by name. - qTenant = tUtils.queryTenantByName (tenantNameOrId, cloudSiteId); + qTenant = tUtils.queryTenantByName(tenantNameOrId, cloudSiteId); } if (qTenant == null) { - logger.debug ("QueryTenant: Tenant {} not found", tenantNameOrId); + logger.debug("QueryTenant: Tenant {} not found", tenantNameOrId); tenantId.value = null; tenantName.value = null; metadata.value = null; } else { logger.debug("QueryTenant: Tenant {} found with ID {}", tenantNameOrId, qTenant.getTenantId()); - tenantId.value = qTenant.getTenantId (); - tenantName.value = qTenant.getTenantName (); - metadata.value = qTenant.getMetadata (); + tenantId.value = qTenant.getTenantId(); + tenantName.value = qTenant.getTenantName(); + metadata.value = qTenant.getMetadata(); } } catch (MsoException me) { logger.error("Exception in queryTenant for {}: ", MessageEnum.RA_GENERAL_EXCEPTION, - ErrorCode.DataError.getValue(), tenantNameOrId, me); - throw new TenantException (me); + ErrorCode.DataError.getValue(), tenantNameOrId, me); + throw new TenantException(me); } return; } @Override - public void deleteTenant (String cloudSiteId, - String tenantId, - MsoRequest msoRequest, - Holder <Boolean> tenantDeleted) throws TenantException { + public void deleteTenant(String cloudSiteId, String tenantId, MsoRequest msoRequest, Holder<Boolean> tenantDeleted) + throws TenantException { - logger.debug ("Deleting Tenant {} in {}", tenantId, cloudSiteId); + logger.debug("Deleting Tenant {} in {}", tenantId, cloudSiteId); // Delete the Tenant. try { - - MsoTenantUtils tUtils = tFactory.getTenantUtils (cloudSiteId); - boolean deleted = tUtils.deleteTenant (tenantId, cloudSiteId); + + MsoTenantUtils tUtils = tFactory.getTenantUtils(cloudSiteId); + boolean deleted = tUtils.deleteTenant(tenantId, cloudSiteId); tenantDeleted.value = deleted; } catch (MsoException me) { logger.error("{} {} Exception - DeleteTenant {}: ", MessageEnum.RA_DELETE_TEMAMT_ERR, - ErrorCode.DataError.getValue(), tenantId, me); - throw new TenantException (me); + ErrorCode.DataError.getValue(), tenantId, me); + throw new TenantException(me); } // On success, nothing is returned. @@ -215,40 +206,39 @@ public class MsoTenantAdapterImpl implements MsoTenantAdapter { } /** - * This web service endpoint will rollback a previous Create VNF operation. - * A rollback object is returned to the client in a successful creation - * response. The client can pass that object as-is back to the rollbackVnf - * operation to undo the creation. + * This web service endpoint will rollback a previous Create VNF operation. A rollback object is returned to the + * client in a successful creation response. The client can pass that object as-is back to the rollbackVnf operation + * to undo the creation. * - * The rollback includes removing the VNF and deleting the tenant if the - * tenant did not exist prior to the VNF creation. + * The rollback includes removing the VNF and deleting the tenant if the tenant did not exist prior to the VNF + * creation. */ @Override - public void rollbackTenant (TenantRollback rollback) throws TenantException { + public void rollbackTenant(TenantRollback rollback) throws TenantException { // rollback may be null (e.g. if stack already existed when Create was called) if (rollback == null) { logger.warn("{} {} rollbackTenant, rollback is null", MessageEnum.RA_ROLLBACK_NULL, - ErrorCode.DataError.getValue()); + ErrorCode.DataError.getValue()); return; } // Get the elements of the VnfRollback object for easier access - String cloudSiteId = rollback.getCloudId (); - String tenantId = rollback.getTenantId (); + String cloudSiteId = rollback.getCloudId(); + String tenantId = rollback.getTenantId(); logger.debug("Rolling Back Tenant {} in {}", rollback.getTenantId(), cloudSiteId); - if (rollback.getTenantCreated ()) { + if (rollback.getTenantCreated()) { try { - - MsoTenantUtils tUtils = tFactory.getTenantUtils (cloudSiteId); - tUtils.deleteTenant (tenantId, cloudSiteId); + + MsoTenantUtils tUtils = tFactory.getTenantUtils(cloudSiteId); + tUtils.deleteTenant(tenantId, cloudSiteId); } catch (MsoException me) { - me.addContext (ROLLBACK_TENANT); + me.addContext(ROLLBACK_TENANT); // Failed to delete the tenant. logger.error("{} {} Exception - rollbackTenant {}: ", MessageEnum.RA_ROLLBACK_TENANT_ERR, - ErrorCode.DataError.getValue(), tenantId, me); - throw new TenantException (me); + ErrorCode.DataError.getValue(), tenantId, me); + throw new TenantException(me); } } return; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/TenantAdapterRest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/TenantAdapterRest.java index 11051df34e..6a38cc60e6 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/TenantAdapterRest.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/TenantAdapterRest.java @@ -65,8 +65,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** - * This class services calls to the REST interface for Tenants (http://host:port/vnfs/rest/v1/tenants) - * Both XML and JSON can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default. + * This class services calls to the REST interface for Tenants (http://host:port/vnfs/rest/v1/tenants) Both XML and JSON + * can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default. */ @Path("/v1/tenants") @Api(value = "/v1/tenants", description = "root of tenant adapters restful web service") @@ -74,265 +74,176 @@ import org.springframework.stereotype.Component; public class TenantAdapterRest { private static Logger logger = LoggerFactory.getLogger(TenantAdapterRest.class); - private static final String EXCEPTION= "Exception :"; - //RAA? No logging in wrappers - @Autowired - private MsoTenantAdapterImpl tenantImpl; - - - - /* - URL: - EP: http://host:8080/tenants/rest - Resource: v1/tenants - REQ - metadata? - { - "cloudSiteId": "DAN", - "tenantName": "RAA_1", - "failIfExists": true, - "msoRequest": { - "requestId": "ra1", - "serviceInstanceId": "sa1" - }} - RESP- - { - "cloudSiteId": "DAN", - "tenantId": "128e10b9996d43a7874f19bbc4eb6749", - "tenantCreated": true, - "tenantRollback": { - "tenantId": "128e10b9996d43a7874f19bbc4eb6749", - "cloudId": "DAN", // RAA? cloudId instead of cloudSiteId - "tenantCreated": true, - "msoRequest": { - "requestId": "ra1", - "serviceInstanceId": "sa1" - } - } - } - */ - @POST - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "CreateTenant", - response = Response.class, - notes = "Creates a new tenant, CreateTenantRequest data is required") - @ApiResponses({ - @ApiResponse(code = 200, message = "tenant has been successfully created"), - @ApiResponse(code = 500, message = "create tenant failed") }) - public Response createTenant( - @ApiParam(value = "details of tenant being created", required = true) - CreateTenantRequest req) { - logger.debug("createTenant enter: {}", req.toJsonString()); - - String newTenantId = null; - TenantRollback tenantRollback = new TenantRollback (); - - try { - Holder<String> htenant = new Holder<>(); - Holder<TenantRollback> hrollback = new Holder<>(); - MsoTenantAdapter impl = tenantImpl; - impl.createTenant( - req.getCloudSiteId(), - req.getTenantName(), - req.getMetadata(), - req.getFailIfExists(), - req.getBackout(), - req.getMsoRequest(), - htenant, - hrollback); - newTenantId = htenant.value; - tenantRollback = hrollback.value; - - } - catch (TenantAlreadyExists tae) { - logger.debug(EXCEPTION, tae); - CreateTenantError exc = new CreateTenantError(tae.getMessage(), tae.getFaultInfo().getCategory(), Boolean.TRUE); - return Response.status(HttpServletResponse.SC_NOT_IMPLEMENTED).entity(exc).build(); - } - catch (TenantException te) { - logger.debug(EXCEPTION, te); - CreateTenantError exc = new CreateTenantError(te.getFaultInfo().getMessage(), te.getFaultInfo().getCategory(), Boolean.TRUE); - return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build(); - } - catch (Exception e) { - logger.debug(EXCEPTION, e); - CreateTenantError exc = new CreateTenantError(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE); - return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build(); - } - - CreateTenantResponse resp = new CreateTenantResponse (req.getCloudSiteId(), newTenantId, tenantRollback.getTenantCreated(), tenantRollback); - return Response.status(HttpServletResponse.SC_OK).entity(resp).build(); - } - - /* - URL: - http://host:8080/tenants/rest - Resource: v1/tenant/tennatId - REQ: - {"cloudSiteId": "DAN", - "tenantId": "ca84cd3d3df44272845da554656b3ace", - "msoRequest": { - "requestId": "ra1", - "serviceInstanceId": "sa1" - } - } - RESP: - {"tenantDeleted": true} - */ - @DELETE - @Path("{tenantId}") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "DeleteTenant", - response = Response.class, - notes = "Delete an existing tenant") - @ApiResponses({ - @ApiResponse(code = 200, message = "tenant has been successfully deleted"), - @ApiResponse(code = 500, message = "delete tenant failed") }) - public Response deleteTenant( - @ApiParam(value = "tenantId of tenant being deleted", required = true) - @PathParam("tenantId") String tenantId, - @ApiParam(value = "DeleteTenantRequest object containing additional information of tenant being deleted", required = false) - DeleteTenantRequest req) - { - boolean tenantDeleted = false; - - try { - Holder<Boolean> deleted = new Holder<>(); - MsoTenantAdapter impl = tenantImpl; - impl.deleteTenant( - req.getCloudSiteId(), - req.getTenantId(), - req.getMsoRequest(), - deleted); - tenantDeleted = deleted.value; - } - catch (TenantException te) { - logger.debug(EXCEPTION, te); - DeleteTenantError exc = new DeleteTenantError(te.getFaultInfo().getMessage(), te.getFaultInfo().getCategory(), Boolean.TRUE); - return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build(); - } - catch (Exception e) { - logger.debug(EXCEPTION, e); - DeleteTenantError exc = new DeleteTenantError(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE); - return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build(); - } - DeleteTenantResponse resp = new DeleteTenantResponse(); - resp.setTenantDeleted(tenantDeleted); - return Response.status(HttpServletResponse.SC_OK).entity(resp).build(); - } - - /* - URL - EP://http://host:8080/tenants/rest - Resource: /v1/tenants - Params:?tenantNameOrId=RAA_1&cloudSiteId=DAN - RESP - { - "tenantId": "214b428a1f554c02935e66330f6a5409", - "tenantName": "RAA_1", - "metadata": {} - } - */ - @GET - @Path("{tenantId}") - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "QueryTenant", - response = Response.class, - notes = "Query an existing tenant") - @ApiResponses({ - @ApiResponse(code = 200, message = "tenant has been successfully queried"), - @ApiResponse(code = 500, message = "query tenant failed") }) - public Response queryTenant( - @ApiParam(value = "tenantId", required = true) - @PathParam("tenantId") String tenantId, -// @QueryParam("tenantNameOrId") String tenantNameOrId, //RAA? diff from doc - @ApiParam(value = "cloudSiteId", required = true) - @QueryParam("cloudSiteId") String cloudSiteId, - @ApiParam(value = "msoRequest.requestId", required = true) - @QueryParam("msoRequest.requestId") String requestId, - @ApiParam(value = "msoRequest.serviceInstanceId", required = true) - @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId) - { - MsoTenant tenant = null; - try { - Holder<String> htenant = new Holder<>(); - Holder<String> tenantName = new Holder<>(); - Holder<Map<String,String>> metadata = new Holder<>(); - MsoTenantAdapter impl = tenantImpl; - impl.queryTenant( - cloudSiteId, - tenantId, - null, - htenant, - tenantName, - metadata - ); - tenant = new MsoTenant(htenant.value, tenantName.value, metadata.value); - - } - catch (TenantException te) { - logger.debug(EXCEPTION, te); - QueryTenantError exc = new QueryTenantError(te.getFaultInfo().getMessage(), te.getFaultInfo().getCategory()); - return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build(); - } - catch (Exception e) { - logger.debug(EXCEPTION, e); - QueryTenantError exc = new QueryTenantError(e.getMessage(), MsoExceptionCategory.INTERNAL); - return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build(); - } - QueryTenantResponse resp = new QueryTenantResponse(tenant.getTenantId(), tenant.getTenantName(), tenant.getMetadata()); - return Response.status(HttpServletResponse.SC_OK).entity(resp).build(); - } - - /* - URL - EP: //http://host:8080/tenants/rest - Resource: /v1/tenants/rollback - REQ - {"cloudSiteId": "DAN", - "tenantId": "f58abb05041d4ff384d4d22d1ccd2a6c", - "msoRequest": { - "requestId": "ra1", - "serviceInstanceId": "sa1" - } - } - RESP: - {"tenantDeleted": true} - */ - @DELETE - @Path("") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "RollbackTenant", - response = Response.class, - notes = "Rollback an existing tenant") - @ApiResponses({ - @ApiResponse(code = 200, message = "tenant has been successfully rolledback"), - @ApiResponse(code = 500, message = "rollback tenant failed") }) - public Response rollbackTenant( - @ApiParam(value = "rollback, command action", required = true) - @QueryParam("rollback") String action, - @ApiParam(value = "RollbackTenantRequest", required = true) - RollbackTenantRequest req) - { - try { - MsoTenantAdapter impl = tenantImpl; - impl.rollbackTenant(req.getTenantRollback()); - } - catch (TenantException te) { - logger.debug(EXCEPTION, te); - RollbackTenantError exc = new RollbackTenantError(te.getFaultInfo().getMessage(), te.getFaultInfo().getCategory(), Boolean.TRUE); - return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build(); - } - catch (Exception e) { - logger.debug(EXCEPTION, e); - RollbackTenantError exc = new RollbackTenantError(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE); - return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build(); - } - - RollbackTenantResponse resp = new RollbackTenantResponse (); - resp.setTenantRolledback(req != null); - return Response.status(HttpServletResponse.SC_OK).entity(resp).build(); - } + private static final String EXCEPTION = "Exception :"; + // RAA? No logging in wrappers + @Autowired + private MsoTenantAdapterImpl tenantImpl; + + + + /* + * URL: EP: http://host:8080/tenants/rest Resource: v1/tenants REQ - metadata? { "cloudSiteId": "DAN", "tenantName": + * "RAA_1", "failIfExists": true, "msoRequest": { "requestId": "ra1", "serviceInstanceId": "sa1" }} RESP- { + * "cloudSiteId": "DAN", "tenantId": "128e10b9996d43a7874f19bbc4eb6749", "tenantCreated": true, "tenantRollback": { + * "tenantId": "128e10b9996d43a7874f19bbc4eb6749", "cloudId": "DAN", // RAA? cloudId instead of cloudSiteId + * "tenantCreated": true, "msoRequest": { "requestId": "ra1", "serviceInstanceId": "sa1" } } } + */ + @POST + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "CreateTenant", response = Response.class, + notes = "Creates a new tenant, CreateTenantRequest data is required") + @ApiResponses({@ApiResponse(code = 200, message = "tenant has been successfully created"), + @ApiResponse(code = 500, message = "create tenant failed")}) + public Response createTenant( + @ApiParam(value = "details of tenant being created", required = true) CreateTenantRequest req) { + logger.debug("createTenant enter: {}", req.toJsonString()); + + String newTenantId = null; + TenantRollback tenantRollback = new TenantRollback(); + + try { + Holder<String> htenant = new Holder<>(); + Holder<TenantRollback> hrollback = new Holder<>(); + MsoTenantAdapter impl = tenantImpl; + impl.createTenant(req.getCloudSiteId(), req.getTenantName(), req.getMetadata(), req.getFailIfExists(), + req.getBackout(), req.getMsoRequest(), htenant, hrollback); + newTenantId = htenant.value; + tenantRollback = hrollback.value; + + } catch (TenantAlreadyExists tae) { + logger.debug(EXCEPTION, tae); + CreateTenantError exc = + new CreateTenantError(tae.getMessage(), tae.getFaultInfo().getCategory(), Boolean.TRUE); + return Response.status(HttpServletResponse.SC_NOT_IMPLEMENTED).entity(exc).build(); + } catch (TenantException te) { + logger.debug(EXCEPTION, te); + CreateTenantError exc = new CreateTenantError(te.getFaultInfo().getMessage(), + te.getFaultInfo().getCategory(), Boolean.TRUE); + return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build(); + } catch (Exception e) { + logger.debug(EXCEPTION, e); + CreateTenantError exc = new CreateTenantError(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE); + return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build(); + } + + CreateTenantResponse resp = new CreateTenantResponse(req.getCloudSiteId(), newTenantId, + tenantRollback.getTenantCreated(), tenantRollback); + return Response.status(HttpServletResponse.SC_OK).entity(resp).build(); + } + + /* + * URL: http://host:8080/tenants/rest Resource: v1/tenant/tennatId REQ: {"cloudSiteId": "DAN", "tenantId": + * "ca84cd3d3df44272845da554656b3ace", "msoRequest": { "requestId": "ra1", "serviceInstanceId": "sa1" } } RESP: + * {"tenantDeleted": true} + */ + @DELETE + @Path("{tenantId}") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "DeleteTenant", response = Response.class, notes = "Delete an existing tenant") + @ApiResponses({@ApiResponse(code = 200, message = "tenant has been successfully deleted"), + @ApiResponse(code = 500, message = "delete tenant failed")}) + public Response deleteTenant( + @ApiParam(value = "tenantId of tenant being deleted", + required = true) @PathParam("tenantId") String tenantId, + @ApiParam(value = "DeleteTenantRequest object containing additional information of tenant being deleted", + required = false) DeleteTenantRequest req) { + boolean tenantDeleted = false; + + try { + Holder<Boolean> deleted = new Holder<>(); + MsoTenantAdapter impl = tenantImpl; + impl.deleteTenant(req.getCloudSiteId(), req.getTenantId(), req.getMsoRequest(), deleted); + tenantDeleted = deleted.value; + } catch (TenantException te) { + logger.debug(EXCEPTION, te); + DeleteTenantError exc = new DeleteTenantError(te.getFaultInfo().getMessage(), + te.getFaultInfo().getCategory(), Boolean.TRUE); + return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build(); + } catch (Exception e) { + logger.debug(EXCEPTION, e); + DeleteTenantError exc = new DeleteTenantError(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE); + return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build(); + } + DeleteTenantResponse resp = new DeleteTenantResponse(); + resp.setTenantDeleted(tenantDeleted); + return Response.status(HttpServletResponse.SC_OK).entity(resp).build(); + } + + /* + * URL EP://http://host:8080/tenants/rest Resource: /v1/tenants Params:?tenantNameOrId=RAA_1&cloudSiteId=DAN RESP { + * "tenantId": "214b428a1f554c02935e66330f6a5409", "tenantName": "RAA_1", "metadata": {} } + */ + @GET + @Path("{tenantId}") + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "QueryTenant", response = Response.class, notes = "Query an existing tenant") + @ApiResponses({@ApiResponse(code = 200, message = "tenant has been successfully queried"), + @ApiResponse(code = 500, message = "query tenant failed")}) + public Response queryTenant(@ApiParam(value = "tenantId", required = true) @PathParam("tenantId") String tenantId, + // @QueryParam("tenantNameOrId") String tenantNameOrId, //RAA? diff from doc + @ApiParam(value = "cloudSiteId", required = true) @QueryParam("cloudSiteId") String cloudSiteId, + @ApiParam(value = "msoRequest.requestId", + required = true) @QueryParam("msoRequest.requestId") String requestId, + @ApiParam(value = "msoRequest.serviceInstanceId", + required = true) @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId) { + MsoTenant tenant = null; + try { + Holder<String> htenant = new Holder<>(); + Holder<String> tenantName = new Holder<>(); + Holder<Map<String, String>> metadata = new Holder<>(); + MsoTenantAdapter impl = tenantImpl; + impl.queryTenant(cloudSiteId, tenantId, null, htenant, tenantName, metadata); + tenant = new MsoTenant(htenant.value, tenantName.value, metadata.value); + + } catch (TenantException te) { + logger.debug(EXCEPTION, te); + QueryTenantError exc = + new QueryTenantError(te.getFaultInfo().getMessage(), te.getFaultInfo().getCategory()); + return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build(); + } catch (Exception e) { + logger.debug(EXCEPTION, e); + QueryTenantError exc = new QueryTenantError(e.getMessage(), MsoExceptionCategory.INTERNAL); + return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build(); + } + QueryTenantResponse resp = + new QueryTenantResponse(tenant.getTenantId(), tenant.getTenantName(), tenant.getMetadata()); + return Response.status(HttpServletResponse.SC_OK).entity(resp).build(); + } + + /* + * URL EP: //http://host:8080/tenants/rest Resource: /v1/tenants/rollback REQ {"cloudSiteId": "DAN", "tenantId": + * "f58abb05041d4ff384d4d22d1ccd2a6c", "msoRequest": { "requestId": "ra1", "serviceInstanceId": "sa1" } } RESP: + * {"tenantDeleted": true} + */ + @DELETE + @Path("") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "RollbackTenant", response = Response.class, notes = "Rollback an existing tenant") + @ApiResponses({@ApiResponse(code = 200, message = "tenant has been successfully rolledback"), + @ApiResponse(code = 500, message = "rollback tenant failed")}) + public Response rollbackTenant( + @ApiParam(value = "rollback, command action", required = true) @QueryParam("rollback") String action, + @ApiParam(value = "RollbackTenantRequest", required = true) RollbackTenantRequest req) { + try { + MsoTenantAdapter impl = tenantImpl; + impl.rollbackTenant(req.getTenantRollback()); + } catch (TenantException te) { + logger.debug(EXCEPTION, te); + RollbackTenantError exc = new RollbackTenantError(te.getFaultInfo().getMessage(), + te.getFaultInfo().getCategory(), Boolean.TRUE); + return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build(); + } catch (Exception e) { + logger.debug(EXCEPTION, e); + RollbackTenantError exc = + new RollbackTenantError(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE); + return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(exc).build(); + } + + RollbackTenantResponse resp = new RollbackTenantResponse(); + resp.setTenantRolledback(req != null); + return Response.status(HttpServletResponse.SC_OK).entity(resp).build(); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantAlreadyExists.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantAlreadyExists.java index 5b8e7c7294..8955eb50c6 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantAlreadyExists.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantAlreadyExists.java @@ -23,23 +23,23 @@ package org.onap.so.adapters.tenant.exceptions; import javax.xml.ws.WebFault; - import org.onap.so.openstack.exceptions.MsoExceptionCategory; /** - * This class reports an exception when trying to create a VNF when another - * VNF of the same name already exists in the target cloud/tenant. Note that - * the createVnf method suppresses this exception by default. + * This class reports an exception when trying to create a VNF when another VNF of the same name already exists in the + * target cloud/tenant. Note that the createVnf method suppresses this exception by default. * * */ -@WebFault (name="TenantAlreadyExists", faultBean="org.onap.so.adapters.tenant.exceptions.TenantExceptionBean", targetNamespace="http://org.onap.so/tenant") +@WebFault(name = "TenantAlreadyExists", faultBean = "org.onap.so.adapters.tenant.exceptions.TenantExceptionBean", + targetNamespace = "http://org.onap.so/tenant") public class TenantAlreadyExists extends TenantException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public TenantAlreadyExists (String name, String cloudId, String tenantId) { - super("Tenant " + name + " already exists in " + cloudId + " with ID " + tenantId, MsoExceptionCategory.USERDATA); - } + public TenantAlreadyExists(String name, String cloudId, String tenantId) { + super("Tenant " + name + " already exists in " + cloudId + " with ID " + tenantId, + MsoExceptionCategory.USERDATA); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantException.java index b8074ef7fc..998da98c8d 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantException.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantException.java @@ -23,53 +23,53 @@ package org.onap.so.adapters.tenant.exceptions; import javax.xml.ws.WebFault; - import org.onap.so.openstack.exceptions.MsoException; import org.onap.so.openstack.exceptions.MsoExceptionCategory; /** - * This class simply extends Exception (without addition additional functionality) - * to provide an identifier for Tenant related exceptions on create, delete, query. + * This class simply extends Exception (without addition additional functionality) to provide an identifier for Tenant + * related exceptions on create, delete, query. * * */ -@WebFault (name="TenantException", faultBean="org.onap.so.adapters.tenant.exceptions.TenantExceptionBean", targetNamespace="http://org.onap.so/tenant") +@WebFault(name = "TenantException", faultBean = "org.onap.so.adapters.tenant.exceptions.TenantExceptionBean", + targetNamespace = "http://org.onap.so/tenant") public class TenantException extends Exception { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; + + private TenantExceptionBean faultInfo; + + public TenantException(String msg) { + super(msg); + faultInfo = new TenantExceptionBean(msg); + } + + public TenantException(String msg, Throwable e) { + super(msg, e); + faultInfo = new TenantExceptionBean(msg); + } + + public TenantException(String msg, MsoExceptionCategory category) { + super(msg); + faultInfo = new TenantExceptionBean(msg, category); + } - private TenantExceptionBean faultInfo; - - public TenantException (String msg) { - super(msg); - faultInfo = new TenantExceptionBean (msg); - } - - public TenantException (String msg, Throwable e) { - super (msg, e); - faultInfo = new TenantExceptionBean (msg); - } + public TenantException(String msg, MsoExceptionCategory category, Throwable e) { + super(msg, e); + faultInfo = new TenantExceptionBean(msg, category); + } - public TenantException (String msg, MsoExceptionCategory category) { - super(msg); - faultInfo = new TenantExceptionBean (msg, category); - } - - public TenantException (String msg, MsoExceptionCategory category, Throwable e) { - super (msg, e); - faultInfo = new TenantExceptionBean (msg, category); - } - - public TenantException (MsoException e) { - super (e); - faultInfo = new TenantExceptionBean (e.getContextMessage(), e.getCategory()); - } + public TenantException(MsoException e) { + super(e); + faultInfo = new TenantExceptionBean(e.getContextMessage(), e.getCategory()); + } - public TenantExceptionBean getFaultInfo() { - return faultInfo; - } + public TenantExceptionBean getFaultInfo() { + return faultInfo; + } - public void setFaultInfo(TenantExceptionBean faultInfo) { - this.faultInfo = faultInfo; - } + public void setFaultInfo(TenantExceptionBean faultInfo) { + this.faultInfo = faultInfo; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionBean.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionBean.java index 1dada60e93..2d9260615a 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionBean.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tenant/exceptions/TenantExceptionBean.java @@ -22,7 +22,6 @@ package org.onap.so.adapters.tenant.exceptions; import java.io.Serializable; - import org.onap.so.openstack.exceptions.MsoExceptionCategory; /** @@ -33,32 +32,32 @@ public class TenantExceptionBean implements Serializable { private static final long serialVersionUID = -9062290006520066109L; private String message; - private MsoExceptionCategory category; + private MsoExceptionCategory category; - public TenantExceptionBean () {} + public TenantExceptionBean() {} - public TenantExceptionBean (String message) { - this.message = message; - } + public TenantExceptionBean(String message) { + this.message = message; + } - public TenantExceptionBean (String message, MsoExceptionCategory category) { - this.message = message; - this.category = category; - } + public TenantExceptionBean(String message, MsoExceptionCategory category) { + this.message = message; + this.category = category; + } - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } - public void setMessage(String message) { - this.message = message; - } + public void setMessage(String message) { + this.message = message; + } - public MsoExceptionCategory getCategory () { - return category; - } + public MsoExceptionCategory getCategory() { + return category; + } - public void setCategory (MsoExceptionCategory category) { - this.category = category; - } + public void setCategory(MsoExceptionCategory category) { + this.category = category; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/GenericValetResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/GenericValetResponse.java index 30062a0144..6946fb1f90 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/GenericValetResponse.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/GenericValetResponse.java @@ -23,50 +23,57 @@ package org.onap.so.adapters.valet; import org.apache.commons.lang3.builder.ToStringBuilder; /* - * The purpose of this class is to encapsulate the possible responses from Valet in to one generic class - * that the vnf adapter can more easily utilize. This will ensure we get an object back. Any status - * code other than 200 will be treated as a failure. We may still get a 200 back - but the - * ValetStatus.status is "failed" - which will also be treated as a failure. The T class is - * expected to be one of the Valet*Response pojos. + * The purpose of this class is to encapsulate the possible responses from Valet in to one generic class that the vnf + * adapter can more easily utilize. This will ensure we get an object back. Any status code other than 200 will be + * treated as a failure. We may still get a 200 back - but the ValetStatus.status is "failed" - which will also be + * treated as a failure. The T class is expected to be one of the Valet*Response pojos. */ public class GenericValetResponse<T> { - private int statusCode; - private String errorMessage; - private T returnObject; - + private int statusCode; + private String errorMessage; + private T returnObject; + + + public GenericValetResponse(int statusCode, String errorMessage, T obj) { + super(); + this.statusCode = statusCode; + this.errorMessage = errorMessage; + this.returnObject = obj; + } + + public GenericValetResponse() { + this(-1, "not set", null); + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("statusCode", statusCode).append("errorMessage", errorMessage) + .append("returnObject", returnObject).toString(); + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public String getErrorMessage() { + return this.errorMessage; + } + + public void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + + public int getStatusCode() { + return this.statusCode; + } + + public void setReturnObject(T obj) { + this.returnObject = obj; + } + + public T getReturnObject() { + return this.returnObject; + } - public GenericValetResponse(int statusCode, String errorMessage, T obj) { - super(); - this.statusCode = statusCode; - this.errorMessage = errorMessage; - this.returnObject = obj; - } - public GenericValetResponse() { - this(-1, "not set", null); - } - @Override - public String toString() { - return new ToStringBuilder(this).append("statusCode", statusCode).append("errorMessage", errorMessage) - .append("returnObject", returnObject).toString(); - } - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - public String getErrorMessage() { - return this.errorMessage; - } - public void setStatusCode(int statusCode) { - this.statusCode = statusCode; - } - public int getStatusCode() { - return this.statusCode; - } - public void setReturnObject(T obj) { - this.returnObject = obj; - } - public T getReturnObject() { - return this.returnObject; - } - } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/ValetClient.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/ValetClient.java index b8e504084b..34177ff5a3 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/ValetClient.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/ValetClient.java @@ -58,278 +58,292 @@ public class ValetClient { private static Logger logger = LoggerFactory.getLogger(ValetClient.class); - @Autowired - private Environment environment; - - private static final String VALET_BASE_URL = "org.onap.so.adapters.valet.base_url"; - private static final String VALET_BASE_PATH = "org.onap.so.adapters.valet.base_path"; - private static final String VALET_AUTH = "org.onap.so.adapters.valet.basic_auth"; - private static final String REQ_ID_HEADER_NAME = "X-RequestID"; - protected static final String NO_STATUS_RETURNED = "no status returned from Valet"; - - private static final String DEFAULT_BASE_URL = "http://localhost:8080/"; - private static final String DEFAULT_BASE_PATH = "api/valet/placement/v1"; - private static final String DEFAULT_AUTH_STRING = ""; - private static final String REQUEST_ID="requestId"; - private static final String HEADERS=", headers="; - private static final String BODY=", body="; - @Autowired - private ObjectMapper mapper; - - protected String baseUrl; - protected String basePath; - protected String authString; - - /* - * Setup the properties needed from properties file. Each will fall to a default - */ - @PostConstruct - private void setupParams() { - try { + @Autowired + private Environment environment; + + private static final String VALET_BASE_URL = "org.onap.so.adapters.valet.base_url"; + private static final String VALET_BASE_PATH = "org.onap.so.adapters.valet.base_path"; + private static final String VALET_AUTH = "org.onap.so.adapters.valet.basic_auth"; + private static final String REQ_ID_HEADER_NAME = "X-RequestID"; + protected static final String NO_STATUS_RETURNED = "no status returned from Valet"; + + private static final String DEFAULT_BASE_URL = "http://localhost:8080/"; + private static final String DEFAULT_BASE_PATH = "api/valet/placement/v1"; + private static final String DEFAULT_AUTH_STRING = ""; + private static final String REQUEST_ID = "requestId"; + private static final String HEADERS = ", headers="; + private static final String BODY = ", body="; + @Autowired + private ObjectMapper mapper; + + protected String baseUrl; + protected String basePath; + protected String authString; + + /* + * Setup the properties needed from properties file. Each will fall to a default + */ + @PostConstruct + private void setupParams() { + try { this.baseUrl = this.environment.getProperty(ValetClient.VALET_BASE_URL, ValetClient.DEFAULT_BASE_URL); this.basePath = this.environment.getProperty(ValetClient.VALET_BASE_PATH, ValetClient.DEFAULT_BASE_PATH); - this.authString = this.environment.getProperty(ValetClient.VALET_AUTH, ValetClient.DEFAULT_AUTH_STRING); - } catch (Exception e) { - logger.debug("Error retrieving valet properties. {}", e.getMessage()); + this.authString = this.environment.getProperty(ValetClient.VALET_AUTH, ValetClient.DEFAULT_AUTH_STRING); + } catch (Exception e) { + logger.debug("Error retrieving valet properties. {}", e.getMessage()); + } + } + + /* + * This method will be invoked to send a Create request to Valet. + */ + public GenericValetResponse<ValetCreateResponse> callValetCreateRequest(String requestId, String regionId, + String ownerId, String tenantId, String serviceInstanceId, String vnfId, String vnfName, String vfModuleId, + String vfModuleName, String keystoneUrl, HeatRequest heatRequest) throws Exception { + ResponseEntity<ValetCreateResponse> response = null; + GenericValetResponse<ValetCreateResponse> gvr = null; + + try { + UriBuilder builder = UriBuilder.fromPath(baseUrl).path(basePath).queryParam(REQUEST_ID, requestId); + URI uri = builder.build(); + + ValetCreateRequest vcr = this.createValetCreateRequest(regionId, ownerId, tenantId, serviceInstanceId, + vnfId, vnfName, vfModuleId, vfModuleName, keystoneUrl, heatRequest); + String body = mapper.writeValueAsString(vcr); + HttpHeaders headers = generateHeaders(requestId); + HttpEntity<String> entity = new HttpEntity<>(body, headers); + + response = getRestTemplate().exchange(uri, HttpMethod.POST, entity, ValetCreateResponse.class); + gvr = this.getGVRFromResponse(response); + } catch (Exception e) { + logger.error("An exception occurred in callValetCreateRequest", e); + throw e; + } + return gvr; + } + + private RestTemplate getRestTemplate() { + RestTemplate restTemplate = new RestTemplate(); + restTemplate + .setRequestFactory(new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory())); + return restTemplate; + } + + /* + * This method will be invoked to send an Update request to Valet. + */ + public GenericValetResponse<ValetUpdateResponse> callValetUpdateRequest(String requestId, String regionId, + String ownerId, String tenantId, String serviceInstanceId, String vnfId, String vnfName, String vfModuleId, + String vfModuleName, String keystoneUrl, HeatRequest heatRequest) throws Exception { + ResponseEntity<ValetUpdateResponse> response = null; + GenericValetResponse<ValetUpdateResponse> gvr = null; + + try { + UriBuilder builder = UriBuilder.fromPath(baseUrl).path(basePath).queryParam(REQUEST_ID, requestId); + URI uri = builder.build(); + + ValetUpdateRequest vur = this.createValetUpdateRequest(regionId, ownerId, tenantId, serviceInstanceId, + vnfId, vnfName, vfModuleId, vfModuleName, keystoneUrl, heatRequest); + String body = mapper.writeValueAsString(vur); + HttpHeaders headers = generateHeaders(requestId); + HttpEntity<String> entity = new HttpEntity<>(body, headers); + + + response = getRestTemplate().exchange(uri, HttpMethod.PUT, entity, ValetUpdateResponse.class); + gvr = this.getGVRFromResponse(response); + } catch (Exception e) { + logger.error("An exception occurred in callValetUpdateRequest", e); + throw e; + } + return gvr; + } + + /* + * This method will be invoked to send a Delete request to Valet. + */ + public GenericValetResponse<ValetDeleteResponse> callValetDeleteRequest(String requestId, String regionId, + String ownerId, String tenantId, String vfModuleId, String vfModuleName) throws Exception { + ResponseEntity<ValetDeleteResponse> response = null; + GenericValetResponse<ValetDeleteResponse> gvr = null; + + try { + UriBuilder builder = UriBuilder.fromPath(baseUrl).path(basePath).queryParam(REQUEST_ID, requestId); + URI uri = builder.build(); + + ValetDeleteRequest vdr = + this.createValetDeleteRequest(regionId, ownerId, tenantId, vfModuleId, vfModuleName); + + String body = mapper.writeValueAsString(vdr); + HttpHeaders headers = generateHeaders(requestId); + HttpEntity<String> entity = new HttpEntity<>(body, headers); + + + response = getRestTemplate().exchange(uri, HttpMethod.DELETE, entity, ValetDeleteResponse.class); + gvr = this.getGVRFromResponse(response); + } catch (Exception e) { + logger.error("An exception occurred in callValetDeleteRequest", e); + throw e; + } + return gvr; + } + + /* + * This method is called to invoke a Confirm request to Valet. + */ + public GenericValetResponse<ValetConfirmResponse> callValetConfirmRequest(String requestId, String stackId) + throws Exception { + ResponseEntity<ValetConfirmResponse> response = null; + GenericValetResponse<ValetConfirmResponse> gvr = null; + + try { + UriBuilder builder = UriBuilder.fromPath(this.baseUrl).path(this.basePath).path("{requestId}/confirm/"); + URI uri = builder.build(requestId); + + ValetConfirmRequest vcr = this.createValetConfirmRequest(stackId); + + String body = mapper.writeValueAsString(vcr); + HttpHeaders headers = generateHeaders(requestId); + HttpEntity<String> entity = new HttpEntity<>(body, headers); + logger.debug("valet confirm req: {} {} {} {} {}", uri, HEADERS, headers, BODY, body); + + response = getRestTemplate().exchange(uri, HttpMethod.PUT, entity, ValetConfirmResponse.class); + gvr = this.getGVRFromResponse(response); + } catch (Exception e) { + logger.error("An exception occurred in callValetConfirmRequest", e); + throw e; + } + return gvr; + } + + /* + * This method is called to invoke a Rollback request to Valet. + */ + public GenericValetResponse<ValetRollbackResponse> callValetRollbackRequest(String requestId, String stackId, + Boolean suppressRollback, String errorMessage) throws Exception { + ResponseEntity<ValetRollbackResponse> response = null; + GenericValetResponse<ValetRollbackResponse> gvr = null; + + try { + UriBuilder builder = UriBuilder.fromPath(this.baseUrl).path(this.basePath).path("{requestId}/rollback/"); + URI uri = builder.build(requestId); + + ValetRollbackRequest vrr = this.createValetRollbackRequest(stackId, suppressRollback, errorMessage); + + String body = mapper.writeValueAsString(vrr); + HttpHeaders headers = generateHeaders(requestId); + HttpEntity<String> entity = new HttpEntity<>(body, headers); + + + response = getRestTemplate().exchange(uri, HttpMethod.PUT, entity, ValetRollbackResponse.class); + gvr = this.getGVRFromResponse(response); + } catch (Exception e) { + logger.error("An exception occurred in callValetRollbackRequest", e); + throw e; + } + return gvr; + } + + /* + * This method is to construct the ValetCreateRequest pojo + */ + private ValetCreateRequest createValetCreateRequest(String regionId, String ownerId, String tenantId, + String serviceInstanceId, String vnfId, String vnfName, String vfModuleId, String vfModuleName, + String keystoneUrl, HeatRequest heatRequest) { + ValetCreateRequest vcr = new ValetCreateRequest(); + vcr.setHeatRequest(heatRequest); + vcr.setKeystoneUrl(keystoneUrl); + vcr.setRegionId(regionId); + vcr.setOwnerId(ownerId); + vcr.setServiceInstanceId(serviceInstanceId); + vcr.setTenantId(tenantId); + vcr.setVfModuleId(vfModuleId); + vcr.setVfModuleName(vfModuleName); + vcr.setVnfId(vnfId); + vcr.setVnfName(vnfName); + + return vcr; + } + + /* + * This method is to construct the ValetUpdateRequest pojo + */ + private ValetUpdateRequest createValetUpdateRequest(String regionId, String ownerId, String tenantId, + String serviceInstanceId, String vnfId, String vnfName, String vfModuleId, String vfModuleName, + String keystoneUrl, HeatRequest heatRequest) { + ValetUpdateRequest vur = new ValetUpdateRequest(); + vur.setHeatRequest(heatRequest); + vur.setKeystoneUrl(keystoneUrl); + vur.setRegionId(regionId == null ? "" : regionId); + vur.setOwnerId(ownerId == null ? "" : ownerId); + vur.setServiceInstanceId(serviceInstanceId == null ? "" : serviceInstanceId); + vur.setTenantId(tenantId == null ? "" : tenantId); + vur.setVfModuleId(vfModuleId == null ? "" : vfModuleId); + vur.setVfModuleName(vfModuleName == null ? "" : vfModuleName); + vur.setVnfId(vnfId == null ? "" : vnfId); + vur.setVnfName(vnfName == null ? "" : vnfName); + + return vur; + } + + /* + * This method is to construct the ValetDeleteRequest pojo + */ + private ValetDeleteRequest createValetDeleteRequest(String regionId, String ownerId, String tenantId, + String vfModuleId, String vfModuleName) { + ValetDeleteRequest vdr = new ValetDeleteRequest(); + vdr.setRegionId(regionId == null ? "" : regionId); + vdr.setOwnerId(ownerId == null ? "" : ownerId); + vdr.setTenantId(tenantId == null ? "" : tenantId); + vdr.setVfModuleId(vfModuleId == null ? "" : vfModuleId); + vdr.setVfModuleName(vfModuleName == null ? "" : vfModuleName); + + return vdr; + } + + /* + * This method is to construct the ValetDeleteRequest pojo + */ + private ValetConfirmRequest createValetConfirmRequest(String stackId) { + ValetConfirmRequest vcr = new ValetConfirmRequest(); + vcr.setStackId(stackId); + + return vcr; + } + + /* + * This method is to construct the ValetRollbackRequest pojo + */ + private ValetRollbackRequest createValetRollbackRequest(String stackId, Boolean suppressRollback, + String errorMessage) { + ValetRollbackRequest vrr = new ValetRollbackRequest(); + vrr.setStackId(stackId); + vrr.setSuppressRollback(suppressRollback); + vrr.setErrorMessage(errorMessage); + + return vrr; + } + + private HttpHeaders generateHeaders(String requestId) { + HttpHeaders headers = new HttpHeaders(); + headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + if (!(this.authString == null || this.authString.isEmpty())) { + headers.add("Authorization", "Basic " + this.authString); + } + headers.add(ValetClient.REQ_ID_HEADER_NAME, requestId); + + return headers; + } + + private <T> GenericValetResponse<T> getGVRFromResponse(ResponseEntity<T> response) { + GenericValetResponse<T> gvr = null; + if (response != null) { + T responseObj = response.getBody(); + gvr = new GenericValetResponse<>(response.getStatusCodeValue(), ValetClient.NO_STATUS_RETURNED, + responseObj); + + } else { + gvr = new GenericValetResponse<>(-1, ValetClient.NO_STATUS_RETURNED, null); + } + return gvr; } - } - - /* - * This method will be invoked to send a Create request to Valet. - */ - public GenericValetResponse<ValetCreateResponse> callValetCreateRequest(String requestId, String regionId, String ownerId, String tenantId, String serviceInstanceId, - String vnfId, String vnfName, String vfModuleId, String vfModuleName, String keystoneUrl, HeatRequest heatRequest) throws Exception { - ResponseEntity<ValetCreateResponse> response = null; - GenericValetResponse<ValetCreateResponse> gvr = null; - - try { - UriBuilder builder = UriBuilder.fromPath(baseUrl).path(basePath).queryParam(REQUEST_ID, requestId); - URI uri = builder.build(); - - ValetCreateRequest vcr = this.createValetCreateRequest(regionId, ownerId, tenantId, serviceInstanceId, vnfId, vnfName, vfModuleId, vfModuleName, keystoneUrl, heatRequest); - String body = mapper.writeValueAsString(vcr); - HttpHeaders headers = generateHeaders(requestId); - HttpEntity<String> entity = new HttpEntity<>(body, headers); - - response = getRestTemplate().exchange(uri, HttpMethod.POST, entity, ValetCreateResponse.class); - gvr = this.getGVRFromResponse(response); - } catch (Exception e) { - logger.error("An exception occurred in callValetCreateRequest", e); - throw e; - } - return gvr; - } - - private RestTemplate getRestTemplate(){ - RestTemplate restTemplate = new RestTemplate(); - restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory())); - return restTemplate; - } - - /* - * This method will be invoked to send an Update request to Valet. - */ - public GenericValetResponse<ValetUpdateResponse> callValetUpdateRequest(String requestId, String regionId, String ownerId, String tenantId, String serviceInstanceId, - String vnfId, String vnfName, String vfModuleId, String vfModuleName, String keystoneUrl, HeatRequest heatRequest) throws Exception { - ResponseEntity<ValetUpdateResponse> response = null; - GenericValetResponse<ValetUpdateResponse> gvr = null; - - try { - UriBuilder builder = UriBuilder.fromPath(baseUrl).path(basePath).queryParam(REQUEST_ID, requestId); - URI uri = builder.build(); - - ValetUpdateRequest vur = this.createValetUpdateRequest(regionId, ownerId, tenantId, serviceInstanceId, vnfId, vnfName, vfModuleId, vfModuleName, keystoneUrl, heatRequest); - String body = mapper.writeValueAsString(vur); - HttpHeaders headers = generateHeaders(requestId); - HttpEntity<String> entity = new HttpEntity<>(body, headers); - - - response = getRestTemplate().exchange(uri, HttpMethod.PUT, entity, ValetUpdateResponse.class); - gvr = this.getGVRFromResponse(response); - } catch (Exception e) { - logger.error("An exception occurred in callValetUpdateRequest", e); - throw e; - } - return gvr; - } - - /* - * This method will be invoked to send a Delete request to Valet. - */ - public GenericValetResponse<ValetDeleteResponse> callValetDeleteRequest(String requestId, String regionId, String ownerId, String tenantId, String vfModuleId, String vfModuleName) throws Exception { - ResponseEntity<ValetDeleteResponse> response = null; - GenericValetResponse<ValetDeleteResponse> gvr = null; - - try { - UriBuilder builder = UriBuilder.fromPath(baseUrl).path(basePath).queryParam(REQUEST_ID, requestId); - URI uri = builder.build(); - - ValetDeleteRequest vdr = this.createValetDeleteRequest(regionId, ownerId, tenantId, vfModuleId, vfModuleName); - - String body = mapper.writeValueAsString(vdr); - HttpHeaders headers = generateHeaders(requestId); - HttpEntity<String> entity = new HttpEntity<>(body, headers); - - - response = getRestTemplate().exchange(uri, HttpMethod.DELETE, entity, ValetDeleteResponse.class); - gvr = this.getGVRFromResponse(response); - } catch (Exception e) { - logger.error("An exception occurred in callValetDeleteRequest", e); - throw e; - } - return gvr; - } - - /* - * This method is called to invoke a Confirm request to Valet. - */ - public GenericValetResponse<ValetConfirmResponse> callValetConfirmRequest(String requestId, String stackId) throws Exception { - ResponseEntity<ValetConfirmResponse> response = null; - GenericValetResponse<ValetConfirmResponse> gvr = null; - - try { - UriBuilder builder = UriBuilder.fromPath(this.baseUrl).path(this.basePath).path("{requestId}/confirm/"); - URI uri = builder.build(requestId); - - ValetConfirmRequest vcr = this.createValetConfirmRequest(stackId); - - String body = mapper.writeValueAsString(vcr); - HttpHeaders headers = generateHeaders(requestId); - HttpEntity<String> entity = new HttpEntity<>(body, headers); - logger.debug("valet confirm req: {} {} {} {} {}", uri, HEADERS, headers, BODY, body); - - response = getRestTemplate().exchange(uri, HttpMethod.PUT, entity, ValetConfirmResponse.class); - gvr = this.getGVRFromResponse(response); - } catch (Exception e) { - logger.error("An exception occurred in callValetConfirmRequest", e); - throw e; - } - return gvr; - } - - /* - * This method is called to invoke a Rollback request to Valet. - */ - public GenericValetResponse<ValetRollbackResponse> callValetRollbackRequest(String requestId, String stackId, Boolean suppressRollback, String errorMessage) throws Exception { - ResponseEntity<ValetRollbackResponse> response = null; - GenericValetResponse<ValetRollbackResponse> gvr = null; - - try { - UriBuilder builder = UriBuilder.fromPath(this.baseUrl).path(this.basePath).path("{requestId}/rollback/"); - URI uri = builder.build(requestId); - - ValetRollbackRequest vrr = this.createValetRollbackRequest(stackId, suppressRollback, errorMessage); - - String body = mapper.writeValueAsString(vrr); - HttpHeaders headers = generateHeaders(requestId); - HttpEntity<String> entity = new HttpEntity<>(body, headers); - - - response = getRestTemplate().exchange(uri, HttpMethod.PUT, entity, ValetRollbackResponse.class); - gvr = this.getGVRFromResponse(response); - } catch (Exception e) { - logger.error("An exception occurred in callValetRollbackRequest", e); - throw e; - } - return gvr; - } - - /* - * This method is to construct the ValetCreateRequest pojo - */ - private ValetCreateRequest createValetCreateRequest(String regionId, String ownerId, String tenantId, String serviceInstanceId, - String vnfId, String vnfName, String vfModuleId, String vfModuleName, String keystoneUrl, HeatRequest heatRequest) { - ValetCreateRequest vcr = new ValetCreateRequest(); - vcr.setHeatRequest(heatRequest); - vcr.setKeystoneUrl(keystoneUrl); - vcr.setRegionId(regionId); - vcr.setOwnerId(ownerId); - vcr.setServiceInstanceId(serviceInstanceId); - vcr.setTenantId(tenantId); - vcr.setVfModuleId(vfModuleId); - vcr.setVfModuleName(vfModuleName); - vcr.setVnfId(vnfId); - vcr.setVnfName(vnfName); - - return vcr; - } - - /* - * This method is to construct the ValetUpdateRequest pojo - */ - private ValetUpdateRequest createValetUpdateRequest(String regionId, String ownerId, String tenantId, String serviceInstanceId, - String vnfId, String vnfName, String vfModuleId, String vfModuleName, String keystoneUrl, HeatRequest heatRequest) { - ValetUpdateRequest vur = new ValetUpdateRequest(); - vur.setHeatRequest(heatRequest); - vur.setKeystoneUrl(keystoneUrl); - vur.setRegionId(regionId == null ? "" : regionId); - vur.setOwnerId(ownerId == null ? "" : ownerId); - vur.setServiceInstanceId(serviceInstanceId == null ? "" : serviceInstanceId); - vur.setTenantId(tenantId == null ? "" : tenantId); - vur.setVfModuleId(vfModuleId == null ? "" : vfModuleId); - vur.setVfModuleName(vfModuleName == null ? "" : vfModuleName); - vur.setVnfId(vnfId == null ? "" : vnfId); - vur.setVnfName(vnfName == null ? "" : vnfName); - - return vur; - } - - /* - * This method is to construct the ValetDeleteRequest pojo - */ - private ValetDeleteRequest createValetDeleteRequest(String regionId, String ownerId, String tenantId, String vfModuleId, String vfModuleName) { - ValetDeleteRequest vdr = new ValetDeleteRequest(); - vdr.setRegionId(regionId == null ? "" : regionId); - vdr.setOwnerId(ownerId == null ? "" : ownerId); - vdr.setTenantId(tenantId == null ? "" : tenantId); - vdr.setVfModuleId(vfModuleId == null ? "" : vfModuleId); - vdr.setVfModuleName(vfModuleName == null ? "" : vfModuleName); - - return vdr; - } - - /* - * This method is to construct the ValetDeleteRequest pojo - */ - private ValetConfirmRequest createValetConfirmRequest(String stackId) { - ValetConfirmRequest vcr = new ValetConfirmRequest(); - vcr.setStackId(stackId); - - return vcr; - } - - /* - * This method is to construct the ValetRollbackRequest pojo - */ - private ValetRollbackRequest createValetRollbackRequest(String stackId, Boolean suppressRollback, String errorMessage) { - ValetRollbackRequest vrr = new ValetRollbackRequest(); - vrr.setStackId(stackId); - vrr.setSuppressRollback(suppressRollback); - vrr.setErrorMessage(errorMessage); - - return vrr; - } - - private HttpHeaders generateHeaders(String requestId) { - HttpHeaders headers = new HttpHeaders(); - headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); - if (!(this.authString == null || this.authString.isEmpty())) { - headers.add("Authorization", "Basic " + this.authString); - } - headers.add(ValetClient.REQ_ID_HEADER_NAME, requestId); - - return headers; - } - - private <T> GenericValetResponse<T> getGVRFromResponse(ResponseEntity<T> response) { - GenericValetResponse<T> gvr = null; - if (response != null) { - T responseObj = response.getBody(); - gvr = new GenericValetResponse<>(response.getStatusCodeValue(), ValetClient.NO_STATUS_RETURNED, responseObj); - - } else { - gvr = new GenericValetResponse<>(-1, ValetClient.NO_STATUS_RETURNED, null); - } - return gvr; - } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/HeatRequest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/HeatRequest.java index 5a28f65db4..c12c89dbff 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/HeatRequest.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/HeatRequest.java @@ -19,108 +19,119 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - + package org.onap.so.adapters.valet.beans; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Objects; - import com.fasterxml.jackson.annotation.JsonProperty; /* - * This class represents the heat request as sent to OpenStack as defined in the - * Valet Placement Operations API + * This class represents the heat request as sent to OpenStack as defined in the Valet Placement Operations API */ public class HeatRequest implements Serializable { - private static final long serialVersionUID = 768026109321305392L; - @JsonProperty("stack_name") - private String stackName; - @JsonProperty("disable_rollback") - private Boolean disableRollback; - @JsonProperty("timeout_mins") - private Integer timeoutMins; - @JsonProperty("template") - private String template; - @JsonProperty("environment") - private String environment; - @JsonProperty("files") - private Map<String, Object> files = new HashMap<>(); - @JsonProperty("parameters") - private Map<String, Object> parameters = new HashMap<>(); - - public HeatRequest(String stackName, boolean disableRollback, int timeoutMins, String template, String environment, Map<String, Object> files, Map<String, Object> parameters) { - super(); - this.stackName = stackName; - this.disableRollback = disableRollback; - this.timeoutMins = timeoutMins; - this.template = template; - this.environment = environment; - this.files = files; - this.parameters = parameters; - } - - public String getStackName() { - return this.stackName; - } - public void setStackName(String stackName) { - this.stackName = stackName; - } - public Boolean getDisableRollback() { - return this.disableRollback; - } - public void setDisableRollback(Boolean disableRollback) { - this.disableRollback = disableRollback; - } - public Integer getTimeoutMins() { - return this.timeoutMins; - } - public void setTimeoutMins(Integer timeoutMins) { - this.timeoutMins = timeoutMins; - } - public String getTemplate() { - return this.template; - } - public void setTemplate(String template) { - this.template = template; - } - public String getEnvironment() { - return this.environment; - } - public void setEnvironment(String environment) { - this.environment = environment; - } - public Map<String, Object> getFiles() { - return this.files; - } - public void setFiles(Map<String, Object> files) { - this.files = files; - } - public Map<String, Object> getParameters() { - return this.parameters; - } - public void setParameters(Map<String, Object> parameters) { - this.parameters = parameters; - } - @Override - public int hashCode() { - return Objects.hash(stackName, disableRollback, timeoutMins, template, environment, files, parameters); - } - @Override - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof HeatRequest)) { - return false; - } - HeatRequest hr = (HeatRequest) o; - return Objects.equals(stackName, hr.stackName) - && Objects.equals(disableRollback, hr.disableRollback) - && Objects.equals(timeoutMins, hr.timeoutMins) - && Objects.equals(template, hr.template) - && Objects.equals(environment, hr.environment) - && Objects.equals(files, hr.files) - && Objects.equals(parameters, hr.parameters); - } + private static final long serialVersionUID = 768026109321305392L; + @JsonProperty("stack_name") + private String stackName; + @JsonProperty("disable_rollback") + private Boolean disableRollback; + @JsonProperty("timeout_mins") + private Integer timeoutMins; + @JsonProperty("template") + private String template; + @JsonProperty("environment") + private String environment; + @JsonProperty("files") + private Map<String, Object> files = new HashMap<>(); + @JsonProperty("parameters") + private Map<String, Object> parameters = new HashMap<>(); + + public HeatRequest(String stackName, boolean disableRollback, int timeoutMins, String template, String environment, + Map<String, Object> files, Map<String, Object> parameters) { + super(); + this.stackName = stackName; + this.disableRollback = disableRollback; + this.timeoutMins = timeoutMins; + this.template = template; + this.environment = environment; + this.files = files; + this.parameters = parameters; + } + + public String getStackName() { + return this.stackName; + } + + public void setStackName(String stackName) { + this.stackName = stackName; + } + + public Boolean getDisableRollback() { + return this.disableRollback; + } + + public void setDisableRollback(Boolean disableRollback) { + this.disableRollback = disableRollback; + } + + public Integer getTimeoutMins() { + return this.timeoutMins; + } + + public void setTimeoutMins(Integer timeoutMins) { + this.timeoutMins = timeoutMins; + } + + public String getTemplate() { + return this.template; + } + + public void setTemplate(String template) { + this.template = template; + } + + public String getEnvironment() { + return this.environment; + } + + public void setEnvironment(String environment) { + this.environment = environment; + } + + public Map<String, Object> getFiles() { + return this.files; + } + + public void setFiles(Map<String, Object> files) { + this.files = files; + } + + public Map<String, Object> getParameters() { + return this.parameters; + } + + public void setParameters(Map<String, Object> parameters) { + this.parameters = parameters; + } + + @Override + public int hashCode() { + return Objects.hash(stackName, disableRollback, timeoutMins, template, environment, files, parameters); + } + + @Override + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof HeatRequest)) { + return false; + } + HeatRequest hr = (HeatRequest) o; + return Objects.equals(stackName, hr.stackName) && Objects.equals(disableRollback, hr.disableRollback) + && Objects.equals(timeoutMins, hr.timeoutMins) && Objects.equals(template, hr.template) + && Objects.equals(environment, hr.environment) && Objects.equals(files, hr.files) + && Objects.equals(parameters, hr.parameters); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetConfirmRequest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetConfirmRequest.java index 36083e8be6..0d6c47b2db 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetConfirmRequest.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetConfirmRequest.java @@ -22,44 +22,47 @@ package org.onap.so.adapters.valet.beans; import java.io.Serializable; import java.util.Objects; - import com.fasterxml.jackson.annotation.JsonProperty; + /* * This class represents the body of a Confirm operation on a Valet Placement API call */ public class ValetConfirmRequest implements Serializable { - private static final long serialVersionUID = 768026109321305392L; - - @JsonProperty("stack_id") - private String stackId; - - public ValetConfirmRequest() { - super(); - } - public ValetConfirmRequest(String stackId) { - super(); - this.stackId = stackId; - } - - public String getStackId() { - return this.stackId; - } - public void setStackId(String stackId) { - this.stackId = stackId; - } - - @Override - public int hashCode() { - return Objects.hash(stackId); - } - @Override - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof ValetConfirmRequest)) { - return false; - } - ValetConfirmRequest vcr = (ValetConfirmRequest) o; - return Objects.equals(stackId, vcr.stackId); - } + private static final long serialVersionUID = 768026109321305392L; + + @JsonProperty("stack_id") + private String stackId; + + public ValetConfirmRequest() { + super(); + } + + public ValetConfirmRequest(String stackId) { + super(); + this.stackId = stackId; + } + + public String getStackId() { + return this.stackId; + } + + public void setStackId(String stackId) { + this.stackId = stackId; + } + + @Override + public int hashCode() { + return Objects.hash(stackId); + } + + @Override + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof ValetConfirmRequest)) { + return false; + } + ValetConfirmRequest vcr = (ValetConfirmRequest) o; + return Objects.equals(stackId, vcr.stackId); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetConfirmResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetConfirmResponse.java index c009da9608..f69b9b7eb8 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetConfirmResponse.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetConfirmResponse.java @@ -25,6 +25,6 @@ import java.io.Serializable; /* This class has no body - placeholder if needed - for the response to a Confirm operation */ public class ValetConfirmResponse implements Serializable { - private static final long serialVersionUID = 768026109321305392L; + private static final long serialVersionUID = 768026109321305392L; } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetCreateRequest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetCreateRequest.java index cb92ecddad..5aac0a167a 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetCreateRequest.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetCreateRequest.java @@ -22,122 +22,137 @@ package org.onap.so.adapters.valet.beans; import java.io.Serializable; import java.util.Objects; - import com.fasterxml.jackson.annotation.JsonProperty; /* * This class represents the body of a Create request operation on a Valet Placement API call */ public class ValetCreateRequest implements Serializable { - private static final long serialVersionUID = 768026109321305392L; - - @JsonProperty("region_id") - private String regionId; - @JsonProperty("owner_id") - private String ownerId; - @JsonProperty("tenant_id") - private String tenantId; - @JsonProperty("service_instance_id") - private String serviceInstanceId; - @JsonProperty("vnf_id") - private String vnfId; - @JsonProperty("vnf_name") - private String vnfName; - @JsonProperty("vf_module_id") - private String vfModuleId; - @JsonProperty("vf_module_name") - private String vfModuleName; - @JsonProperty("keystone_url") - private String keystoneUrl; - @JsonProperty("heat_request") - private HeatRequest heatRequest; - - public ValetCreateRequest() { - super(); - } - - public String getRegionId() { - return this.regionId; - } - public void setRegionId(String regionId) { - this.regionId = regionId; - } + private static final long serialVersionUID = 768026109321305392L; + + @JsonProperty("region_id") + private String regionId; + @JsonProperty("owner_id") + private String ownerId; + @JsonProperty("tenant_id") + private String tenantId; + @JsonProperty("service_instance_id") + private String serviceInstanceId; + @JsonProperty("vnf_id") + private String vnfId; + @JsonProperty("vnf_name") + private String vnfName; + @JsonProperty("vf_module_id") + private String vfModuleId; + @JsonProperty("vf_module_name") + private String vfModuleName; + @JsonProperty("keystone_url") + private String keystoneUrl; + @JsonProperty("heat_request") + private HeatRequest heatRequest; + + public ValetCreateRequest() { + super(); + } + + public String getRegionId() { + return this.regionId; + } + + public void setRegionId(String regionId) { + this.regionId = regionId; + } + public String getOwnerId() { return this.ownerId; } + public void setOwnerId(String ownerId) { this.ownerId = ownerId; } - public String getTenantId() { - return this.tenantId; - } - public void setTenantId(String tenantId) { - this.tenantId = tenantId; - } - public String getServiceInstanceId() { - return this.serviceInstanceId; - } - public void setServiceInstanceId(String serviceInstanceId) { - this.serviceInstanceId = serviceInstanceId; - } - public String getVnfId() { - return this.vnfId; - } - public void setVnfId(String vnfId) { - this.vnfId = vnfId; - } - public String getVnfName() { - return this.vnfName; - } - public void setVnfName(String vnfName) { - this.vnfName = vnfName; - } - public String getVfModuleId() { - return this.vfModuleId; - } - public void setVfModuleId(String vfModuleId) { - this.vfModuleId = vfModuleId; - } - public String getVfModuleName() { - return this.vfModuleName; - } - public void setVfModuleName(String vfModuleName) { - this.vfModuleName = vfModuleName; - } - public String getKeystoneUrl() { - return this.keystoneUrl; - } - public void setKeystoneUrl(String keystoneUrl) { - this.keystoneUrl = keystoneUrl; - } - public HeatRequest getHeatRequest() { - return this.heatRequest; - } - public void setHeatRequest(HeatRequest heatRequest) { - this.heatRequest = heatRequest; - } - - @Override - public int hashCode() { - return Objects.hash(regionId, ownerId, tenantId, serviceInstanceId, vnfId, vnfName, vfModuleId, vfModuleName, keystoneUrl, heatRequest); - } - @Override - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof ValetCreateRequest)) { - return false; - } - ValetCreateRequest vcr = (ValetCreateRequest) o; - return Objects.equals(regionId, vcr.regionId) - && Objects.equals(ownerId, vcr.ownerId) - && Objects.equals(tenantId, vcr.tenantId) - && Objects.equals(serviceInstanceId, vcr.serviceInstanceId) - && Objects.equals(vnfId, vcr.vnfId) - && Objects.equals(vnfName, vcr.vnfName) - && Objects.equals(vfModuleId, vcr.vfModuleId) - && Objects.equals(vfModuleName, vcr.vfModuleName) - && Objects.equals(keystoneUrl, vcr.keystoneUrl) - && Objects.equals(heatRequest, vcr.heatRequest); - } + + public String getTenantId() { + return this.tenantId; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + public String getServiceInstanceId() { + return this.serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public String getVnfId() { + return this.vnfId; + } + + public void setVnfId(String vnfId) { + this.vnfId = vnfId; + } + + public String getVnfName() { + return this.vnfName; + } + + public void setVnfName(String vnfName) { + this.vnfName = vnfName; + } + + public String getVfModuleId() { + return this.vfModuleId; + } + + public void setVfModuleId(String vfModuleId) { + this.vfModuleId = vfModuleId; + } + + public String getVfModuleName() { + return this.vfModuleName; + } + + public void setVfModuleName(String vfModuleName) { + this.vfModuleName = vfModuleName; + } + + public String getKeystoneUrl() { + return this.keystoneUrl; + } + + public void setKeystoneUrl(String keystoneUrl) { + this.keystoneUrl = keystoneUrl; + } + + public HeatRequest getHeatRequest() { + return this.heatRequest; + } + + public void setHeatRequest(HeatRequest heatRequest) { + this.heatRequest = heatRequest; + } + + @Override + public int hashCode() { + return Objects.hash(regionId, ownerId, tenantId, serviceInstanceId, vnfId, vnfName, vfModuleId, vfModuleName, + keystoneUrl, heatRequest); + } + + @Override + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof ValetCreateRequest)) { + return false; + } + ValetCreateRequest vcr = (ValetCreateRequest) o; + return Objects.equals(regionId, vcr.regionId) && Objects.equals(ownerId, vcr.ownerId) + && Objects.equals(tenantId, vcr.tenantId) && Objects.equals(serviceInstanceId, vcr.serviceInstanceId) + && Objects.equals(vnfId, vcr.vnfId) && Objects.equals(vnfName, vcr.vnfName) + && Objects.equals(vfModuleId, vcr.vfModuleId) && Objects.equals(vfModuleName, vcr.vfModuleName) + && Objects.equals(keystoneUrl, vcr.keystoneUrl) && Objects.equals(heatRequest, vcr.heatRequest); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetCreateResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetCreateResponse.java index e0c750e79f..e09788714a 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetCreateResponse.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetCreateResponse.java @@ -24,47 +24,51 @@ import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; import java.util.Objects; import java.io.Serializable; + /* * This class represents the body of a Create response on a Valet Placement API call */ public class ValetCreateResponse implements Serializable { - private static final long serialVersionUID = 768026109321305392L; - - @JsonProperty("status") - private ValetStatus status; - @JsonProperty("parameters") - private Map<String, Object> parameters; - - public ValetCreateResponse() { - super(); - } - - public ValetStatus getStatus() { - return this.status; - } - public void setStatus(ValetStatus status) { - this.status = status; - } - public Map<String, Object> getParameters() { - return this.parameters; - } - public void setParameters(Map<String, Object> parameters) { - this.parameters = parameters; - } - - @Override - public int hashCode() { - return Objects.hash(status, parameters); - } - @Override - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof ValetCreateResponse)) { - return false; - } - ValetCreateResponse vcr = (ValetCreateResponse) o; - return Objects.equals(status, vcr.status) - && Objects.equals(parameters, vcr.parameters); - } + private static final long serialVersionUID = 768026109321305392L; + + @JsonProperty("status") + private ValetStatus status; + @JsonProperty("parameters") + private Map<String, Object> parameters; + + public ValetCreateResponse() { + super(); + } + + public ValetStatus getStatus() { + return this.status; + } + + public void setStatus(ValetStatus status) { + this.status = status; + } + + public Map<String, Object> getParameters() { + return this.parameters; + } + + public void setParameters(Map<String, Object> parameters) { + this.parameters = parameters; + } + + @Override + public int hashCode() { + return Objects.hash(status, parameters); + } + + @Override + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof ValetCreateResponse)) { + return false; + } + ValetCreateResponse vcr = (ValetCreateResponse) o; + return Objects.equals(status, vcr.status) && Objects.equals(parameters, vcr.parameters); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetDeleteRequest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetDeleteRequest.java index 75d7df1a83..fb6ceb45d8 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetDeleteRequest.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetDeleteRequest.java @@ -22,72 +22,80 @@ package org.onap.so.adapters.valet.beans; import java.io.Serializable; import java.util.Objects; - import com.fasterxml.jackson.annotation.JsonProperty; /* * This class represents the body of a Delete request on a Valet Placement API call */ public class ValetDeleteRequest implements Serializable { - private static final long serialVersionUID = 768026109321305392L; - - @JsonProperty("region_id") - private String regionId; - @JsonProperty("owner_id") - private String ownerId; - @JsonProperty("tenant_id") - private String tenantId; - @JsonProperty("vf_module_id") - private String vfModuleId; - @JsonProperty("vf_module_name") - private String vfModuleName; - - public String getRegionId() { - return this.regionId; - } - public void setRegionId(String regionId) { - this.regionId = regionId; - } + private static final long serialVersionUID = 768026109321305392L; + + @JsonProperty("region_id") + private String regionId; + @JsonProperty("owner_id") + private String ownerId; + @JsonProperty("tenant_id") + private String tenantId; + @JsonProperty("vf_module_id") + private String vfModuleId; + @JsonProperty("vf_module_name") + private String vfModuleName; + + public String getRegionId() { + return this.regionId; + } + + public void setRegionId(String regionId) { + this.regionId = regionId; + } + public String getOwnerId() { return this.ownerId; } + public void setOwnerId(String ownerId) { this.ownerId = ownerId; } - public String getTenantId() { - return this.tenantId; - } - public void setTenantId(String tenantId) { - this.tenantId = tenantId; - } - public String getVfModuleId() { - return this.vfModuleId; - } - public void setVfModuleId(String vfModuleId) { - this.vfModuleId = vfModuleId; - } - public String getVfModuleName() { - return this.vfModuleName; - } - public void setVfModuleName(String vfModuleName) { - this.vfModuleName = vfModuleName; - } - @Override - public int hashCode() { - return Objects.hash(regionId, ownerId, tenantId, vfModuleId, vfModuleName); - } - @Override - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof ValetDeleteRequest)) { - return false; - } - ValetDeleteRequest vdr = (ValetDeleteRequest) o; - return Objects.equals(regionId, vdr.regionId) - && Objects.equals(ownerId, vdr.ownerId) - && Objects.equals(tenantId, vdr.tenantId) - && Objects.equals(vfModuleId, vdr.vfModuleId) - && Objects.equals(vfModuleName, vdr.vfModuleName); - } + + public String getTenantId() { + return this.tenantId; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + public String getVfModuleId() { + return this.vfModuleId; + } + + public void setVfModuleId(String vfModuleId) { + this.vfModuleId = vfModuleId; + } + + public String getVfModuleName() { + return this.vfModuleName; + } + + public void setVfModuleName(String vfModuleName) { + this.vfModuleName = vfModuleName; + } + + @Override + public int hashCode() { + return Objects.hash(regionId, ownerId, tenantId, vfModuleId, vfModuleName); + } + + @Override + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof ValetDeleteRequest)) { + return false; + } + ValetDeleteRequest vdr = (ValetDeleteRequest) o; + return Objects.equals(regionId, vdr.regionId) && Objects.equals(ownerId, vdr.ownerId) + && Objects.equals(tenantId, vdr.tenantId) && Objects.equals(vfModuleId, vdr.vfModuleId) + && Objects.equals(vfModuleName, vdr.vfModuleName); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetDeleteResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetDeleteResponse.java index fa58752d61..81cfbc7acb 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetDeleteResponse.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetDeleteResponse.java @@ -22,45 +22,47 @@ package org.onap.so.adapters.valet.beans; import java.io.Serializable; import java.util.Objects; - import com.fasterxml.jackson.annotation.JsonProperty; /* * This class represents the body of a Delete response on a Valet Placement API call */ public class ValetDeleteResponse implements Serializable { - private static final long serialVersionUID = 768026109321305392L; - @JsonProperty("status") - private ValetStatus status; - - public ValetDeleteResponse() { - super(); - } - public ValetDeleteResponse(ValetStatus status) { - super(); - this.status = status; - } - - public ValetStatus getStatus() { - return this.status; - } - public void setStatus(ValetStatus status) { - this.status = status; - } - - @Override - public int hashCode() { - return Objects.hash(status); - } - @Override - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof ValetDeleteResponse)) { - return false; - } - ValetDeleteResponse vdr = (ValetDeleteResponse) o; - return Objects.equals(status, vdr.status); - } + private static final long serialVersionUID = 768026109321305392L; + @JsonProperty("status") + private ValetStatus status; + + public ValetDeleteResponse() { + super(); + } + + public ValetDeleteResponse(ValetStatus status) { + super(); + this.status = status; + } + + public ValetStatus getStatus() { + return this.status; + } + + public void setStatus(ValetStatus status) { + this.status = status; + } + + @Override + public int hashCode() { + return Objects.hash(status); + } + + @Override + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof ValetDeleteResponse)) { + return false; + } + ValetDeleteResponse vdr = (ValetDeleteResponse) o; + return Objects.equals(status, vdr.status); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetRollbackRequest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetRollbackRequest.java index ae0af67f80..7ca11af443 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetRollbackRequest.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetRollbackRequest.java @@ -22,60 +22,64 @@ package org.onap.so.adapters.valet.beans; import java.io.Serializable; import java.util.Objects; - import com.fasterxml.jackson.annotation.JsonProperty; /* * This class represents the body of a Rollback request on a Valet Placement API call */ public class ValetRollbackRequest implements Serializable { - private static final long serialVersionUID = 768026109321305392L; + private static final long serialVersionUID = 768026109321305392L; + + @JsonProperty("stack_id") + private String stackId; + @JsonProperty("suppress_rollback") + private Boolean suppressRollback = false; + @JsonProperty("error_message") + private String errorMessage; + + public ValetRollbackRequest() { + super(); + } + + public String getStackId() { + return this.stackId; + } + + public void setStackId(String stackId) { + this.stackId = stackId; + } + + public Boolean getSuppressRollback() { + return this.suppressRollback; + } + + public void setSuppressRollback(Boolean suppressRollback) { + this.suppressRollback = suppressRollback; + } + + public String getErrorMessage() { + return this.errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + @Override + public int hashCode() { + return Objects.hash(stackId, suppressRollback, errorMessage); + } - @JsonProperty("stack_id") - private String stackId; - @JsonProperty("suppress_rollback") - private Boolean suppressRollback = false; - @JsonProperty("error_message") - private String errorMessage; - - public ValetRollbackRequest() { - super(); - } - - public String getStackId() { - return this.stackId; - } - public void setStackId(String stackId) { - this.stackId = stackId; - } - public Boolean getSuppressRollback() { - return this.suppressRollback; - } - public void setSuppressRollback(Boolean suppressRollback) { - this.suppressRollback = suppressRollback; - } - public String getErrorMessage() { - return this.errorMessage; - } - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - - @Override - public int hashCode() { - return Objects.hash(stackId, suppressRollback, errorMessage); - } - @Override - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof ValetRollbackRequest)) { - return false; - } - ValetRollbackRequest vrr = (ValetRollbackRequest) o; - return Objects.equals(stackId, vrr.stackId) - && Objects.equals(suppressRollback, vrr.suppressRollback) - && Objects.equals(errorMessage, vrr.errorMessage); - } + @Override + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof ValetRollbackRequest)) { + return false; + } + ValetRollbackRequest vrr = (ValetRollbackRequest) o; + return Objects.equals(stackId, vrr.stackId) && Objects.equals(suppressRollback, vrr.suppressRollback) + && Objects.equals(errorMessage, vrr.errorMessage); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetRollbackResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetRollbackResponse.java index 429aa95af0..d9d29c0935 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetRollbackResponse.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetRollbackResponse.java @@ -21,9 +21,9 @@ package org.onap.so.adapters.valet.beans; import java.io.Serializable; -/* This class has no body - placeholder - body of a Rollback response on a Valet Placement Operation */ +/* This class has no body - placeholder - body of a Rollback response on a Valet Placement Operation */ public class ValetRollbackResponse implements Serializable { - private static final long serialVersionUID = 768026109321305392L; + private static final long serialVersionUID = 768026109321305392L; } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetStatus.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetStatus.java index cc48e95c81..3b8528cd72 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetStatus.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetStatus.java @@ -22,62 +22,65 @@ package org.onap.so.adapters.valet.beans; import java.io.Serializable; import java.util.Objects; - import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang3.builder.ToStringBuilder; -/* +/* * This class represents the status object as defined in the Valet Placement Operations API - part of Response objects */ public class ValetStatus implements Serializable { - private static final long serialVersionUID = 1L; - @JsonProperty("status") - private String status; - @JsonProperty("message") - private String message; + private static final long serialVersionUID = 1L; + @JsonProperty("status") + private String status; + @JsonProperty("message") + private String message; + + + public ValetStatus() { + super(); + } + + public ValetStatus(String statusCode, String statusMessage) { + super(); + this.status = statusCode; + this.message = statusMessage; + } + + + @Override + public String toString() { + return new ToStringBuilder(this).append("status", status).append("message", message).toString(); + } + + public String getStatus() { + return this.status; + } + + public void setStatus(String statusCode) { + this.status = statusCode; + } + + public String getMessage() { + return this.message; + } + public void setMessage(String statusMessage) { + this.message = statusMessage; + } - public ValetStatus() { - super(); - } - - public ValetStatus(String statusCode, String statusMessage) { - super(); - this.status = statusCode; - this.message = statusMessage; - } - - - @Override - public String toString() { - return new ToStringBuilder(this).append("status", status).append("message", message).toString(); - } - - public String getStatus() { - return this.status; - } - public void setStatus(String statusCode) { - this.status = statusCode; - } - public String getMessage() { - return this.message; - } - public void setMessage(String statusMessage) { - this.message = statusMessage; - } + @Override + public int hashCode() { + return Objects.hash(status, message); + } - @Override - public int hashCode() { - return Objects.hash(status, message); - } - @Override - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof ValetStatus)) { - return false; - } - ValetStatus vs = (ValetStatus) o; - return Objects.equals(status, vs.status) && Objects.equals(message, vs.message); - } + @Override + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof ValetStatus)) { + return false; + } + ValetStatus vs = (ValetStatus) o; + return Objects.equals(status, vs.status) && Objects.equals(message, vs.message); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetUpdateRequest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetUpdateRequest.java index 2d39dd1a71..ff27d88a1f 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetUpdateRequest.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetUpdateRequest.java @@ -22,122 +22,138 @@ package org.onap.so.adapters.valet.beans; import java.io.Serializable; import java.util.Objects; - import com.fasterxml.jackson.annotation.JsonProperty; /* * This class represents the body of an Update request on a Valet Placement API call */ public class ValetUpdateRequest implements Serializable { - private static final long serialVersionUID = 768026109321305392L; - - @JsonProperty("region_id") - private String regionId; - @JsonProperty("owner)_id") - private String ownerId; - @JsonProperty("tenant_id") - private String tenantId; - @JsonProperty("service_instance_id") - private String serviceInstanceId; - @JsonProperty("vnf_id") - private String vnfId; - @JsonProperty("vnf_name") - private String vnfName; - @JsonProperty("vf_module_id") - private String vfModuleId; - @JsonProperty("vf_module_name") - private String vfModuleName; - @JsonProperty("keystone_url") - private String keystoneUrl; - @JsonProperty("heat_request") - private HeatRequest heatRequest; - - public ValetUpdateRequest() { - super(); - } - - public String getRegionId() { - return this.regionId; - } - public void setRegionId(String regionId) { - this.regionId = regionId; - } + private static final long serialVersionUID = 768026109321305392L; + + @JsonProperty("region_id") + private String regionId; + @JsonProperty("owner)_id") + private String ownerId; + @JsonProperty("tenant_id") + private String tenantId; + @JsonProperty("service_instance_id") + private String serviceInstanceId; + @JsonProperty("vnf_id") + private String vnfId; + @JsonProperty("vnf_name") + private String vnfName; + @JsonProperty("vf_module_id") + private String vfModuleId; + @JsonProperty("vf_module_name") + private String vfModuleName; + @JsonProperty("keystone_url") + private String keystoneUrl; + @JsonProperty("heat_request") + private HeatRequest heatRequest; + + public ValetUpdateRequest() { + super(); + } + + public String getRegionId() { + return this.regionId; + } + + public void setRegionId(String regionId) { + this.regionId = regionId; + } + public String getOwnerId() { return this.ownerId; } + public void setOwnerId(String ownerId) { this.ownerId = ownerId; } - public String getTenantId() { - return this.tenantId; - } - public void setTenantId(String tenantId) { - this.tenantId = tenantId; - } - public String getServiceInstanceId() { - return this.serviceInstanceId; - } - public void setServiceInstanceId(String serviceInstanceId) { - this.serviceInstanceId = serviceInstanceId; - } - public String getVnfId() { - return this.vnfId; - } - public void setVnfId(String vnfId) { - this.vnfId = vnfId; - } - public String getVnfName() { - return this.vnfName; - } - public void setVnfName(String vnfName) { - this.vnfName = vnfName; - } - public String getVfModuleId() { - return this.vfModuleId; - } - public void setVfModuleId(String vfModuleId) { - this.vfModuleId = vfModuleId; - } - public String getVfModuleName() { - return this.vfModuleName; - } - public void setVfModuleName(String vfModuleName) { - this.vfModuleName = vfModuleName; - } - public String getKeystoneUrl() { - return this.keystoneUrl; - } - public void setKeystoneUrl(String keystoneUrl) { - this.keystoneUrl = keystoneUrl; - } - public HeatRequest getHeatRequest() { - return this.heatRequest; - } - public void setHeatRequest(HeatRequest heatRequest) { - this.heatRequest = heatRequest; - } - @Override - public int hashCode() { - return Objects.hash(regionId, ownerId, tenantId, serviceInstanceId, vnfId, vnfName, vfModuleId, vfModuleName, keystoneUrl, heatRequest); - - } - @Override - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof ValetUpdateRequest)) { - return false; - } - ValetUpdateRequest vur = (ValetUpdateRequest) o; - return Objects.equals(regionId, vur.regionId) - && Objects.equals(ownerId, vur.ownerId) - && Objects.equals(tenantId, vur.tenantId) - && Objects.equals(serviceInstanceId, vur.serviceInstanceId) - && Objects.equals(vnfId, vur.vnfId) - && Objects.equals(vnfName, vur.vnfName) - && Objects.equals(vfModuleId, vur.vfModuleId) - && Objects.equals(vfModuleName, vur.vfModuleName) - && Objects.equals(keystoneUrl, vur.keystoneUrl) - && Objects.equals(heatRequest, vur.heatRequest); - } + + public String getTenantId() { + return this.tenantId; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + public String getServiceInstanceId() { + return this.serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public String getVnfId() { + return this.vnfId; + } + + public void setVnfId(String vnfId) { + this.vnfId = vnfId; + } + + public String getVnfName() { + return this.vnfName; + } + + public void setVnfName(String vnfName) { + this.vnfName = vnfName; + } + + public String getVfModuleId() { + return this.vfModuleId; + } + + public void setVfModuleId(String vfModuleId) { + this.vfModuleId = vfModuleId; + } + + public String getVfModuleName() { + return this.vfModuleName; + } + + public void setVfModuleName(String vfModuleName) { + this.vfModuleName = vfModuleName; + } + + public String getKeystoneUrl() { + return this.keystoneUrl; + } + + public void setKeystoneUrl(String keystoneUrl) { + this.keystoneUrl = keystoneUrl; + } + + public HeatRequest getHeatRequest() { + return this.heatRequest; + } + + public void setHeatRequest(HeatRequest heatRequest) { + this.heatRequest = heatRequest; + } + + @Override + public int hashCode() { + return Objects.hash(regionId, ownerId, tenantId, serviceInstanceId, vnfId, vnfName, vfModuleId, vfModuleName, + keystoneUrl, heatRequest); + + } + + @Override + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof ValetUpdateRequest)) { + return false; + } + ValetUpdateRequest vur = (ValetUpdateRequest) o; + return Objects.equals(regionId, vur.regionId) && Objects.equals(ownerId, vur.ownerId) + && Objects.equals(tenantId, vur.tenantId) && Objects.equals(serviceInstanceId, vur.serviceInstanceId) + && Objects.equals(vnfId, vur.vnfId) && Objects.equals(vnfName, vur.vnfName) + && Objects.equals(vfModuleId, vur.vfModuleId) && Objects.equals(vfModuleName, vur.vfModuleName) + && Objects.equals(keystoneUrl, vur.keystoneUrl) && Objects.equals(heatRequest, vur.heatRequest); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetUpdateResponse.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetUpdateResponse.java index b6cb27caa3..10b6d2a09e 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetUpdateResponse.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/valet/beans/ValetUpdateResponse.java @@ -23,49 +23,51 @@ package org.onap.so.adapters.valet.beans; import java.io.Serializable; import java.util.HashMap; import java.util.Objects; - import com.fasterxml.jackson.annotation.JsonProperty; /* * This class represents the body of an Update response on a Valet Placement API call */ public class ValetUpdateResponse implements Serializable { - private static final long serialVersionUID = 768026109321305392L; - @JsonProperty("status") - private ValetStatus status; - @JsonProperty("parameters") - private HashMap<String, Object> parameters; - - public ValetUpdateResponse() { - super(); - } - - public ValetStatus getStatus() { - return this.status; - } - public void setStatus(ValetStatus status) { - this.status = status; - } - public HashMap<String, Object> getParameters() { - return this.parameters; - } - public void setParameters(HashMap<String, Object> parameters) { - this.parameters = parameters; - } + private static final long serialVersionUID = 768026109321305392L; + @JsonProperty("status") + private ValetStatus status; + @JsonProperty("parameters") + private HashMap<String, Object> parameters; + + public ValetUpdateResponse() { + super(); + } + + public ValetStatus getStatus() { + return this.status; + } + + public void setStatus(ValetStatus status) { + this.status = status; + } + + public HashMap<String, Object> getParameters() { + return this.parameters; + } + + public void setParameters(HashMap<String, Object> parameters) { + this.parameters = parameters; + } + + @Override + public int hashCode() { + return Objects.hash(status, parameters); + } - @Override - public int hashCode() { - return Objects.hash(status, parameters); - } - @Override - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof ValetUpdateResponse)) { - return false; - } - ValetUpdateResponse vur = (ValetUpdateResponse) o; - return Objects.equals(status, vur.status) - && Objects.equals(parameters, vur.parameters); - } + @Override + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof ValetUpdateResponse)) { + return false; + } + ValetUpdateResponse vur = (ValetUpdateResponse) o; + return Objects.equals(status, vur.status) && Objects.equals(parameters, vur.parameters); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapper.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapper.java index b418368170..f8a6e96bc6 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapper.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapper.java @@ -21,7 +21,6 @@ package org.onap.so.adapters.vdu.mapper; import java.util.List; - import org.onap.so.adapters.vdu.VduModelInfo; import org.onap.so.adapters.vdu.VduArtifact; import org.onap.so.adapters.vdu.VduArtifact.ArtifactType; @@ -34,98 +33,96 @@ import org.springframework.stereotype.Component; @Component public class VfModuleCustomizationToVduMapper { - public VduModelInfo mapVfModuleCustomizationToVdu(VfModuleCustomization vfModuleCustom) - { - VduModelInfo vduModel = new VduModelInfo(); - vduModel.setModelCustomizationUUID(vfModuleCustom.getModelCustomizationUUID()); - vduModel.setModelUUID(vfModuleCustom.getVfModule().getModelUUID()); - vduModel.setModelInvariantUUID(vfModuleCustom.getVfModule().getModelInvariantUUID()); - - // Map the cloud templates, attached files, and environment file - mapCloudTemplates(vfModuleCustom.getVfModule().getModuleHeatTemplate(), vduModel); - mapCloudFiles(vfModuleCustom,vduModel); - mapEnvironment(vfModuleCustom.getHeatEnvironment(), vduModel); - - return vduModel; - } - - public VduModelInfo mapVfModuleCustVolumeToVdu(VfModuleCustomization vfModuleCustom) - { - VduModelInfo vduModel = new VduModelInfo(); - vduModel.setModelCustomizationUUID(vfModuleCustom.getModelCustomizationUUID()); - vduModel.setModelUUID(vfModuleCustom.getVfModule().getModelUUID()); - vduModel.setModelInvariantUUID(vfModuleCustom.getVfModule().getModelInvariantUUID()); - - // Map the cloud templates, attached files, and environment file - mapCloudTemplates(vfModuleCustom.getVfModule().getVolumeHeatTemplate(), vduModel); - mapCloudFiles(vfModuleCustom,vduModel); - mapEnvironment(vfModuleCustom.getVolumeHeatEnv(), vduModel); - - return vduModel; - } - - private void mapCloudTemplates(HeatTemplate heatTemplate, VduModelInfo vduModel) { - // TODO: These catalog objects will be refactored to be non-Heat-specific - - List<VduArtifact> vduArtifacts = vduModel.getArtifacts(); - - // Main template. Also set the VDU timeout based on the main template. - vduArtifacts.add(mapHeatTemplateToVduArtifact(heatTemplate, ArtifactType.MAIN_TEMPLATE)); - vduModel.setTimeoutMinutes(heatTemplate.getTimeoutMinutes()); - - // Nested templates - List<HeatTemplate> childTemplates = heatTemplate.getChildTemplates(); - if (childTemplates != null) { - for(HeatTemplate childTemplate : childTemplates){ - vduArtifacts.add(mapHeatTemplateToVduArtifact(childTemplate, ArtifactType.NESTED_TEMPLATE)); - } - } - } - - private VduArtifact mapHeatTemplateToVduArtifact(HeatTemplate heatTemplate, ArtifactType artifactType) { - VduArtifact vduArtifact = new VduArtifact(); - vduArtifact.setName(heatTemplate.getTemplateName()); - vduArtifact.setContent(heatTemplate.getHeatTemplate().getBytes()); - vduArtifact.setType(artifactType); - return vduArtifact; - } - - private void mapCloudFiles(VfModuleCustomization vfModuleCustom, VduModelInfo vduModel) { - // TODO: These catalog objects will be refactored to be non-Heat-specific - - List<VduArtifact> vduArtifacts = vduModel.getArtifacts(); - - // Attached Files - List<HeatFiles> heatFiles = vfModuleCustom.getVfModule().getHeatFiles(); - if (heatFiles != null) { - for(HeatFiles file : heatFiles){ - vduArtifacts.add(mapCloudFileToVduArtifact(file, ArtifactType.TEXT_FILE)); - } - } - } - - private VduArtifact mapCloudFileToVduArtifact(HeatFiles heatFile, ArtifactType artifactType) { - VduArtifact vduArtifact = new VduArtifact(); - vduArtifact.setName(heatFile.getFileName()); - vduArtifact.setContent(heatFile.getFileBody().getBytes()); - vduArtifact.setType(artifactType); - return vduArtifact; - } - - private void mapEnvironment(HeatEnvironment heatEnvironment, VduModelInfo vduModel) { - // TODO: These catalog objects will be refactored to be non-Heat-specific - if (heatEnvironment != null) { - List<VduArtifact> vduArtifacts = vduModel.getArtifacts(); - vduArtifacts.add(mapEnvironmentFileToVduArtifact(heatEnvironment)); - } - } - - private VduArtifact mapEnvironmentFileToVduArtifact(HeatEnvironment heatEnv) { - VduArtifact vduArtifact = new VduArtifact(); - vduArtifact.setName(heatEnv.getName()); - vduArtifact.setContent(heatEnv.getEnvironment().getBytes()); - vduArtifact.setType(ArtifactType.ENVIRONMENT); - return vduArtifact; - } + public VduModelInfo mapVfModuleCustomizationToVdu(VfModuleCustomization vfModuleCustom) { + VduModelInfo vduModel = new VduModelInfo(); + vduModel.setModelCustomizationUUID(vfModuleCustom.getModelCustomizationUUID()); + vduModel.setModelUUID(vfModuleCustom.getVfModule().getModelUUID()); + vduModel.setModelInvariantUUID(vfModuleCustom.getVfModule().getModelInvariantUUID()); + + // Map the cloud templates, attached files, and environment file + mapCloudTemplates(vfModuleCustom.getVfModule().getModuleHeatTemplate(), vduModel); + mapCloudFiles(vfModuleCustom, vduModel); + mapEnvironment(vfModuleCustom.getHeatEnvironment(), vduModel); + + return vduModel; + } + + public VduModelInfo mapVfModuleCustVolumeToVdu(VfModuleCustomization vfModuleCustom) { + VduModelInfo vduModel = new VduModelInfo(); + vduModel.setModelCustomizationUUID(vfModuleCustom.getModelCustomizationUUID()); + vduModel.setModelUUID(vfModuleCustom.getVfModule().getModelUUID()); + vduModel.setModelInvariantUUID(vfModuleCustom.getVfModule().getModelInvariantUUID()); + + // Map the cloud templates, attached files, and environment file + mapCloudTemplates(vfModuleCustom.getVfModule().getVolumeHeatTemplate(), vduModel); + mapCloudFiles(vfModuleCustom, vduModel); + mapEnvironment(vfModuleCustom.getVolumeHeatEnv(), vduModel); + + return vduModel; + } + + private void mapCloudTemplates(HeatTemplate heatTemplate, VduModelInfo vduModel) { + // TODO: These catalog objects will be refactored to be non-Heat-specific + + List<VduArtifact> vduArtifacts = vduModel.getArtifacts(); + + // Main template. Also set the VDU timeout based on the main template. + vduArtifacts.add(mapHeatTemplateToVduArtifact(heatTemplate, ArtifactType.MAIN_TEMPLATE)); + vduModel.setTimeoutMinutes(heatTemplate.getTimeoutMinutes()); + + // Nested templates + List<HeatTemplate> childTemplates = heatTemplate.getChildTemplates(); + if (childTemplates != null) { + for (HeatTemplate childTemplate : childTemplates) { + vduArtifacts.add(mapHeatTemplateToVduArtifact(childTemplate, ArtifactType.NESTED_TEMPLATE)); + } + } + } + + private VduArtifact mapHeatTemplateToVduArtifact(HeatTemplate heatTemplate, ArtifactType artifactType) { + VduArtifact vduArtifact = new VduArtifact(); + vduArtifact.setName(heatTemplate.getTemplateName()); + vduArtifact.setContent(heatTemplate.getHeatTemplate().getBytes()); + vduArtifact.setType(artifactType); + return vduArtifact; + } + + private void mapCloudFiles(VfModuleCustomization vfModuleCustom, VduModelInfo vduModel) { + // TODO: These catalog objects will be refactored to be non-Heat-specific + + List<VduArtifact> vduArtifacts = vduModel.getArtifacts(); + + // Attached Files + List<HeatFiles> heatFiles = vfModuleCustom.getVfModule().getHeatFiles(); + if (heatFiles != null) { + for (HeatFiles file : heatFiles) { + vduArtifacts.add(mapCloudFileToVduArtifact(file, ArtifactType.TEXT_FILE)); + } + } + } + + private VduArtifact mapCloudFileToVduArtifact(HeatFiles heatFile, ArtifactType artifactType) { + VduArtifact vduArtifact = new VduArtifact(); + vduArtifact.setName(heatFile.getFileName()); + vduArtifact.setContent(heatFile.getFileBody().getBytes()); + vduArtifact.setType(artifactType); + return vduArtifact; + } + + private void mapEnvironment(HeatEnvironment heatEnvironment, VduModelInfo vduModel) { + // TODO: These catalog objects will be refactored to be non-Heat-specific + if (heatEnvironment != null) { + List<VduArtifact> vduArtifacts = vduModel.getArtifacts(); + vduArtifacts.add(mapEnvironmentFileToVduArtifact(heatEnvironment)); + } + } + + private VduArtifact mapEnvironmentFileToVduArtifact(HeatEnvironment heatEnv) { + VduArtifact vduArtifact = new VduArtifact(); + vduArtifact.setName(heatEnv.getName()); + vduArtifact.setContent(heatEnv.getEnvironment().getBytes()); + vduArtifact.setType(ArtifactType.ENVIRONMENT); + return vduArtifact; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/BpelRestClient.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/BpelRestClient.java index 1601de064d..906c285c28 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/BpelRestClient.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/BpelRestClient.java @@ -48,254 +48,250 @@ import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; /** - * This is the class that is used to POST replies from the MSO adapters to the BPEL engine. - * It can be configured via property file, or modified using the member methods. - * The properties to use are: - * org.onap.so.adapters.vnf.bpelauth encrypted authorization string to send to BEPL engine - * org.onap.so.adapters.vnf.sockettimeout socket timeout value - * org.onap.so.adapters.vnf.connecttimeout connect timeout value - * org.onap.so.adapters.vnf.retrycount number of times to retry failed connections - * org.onap.so.adapters.vnf.retryinterval interval (in seconds) between retries - * org.onap.so.adapters.vnf.retrylist list of response codes that will trigger a retry (the special code - * 900 means "connection was not established") + * This is the class that is used to POST replies from the MSO adapters to the BPEL engine. It can be configured via + * property file, or modified using the member methods. The properties to use are: org.onap.so.adapters.vnf.bpelauth + * encrypted authorization string to send to BEPL engine org.onap.so.adapters.vnf.sockettimeout socket timeout value + * org.onap.so.adapters.vnf.connecttimeout connect timeout value org.onap.so.adapters.vnf.retrycount number of times to + * retry failed connections org.onap.so.adapters.vnf.retryinterval interval (in seconds) between retries + * org.onap.so.adapters.vnf.retrylist list of response codes that will trigger a retry (the special code 900 means + * "connection was not established") */ @Component @Scope("prototype") public class BpelRestClient { - public static final String MSO_PROP_VNF_ADAPTER = "MSO_PROP_VNF_ADAPTER"; - private static final String PROPERTY_DOMAIN = "org.onap.so.adapters.vnf"; - private static final String BPEL_AUTH_PROPERTY = PROPERTY_DOMAIN+".bpelauth"; - private static final String SOCKET_TIMEOUT_PROPERTY = PROPERTY_DOMAIN+".sockettimeout"; - private static final String CONN_TIMEOUT_PROPERTY = PROPERTY_DOMAIN+".connecttimeout"; - private static final String RETRY_COUNT_PROPERTY = PROPERTY_DOMAIN+".retrycount"; - private static final String RETRY_INTERVAL_PROPERTY = PROPERTY_DOMAIN+".retryinterval"; - private static final String RETRY_LIST_PROPERTY = PROPERTY_DOMAIN+".retrylist"; - private static final String ENCRYPTION_KEY_PROP = "org.onap.so.adapters.network.encryptionKey"; + public static final String MSO_PROP_VNF_ADAPTER = "MSO_PROP_VNF_ADAPTER"; + private static final String PROPERTY_DOMAIN = "org.onap.so.adapters.vnf"; + private static final String BPEL_AUTH_PROPERTY = PROPERTY_DOMAIN + ".bpelauth"; + private static final String SOCKET_TIMEOUT_PROPERTY = PROPERTY_DOMAIN + ".sockettimeout"; + private static final String CONN_TIMEOUT_PROPERTY = PROPERTY_DOMAIN + ".connecttimeout"; + private static final String RETRY_COUNT_PROPERTY = PROPERTY_DOMAIN + ".retrycount"; + private static final String RETRY_INTERVAL_PROPERTY = PROPERTY_DOMAIN + ".retryinterval"; + private static final String RETRY_LIST_PROPERTY = PROPERTY_DOMAIN + ".retrylist"; + private static final String ENCRYPTION_KEY_PROP = "org.onap.so.adapters.network.encryptionKey"; private static final Logger logger = LoggerFactory.getLogger(BpelRestClient.class); - /** Default socket timeout (in seconds) */ - public static final int DEFAULT_SOCKET_TIMEOUT = 5; - /** Default connect timeout (in seconds) */ - public static final int DEFAULT_CONNECT_TIMEOUT = 5; - /** By default, retry up to five times */ - public static final int DEFAULT_RETRY_COUNT = 5; - /** Default interval to wait between retries (in seconds), negative means use backoff algorithm */ - public static final int DEFAULT_RETRY_INTERVAL = -15; - /** Default list of response codes to trigger a retry */ - public static final String DEFAULT_RETRY_LIST = "408,429,500,502,503,504,900"; // 900 is "connection failed" - /** Default credentials */ - public static final String DEFAULT_CREDENTIALS = ""; - - @Autowired - private Environment env; - // Properties of the BPEL client -- all are configurable - private int socketTimeout; - private int connectTimeout; - private int retryCount; - private int retryInterval; - private Set<Integer> retryList; - private String credentials; - - // last response from BPEL engine - private int lastResponseCode; - private String lastResponse; - - /** - * Create a client to send results to the BPEL engine, using configuration from the - * MSO_PROP_VNF_ADAPTER properties. - */ - public BpelRestClient() { - socketTimeout = DEFAULT_SOCKET_TIMEOUT; - connectTimeout = DEFAULT_CONNECT_TIMEOUT; - retryCount = DEFAULT_RETRY_COUNT; - retryInterval = DEFAULT_RETRY_INTERVAL; - setRetryList(DEFAULT_RETRY_LIST); - credentials = DEFAULT_CREDENTIALS; - lastResponseCode = 0; - lastResponse = ""; - - } - - @PostConstruct - protected void init() { - - socketTimeout = env.getProperty(SOCKET_TIMEOUT_PROPERTY, Integer.class, DEFAULT_SOCKET_TIMEOUT); - connectTimeout = env.getProperty(CONN_TIMEOUT_PROPERTY, Integer.class, DEFAULT_CONNECT_TIMEOUT); - retryCount = env.getProperty(RETRY_COUNT_PROPERTY, Integer.class, DEFAULT_RETRY_COUNT); - retryInterval = env.getProperty(RETRY_INTERVAL_PROPERTY, Integer.class, DEFAULT_RETRY_INTERVAL); - setRetryList(env.getProperty(RETRY_LIST_PROPERTY, DEFAULT_RETRY_LIST)); - credentials = getEncryptedProperty(BPEL_AUTH_PROPERTY, DEFAULT_CREDENTIALS, ENCRYPTION_KEY_PROP); - } - - public int getSocketTimeout() { - return socketTimeout; - } - - public void setSocketTimeout(int socketTimeout) { - this.socketTimeout = socketTimeout; - } - - public int getConnectTimeout() { - return connectTimeout; - } - - public void setConnectTimeout(int connectTimeout) { - this.connectTimeout = connectTimeout; - } - - public int getRetryCount() { - return retryCount; - } - - public void setRetryCount(int retryCount) { - int newRetryCount = retryCount; - if (newRetryCount < 0) - newRetryCount = DEFAULT_RETRY_COUNT; - this.retryCount = newRetryCount; - } - - public int getRetryInterval() { - return retryInterval; - } - - public void setRetryInterval(int retryInterval) { - this.retryInterval = retryInterval; - } - - public String getCredentials() { - return credentials; - } - - public void setCredentials(String credentials) { - this.credentials = credentials; - } - - public String getRetryList() { - if (retryList.isEmpty()) - return ""; - String t = retryList.toString(); - return t.substring(1, t.length()-1); - } - - public void setRetryList(String retryList) { - Set<Integer> s = new TreeSet<>(); - for (String t : retryList.split("[, ]")) { - try { - s.add(Integer.parseInt(t)); - } catch (NumberFormatException x) { - // ignore - } - } - this.retryList = s; - } - - public int getLastResponseCode() { - return lastResponseCode; - } - - public String getLastResponse() { - return lastResponse; - } - - /** - * Post a response to the URL of the BPEL engine. As long as the response code is one of those in - * the retryList, the post will be retried up to "retrycount" times with an interval (in seconds) - * of "retryInterval". If retryInterval is negative, then each successive retry interval will be - * double the previous one. - * @param toBpelStr the content (XML or JSON) to post - * @param bpelUrl the URL to post to - * @param isxml true if the content is XML, otherwise assumed to be JSON - * @return true if the post succeeded, false if all retries failed - */ - public boolean bpelPost(final String toBpelStr, final String bpelUrl, final boolean isxml) { - debug("Sending response to BPEL: " + toBpelStr); - int totalretries = 0; - int retryint = retryInterval; - while (true) { - sendOne(toBpelStr, bpelUrl, isxml); - // Note: really should handle response code 415 by switching between content types if needed - if (!retryList.contains(lastResponseCode)) { - debug("Got response code: " + lastResponseCode + ": returning."); - return true; - } - if (totalretries >= retryCount) { - debug("Retried " + totalretries + " times, giving up."); - logger.error("{} {} Could not deliver response to BPEL after {} tries: {}", MessageEnum.RA_SEND_VNF_NOTIF_ERR, - ErrorCode.BusinessProcesssError.getValue(), totalretries, toBpelStr); - return false; - } - totalretries++; - int sleepinterval = retryint; - if (retryint < 0) { - // if retry interval is negative double the retry on each pass - sleepinterval = -retryint; - retryint *= 2; - } - debug("Sleeping for " + sleepinterval + " seconds."); - try { - Thread.sleep(sleepinterval * 1000L); - } catch (InterruptedException e) { - logger.debug("Exception while Thread sleep", e); - Thread.currentThread().interrupt(); - } - } - } - private void debug(String m) { - logger.debug(m); - } - private void sendOne(final String toBpelStr, final String bpelUrl, final boolean isxml) { - logger.debug("Sending to BPEL server: {}", bpelUrl); - logger.debug("Content is: {}", toBpelStr); - - //POST - HttpPost post = new HttpPost(bpelUrl); - if (credentials != null && !credentials.isEmpty()) - post.addHeader("Authorization", "Basic " + DatatypeConverter.printBase64Binary(credentials.getBytes())); - - logger.debug("HTTPPost Headers: {}", post.getAllHeaders()); - - //ContentType + /** Default socket timeout (in seconds) */ + public static final int DEFAULT_SOCKET_TIMEOUT = 5; + /** Default connect timeout (in seconds) */ + public static final int DEFAULT_CONNECT_TIMEOUT = 5; + /** By default, retry up to five times */ + public static final int DEFAULT_RETRY_COUNT = 5; + /** Default interval to wait between retries (in seconds), negative means use backoff algorithm */ + public static final int DEFAULT_RETRY_INTERVAL = -15; + /** Default list of response codes to trigger a retry */ + public static final String DEFAULT_RETRY_LIST = "408,429,500,502,503,504,900"; // 900 is "connection failed" + /** Default credentials */ + public static final String DEFAULT_CREDENTIALS = ""; + + @Autowired + private Environment env; + // Properties of the BPEL client -- all are configurable + private int socketTimeout; + private int connectTimeout; + private int retryCount; + private int retryInterval; + private Set<Integer> retryList; + private String credentials; + + // last response from BPEL engine + private int lastResponseCode; + private String lastResponse; + + /** + * Create a client to send results to the BPEL engine, using configuration from the MSO_PROP_VNF_ADAPTER properties. + */ + public BpelRestClient() { + socketTimeout = DEFAULT_SOCKET_TIMEOUT; + connectTimeout = DEFAULT_CONNECT_TIMEOUT; + retryCount = DEFAULT_RETRY_COUNT; + retryInterval = DEFAULT_RETRY_INTERVAL; + setRetryList(DEFAULT_RETRY_LIST); + credentials = DEFAULT_CREDENTIALS; + lastResponseCode = 0; + lastResponse = ""; + + } + + @PostConstruct + protected void init() { + + socketTimeout = env.getProperty(SOCKET_TIMEOUT_PROPERTY, Integer.class, DEFAULT_SOCKET_TIMEOUT); + connectTimeout = env.getProperty(CONN_TIMEOUT_PROPERTY, Integer.class, DEFAULT_CONNECT_TIMEOUT); + retryCount = env.getProperty(RETRY_COUNT_PROPERTY, Integer.class, DEFAULT_RETRY_COUNT); + retryInterval = env.getProperty(RETRY_INTERVAL_PROPERTY, Integer.class, DEFAULT_RETRY_INTERVAL); + setRetryList(env.getProperty(RETRY_LIST_PROPERTY, DEFAULT_RETRY_LIST)); + credentials = getEncryptedProperty(BPEL_AUTH_PROPERTY, DEFAULT_CREDENTIALS, ENCRYPTION_KEY_PROP); + } + + public int getSocketTimeout() { + return socketTimeout; + } + + public void setSocketTimeout(int socketTimeout) { + this.socketTimeout = socketTimeout; + } + + public int getConnectTimeout() { + return connectTimeout; + } + + public void setConnectTimeout(int connectTimeout) { + this.connectTimeout = connectTimeout; + } + + public int getRetryCount() { + return retryCount; + } + + public void setRetryCount(int retryCount) { + int newRetryCount = retryCount; + if (newRetryCount < 0) + newRetryCount = DEFAULT_RETRY_COUNT; + this.retryCount = newRetryCount; + } + + public int getRetryInterval() { + return retryInterval; + } + + public void setRetryInterval(int retryInterval) { + this.retryInterval = retryInterval; + } + + public String getCredentials() { + return credentials; + } + + public void setCredentials(String credentials) { + this.credentials = credentials; + } + + public String getRetryList() { + if (retryList.isEmpty()) + return ""; + String t = retryList.toString(); + return t.substring(1, t.length() - 1); + } + + public void setRetryList(String retryList) { + Set<Integer> s = new TreeSet<>(); + for (String t : retryList.split("[, ]")) { + try { + s.add(Integer.parseInt(t)); + } catch (NumberFormatException x) { + // ignore + } + } + this.retryList = s; + } + + public int getLastResponseCode() { + return lastResponseCode; + } + + public String getLastResponse() { + return lastResponse; + } + + /** + * Post a response to the URL of the BPEL engine. As long as the response code is one of those in the retryList, the + * post will be retried up to "retrycount" times with an interval (in seconds) of "retryInterval". If retryInterval + * is negative, then each successive retry interval will be double the previous one. + * + * @param toBpelStr the content (XML or JSON) to post + * @param bpelUrl the URL to post to + * @param isxml true if the content is XML, otherwise assumed to be JSON + * @return true if the post succeeded, false if all retries failed + */ + public boolean bpelPost(final String toBpelStr, final String bpelUrl, final boolean isxml) { + debug("Sending response to BPEL: " + toBpelStr); + int totalretries = 0; + int retryint = retryInterval; + while (true) { + sendOne(toBpelStr, bpelUrl, isxml); + // Note: really should handle response code 415 by switching between content types if needed + if (!retryList.contains(lastResponseCode)) { + debug("Got response code: " + lastResponseCode + ": returning."); + return true; + } + if (totalretries >= retryCount) { + debug("Retried " + totalretries + " times, giving up."); + logger.error("{} {} Could not deliver response to BPEL after {} tries: {}", + MessageEnum.RA_SEND_VNF_NOTIF_ERR, ErrorCode.BusinessProcesssError.getValue(), totalretries, + toBpelStr); + return false; + } + totalretries++; + int sleepinterval = retryint; + if (retryint < 0) { + // if retry interval is negative double the retry on each pass + sleepinterval = -retryint; + retryint *= 2; + } + debug("Sleeping for " + sleepinterval + " seconds."); + try { + Thread.sleep(sleepinterval * 1000L); + } catch (InterruptedException e) { + logger.debug("Exception while Thread sleep", e); + Thread.currentThread().interrupt(); + } + } + } + + private void debug(String m) { + logger.debug(m); + } + + private void sendOne(final String toBpelStr, final String bpelUrl, final boolean isxml) { + logger.debug("Sending to BPEL server: {}", bpelUrl); + logger.debug("Content is: {}", toBpelStr); + + // POST + HttpPost post = new HttpPost(bpelUrl); + if (credentials != null && !credentials.isEmpty()) + post.addHeader("Authorization", "Basic " + DatatypeConverter.printBase64Binary(credentials.getBytes())); + + logger.debug("HTTPPost Headers: {}", post.getAllHeaders()); + + // ContentType ContentType ctype = isxml ? ContentType.APPLICATION_XML : ContentType.APPLICATION_JSON; post.setEntity(new StringEntity(toBpelStr, ctype)); - //Timeouts - RequestConfig requestConfig = RequestConfig - .custom() - .setSocketTimeout(socketTimeout * 1000) - .setConnectTimeout(connectTimeout * 1000) - .build(); - post.setConfig(requestConfig); - + // Timeouts + RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout * 1000) + .setConnectTimeout(connectTimeout * 1000).build(); + post.setConfig(requestConfig); + try (CloseableHttpClient client = HttpClients.createDefault()) { - CloseableHttpResponse response = client.execute(post); - if (response != null) { - lastResponseCode = response.getStatusLine().getStatusCode(); - HttpEntity entity = response.getEntity(); - lastResponse = (entity != null) ? EntityUtils.toString(entity) : ""; - } else { - lastResponseCode = 900; - lastResponse = ""; - } - } catch (Exception e) { + CloseableHttpResponse response = client.execute(post); + if (response != null) { + lastResponseCode = response.getStatusLine().getStatusCode(); + HttpEntity entity = response.getEntity(); + lastResponse = (entity != null) ? EntityUtils.toString(entity) : ""; + } else { + lastResponseCode = 900; + lastResponse = ""; + } + } catch (Exception e) { logger.error("{} {} Exception - Error sending Bpel notification: {} ", MessageEnum.RA_SEND_VNF_NOTIF_ERR, - ErrorCode.BusinessProcesssError.getValue(), toBpelStr, e); - lastResponseCode = 900; - lastResponse = ""; - } - - logger.debug("Response code from BPEL server: {}", lastResponseCode); - logger.debug("Response body is: {}", lastResponse); - } - - private String getEncryptedProperty(String key, String defaultValue, String encryptionKey) { - if (env.getProperty(key) != null) { - try { - return CryptoUtils.decrypt(env.getProperty(key), env.getProperty(encryptionKey)); - } catch (GeneralSecurityException e) { - logger.debug("Exception while decrypting property: {} ", env.getProperty(key), e); - } - } - return defaultValue; - } + ErrorCode.BusinessProcesssError.getValue(), toBpelStr, e); + lastResponseCode = 900; + lastResponse = ""; + } + + logger.debug("Response code from BPEL server: {}", lastResponseCode); + logger.debug("Response body is: {}", lastResponse); + } + + private String getEncryptedProperty(String key, String defaultValue, String encryptionKey) { + if (env.getProperty(key) != null) { + try { + return CryptoUtils.decrypt(env.getProperty(key), env.getProperty(encryptionKey)); + } catch (GeneralSecurityException e) { + logger.debug("Exception while decrypting property: {} ", env.getProperty(key), e); + } + } + return defaultValue; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java index bbfcef02e2..7786b872ef 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java @@ -31,162 +31,159 @@ import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; - import org.onap.so.adapters.vdu.VduArtifact; import org.onap.so.adapters.vdu.VduArtifact.ArtifactType; import org.onap.so.adapters.vdu.VduModelInfo; import org.onap.so.adapters.vnf.exceptions.VnfException; - import com.google.common.io.Files; /** - * The purpose of this class is to create a CSAR byte array from Vdu inputs for the purpose - * of forwarding to a TOSCA orchestrator. + * The purpose of this class is to create a CSAR byte array from Vdu inputs for the purpose of forwarding to a TOSCA + * orchestrator. * * @author DeWayne * */ public class CSAR { - private static final String MANIFEST_FILENAME = "MANIFEST.MF"; - private VduModelInfo vduModel; - - public CSAR(VduModelInfo model){ - this.vduModel = model; - } - - /** - * Creates a byte array representation of a CSAR corresponding to the VduBlueprint arg in the - * constructor. - * - * @return - * @throws VnfException - */ - public byte[] create() { - File dir = Files.createTempDir(); - - /** - * Create subdir - */ - File metadir = new File(dir.getAbsolutePath() + "/TOSCA-Metadata"); - if (!metadir.mkdir()) { - throw new RuntimeException("CSAR TOSCA-Metadata directory create failed"); - } - - /** - * Organize model info for consumption - */ - VduArtifact mainTemplate = null; - List<VduArtifact> extraFiles = new ArrayList<>(); - for(VduArtifact artifact: vduModel.getArtifacts()) { - if(artifact.getType() == ArtifactType.MAIN_TEMPLATE ) { - mainTemplate = artifact; - } else{ - extraFiles.add(artifact); - } - } - - if (mainTemplate == null) { // make a dummy to avoid null pointers - mainTemplate = new VduArtifact("", new byte[0], null); - } - - /** - * Write template files - */ - try (OutputStream ofs = new FileOutputStream(new File(dir, mainTemplate.getName())); - PrintStream mfstream = new PrintStream(new File(metadir.getAbsolutePath() + '/' + MANIFEST_FILENAME)); - ) { - ofs.write(mainTemplate.getContent()); - - /** - * Write other files - */ - if (!extraFiles.isEmpty()) { - for (VduArtifact artifact: extraFiles){ - try (OutputStream out = new FileOutputStream(new File(dir, artifact.getName()));) { - out.write(artifact.getContent()); - } - } - } - - - /** - * Create manifest - */ - mfstream.println("TOSCA-Meta-File-Version: 1.0"); - mfstream.println("CSAR-Version: 1.1"); - mfstream.println("Created-by: ONAP"); - mfstream.println("Entry-Definitions: " + mainTemplate.getName()); - - /** - * ZIP it up - */ - ByteArrayOutputStream zipbytes = new ByteArrayOutputStream(); - ZipOutputStream zos = new ZipOutputStream(zipbytes); - compressTree(zos, "", dir, dir); - zos.close(); - return zipbytes.toByteArray(); - - } catch (Exception e) { - throw new RuntimeException("Failed to create CSAR: " + e.getMessage()); - } finally { - /** - * Clean up tmpdir - */ - deleteDirectory(dir); - } - } - - /** - * Private methods - */ - - /** - * Compresses (ZIPs) a directory tree - * - * @param dir - * @throws IOException - */ - private void compressTree(ZipOutputStream zos, String path, File basedir, File dir) throws IOException { - if (!dir.isDirectory()) - return; - - for (File f : dir.listFiles()) { - if (f.isDirectory()) { - String newpath = path + f.getName() + '/'; - ZipEntry entry = new ZipEntry(newpath); - zos.putNextEntry(entry); - zos.closeEntry(); - compressTree(zos, newpath, basedir, f); - } else { - ZipEntry ze = new ZipEntry( - f.getAbsolutePath().substring(basedir.getAbsolutePath().length() + 1).replaceAll("\\\\", "/")); - zos.putNextEntry(ze); - // read the file and write to ZipOutputStream - try (FileInputStream fis = new FileInputStream(f);) { - byte[] buffer = new byte[1024]; - int len; - while ((len = fis.read(buffer)) > 0) { - zos.write(buffer, 0, len); - } - } - zos.closeEntry(); - } - } - } - - private boolean deleteDirectory(File directory) { - if (directory.exists()) { - File[] files = directory.listFiles(); - if (null != files) { - for (int i = 0; i < files.length; i++) { - if (files[i].isDirectory()) { - deleteDirectory(files[i]); - } else { - files[i].delete(); - } - } - } - } - return (directory.delete()); - } + private static final String MANIFEST_FILENAME = "MANIFEST.MF"; + private VduModelInfo vduModel; + + public CSAR(VduModelInfo model) { + this.vduModel = model; + } + + /** + * Creates a byte array representation of a CSAR corresponding to the VduBlueprint arg in the constructor. + * + * @return + * @throws VnfException + */ + public byte[] create() { + File dir = Files.createTempDir(); + + /** + * Create subdir + */ + File metadir = new File(dir.getAbsolutePath() + "/TOSCA-Metadata"); + if (!metadir.mkdir()) { + throw new RuntimeException("CSAR TOSCA-Metadata directory create failed"); + } + + /** + * Organize model info for consumption + */ + VduArtifact mainTemplate = null; + List<VduArtifact> extraFiles = new ArrayList<>(); + for (VduArtifact artifact : vduModel.getArtifacts()) { + if (artifact.getType() == ArtifactType.MAIN_TEMPLATE) { + mainTemplate = artifact; + } else { + extraFiles.add(artifact); + } + } + + if (mainTemplate == null) { // make a dummy to avoid null pointers + mainTemplate = new VduArtifact("", new byte[0], null); + } + + /** + * Write template files + */ + try (OutputStream ofs = new FileOutputStream(new File(dir, mainTemplate.getName())); + PrintStream mfstream = + new PrintStream(new File(metadir.getAbsolutePath() + '/' + MANIFEST_FILENAME));) { + ofs.write(mainTemplate.getContent()); + + /** + * Write other files + */ + if (!extraFiles.isEmpty()) { + for (VduArtifact artifact : extraFiles) { + try (OutputStream out = new FileOutputStream(new File(dir, artifact.getName()));) { + out.write(artifact.getContent()); + } + } + } + + + /** + * Create manifest + */ + mfstream.println("TOSCA-Meta-File-Version: 1.0"); + mfstream.println("CSAR-Version: 1.1"); + mfstream.println("Created-by: ONAP"); + mfstream.println("Entry-Definitions: " + mainTemplate.getName()); + + /** + * ZIP it up + */ + ByteArrayOutputStream zipbytes = new ByteArrayOutputStream(); + ZipOutputStream zos = new ZipOutputStream(zipbytes); + compressTree(zos, "", dir, dir); + zos.close(); + return zipbytes.toByteArray(); + + } catch (Exception e) { + throw new RuntimeException("Failed to create CSAR: " + e.getMessage()); + } finally { + /** + * Clean up tmpdir + */ + deleteDirectory(dir); + } + } + + /** + * Private methods + */ + + /** + * Compresses (ZIPs) a directory tree + * + * @param dir + * @throws IOException + */ + private void compressTree(ZipOutputStream zos, String path, File basedir, File dir) throws IOException { + if (!dir.isDirectory()) + return; + + for (File f : dir.listFiles()) { + if (f.isDirectory()) { + String newpath = path + f.getName() + '/'; + ZipEntry entry = new ZipEntry(newpath); + zos.putNextEntry(entry); + zos.closeEntry(); + compressTree(zos, newpath, basedir, f); + } else { + ZipEntry ze = new ZipEntry( + f.getAbsolutePath().substring(basedir.getAbsolutePath().length() + 1).replaceAll("\\\\", "/")); + zos.putNextEntry(ze); + // read the file and write to ZipOutputStream + try (FileInputStream fis = new FileInputStream(f);) { + byte[] buffer = new byte[1024]; + int len; + while ((len = fis.read(buffer)) > 0) { + zos.write(buffer, 0, len); + } + } + zos.closeEntry(); + } + } + } + + private boolean deleteDirectory(File directory) { + if (directory.exists()) { + File[] files = directory.listFiles(); + if (null != files) { + for (int i = 0; i < files.length; i++) { + if (files[i].isDirectory()) { + deleteDirectory(files[i]); + } else { + files[i].delete(); + } + } + } + } + return (directory.delete()); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapter.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapter.java index 349aa78d44..f6ea2261d7 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapter.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapter.java @@ -22,7 +22,6 @@ package org.onap.so.adapters.vnf; import java.util.Map; - import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebParam.Mode; @@ -30,7 +29,6 @@ import javax.jws.WebService; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.ws.Holder; - import org.onap.so.adapters.vnf.exceptions.VnfAlreadyExists; import org.onap.so.adapters.vnf.exceptions.VnfException; import org.onap.so.entity.MsoRequest; @@ -38,121 +36,112 @@ import org.onap.so.openstack.beans.VnfRollback; import org.onap.so.openstack.beans.VnfStatus; import org.onap.so.openstack.mappers.MapAdapter; -@WebService (name="VnfAdapter", targetNamespace="http://org.onap.so/vnf") -public interface MsoVnfAdapter -{ - /** - * This is the "Create VNF" Web Service Endpoint definition. - */ - @WebMethod - public void createVnf (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="vnfType") @XmlElement(required=true) String vnfType, - @WebParam(name="vnfVersion") @XmlElement(required=false) String vnfVersion, - @WebParam(name="vnfName") @XmlElement(required=true) String vnfName, - @WebParam(name="requestType") @XmlElement(required=false) String requestType, - @WebParam(name="volumeGroupHeatStackId") @XmlElement(required=false) String volumeGroupHeatStackId, - @WebParam(name="inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String,Object> inputs, - @WebParam(name="failIfExists") Boolean failIfExists, - @WebParam(name="backout") Boolean backout, - @WebParam(name="enableBridge") Boolean enableBridge, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="vnfId", mode=Mode.OUT) Holder<String> vnfId, - @WebParam(name="outputs", mode=Mode.OUT) Holder<Map<String,String>> outputs, - @WebParam(name="rollback", mode=Mode.OUT) Holder<VnfRollback> rollback ) - throws VnfException, VnfAlreadyExists; +@WebService(name = "VnfAdapter", targetNamespace = "http://org.onap.so/vnf") +public interface MsoVnfAdapter { + /** + * This is the "Create VNF" Web Service Endpoint definition. + */ + @WebMethod + public void createVnf(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "vnfType") @XmlElement(required = true) String vnfType, + @WebParam(name = "vnfVersion") @XmlElement(required = false) String vnfVersion, + @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName, + @WebParam(name = "requestType") @XmlElement(required = false) String requestType, + @WebParam(name = "volumeGroupHeatStackId") @XmlElement(required = false) String volumeGroupHeatStackId, + @WebParam(name = "inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String, Object> inputs, + @WebParam(name = "failIfExists") Boolean failIfExists, @WebParam(name = "backout") Boolean backout, + @WebParam(name = "enableBridge") Boolean enableBridge, @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "vnfId", mode = Mode.OUT) Holder<String> vnfId, + @WebParam(name = "outputs", mode = Mode.OUT) Holder<Map<String, String>> outputs, + @WebParam(name = "rollback", mode = Mode.OUT) Holder<VnfRollback> rollback) + throws VnfException, VnfAlreadyExists; - @WebMethod - public void updateVnf (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="vnfType") @XmlElement(required=true) String vnfType, - @WebParam(name="vnfVersion") @XmlElement(required=false) String vnfVersion, - @WebParam(name="vnfName") @XmlElement(required=true) String vnfName, - @WebParam(name="requestType") @XmlElement(required=false) String requestType, - @WebParam(name="volumeGroupHeatStackId") @XmlElement(required=false) String volumeGroupHeatStackId, - @WebParam(name="inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String,Object> inputs, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="outputs", mode=Mode.OUT) Holder<Map<String,String>> outputs, - @WebParam(name="rollback", mode=Mode.OUT) Holder<VnfRollback> rollback ) - throws VnfException; + @WebMethod + public void updateVnf(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "vnfType") @XmlElement(required = true) String vnfType, + @WebParam(name = "vnfVersion") @XmlElement(required = false) String vnfVersion, + @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName, + @WebParam(name = "requestType") @XmlElement(required = false) String requestType, + @WebParam(name = "volumeGroupHeatStackId") @XmlElement(required = false) String volumeGroupHeatStackId, + @WebParam(name = "inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String, Object> inputs, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "outputs", mode = Mode.OUT) Holder<Map<String, String>> outputs, + @WebParam(name = "rollback", mode = Mode.OUT) Holder<VnfRollback> rollback) throws VnfException; - @WebMethod - public void queryVnf (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="vnfName") @XmlElement(required=true) String vnfName, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="vnfExists", mode=Mode.OUT) Holder<Boolean> vnfExists, - @WebParam(name="vnfId", mode=Mode.OUT) Holder<String> vnfId, - @WebParam(name="status", mode=Mode.OUT) Holder<VnfStatus> status, - @WebParam(name="outputs", mode=Mode.OUT) Holder<Map<String,String>> outputs ) - throws VnfException; + @WebMethod + public void queryVnf(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "vnfExists", mode = Mode.OUT) Holder<Boolean> vnfExists, + @WebParam(name = "vnfId", mode = Mode.OUT) Holder<String> vnfId, + @WebParam(name = "status", mode = Mode.OUT) Holder<VnfStatus> status, + @WebParam(name = "outputs", mode = Mode.OUT) Holder<Map<String, String>> outputs) throws VnfException; - @WebMethod - public void deleteVnf (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="vnfName") @XmlElement(required=true) String vnfName, - @WebParam(name="request") MsoRequest msoRequest) - throws VnfException; + @WebMethod + public void deleteVnf(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName, + @WebParam(name = "request") MsoRequest msoRequest) throws VnfException; - @WebMethod - public void rollbackVnf (@WebParam(name="rollback") @XmlElement(required=true) VnfRollback rollback) - throws VnfException; + @WebMethod + public void rollbackVnf(@WebParam(name = "rollback") @XmlElement(required = true) VnfRollback rollback) + throws VnfException; - @WebMethod - public void createVfModule (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="vnfType") @XmlElement(required=true) String vnfType, - @WebParam(name="vnfVersion") @XmlElement(required=false) String vnfVersion, - @WebParam(name="genericVnfId") @XmlElement(required=true) String genericVnfId, - @WebParam(name="vnfName") @XmlElement(required=true) String vnfName, - @WebParam(name="vfModuleId") @XmlElement(required=true) String vfModuleId, - @WebParam(name="requestType") @XmlElement(required=false) String requestType, - @WebParam(name="volumeGroupHeatStackId") @XmlElement(required=false) String volumeGroupHeatStackId, - @WebParam(name="baseVfHeatStackId") @XmlElement(required=false) String baseVfHeatStackId, - @WebParam(name = "modelCustomizationUuid") @XmlElement(required = false) String modelCustomizationUuid, - @WebParam(name="inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String,Object> inputs, - @WebParam(name="failIfExists") Boolean failIfExists, - @WebParam(name="backout") Boolean backout, - @WebParam(name="enableBridge") Boolean enableBridge, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="vnfId", mode=Mode.OUT) Holder<String> vnfId, - @WebParam(name="outputs", mode=Mode.OUT) Holder<Map<String,String>> outputs, - @WebParam(name="rollback", mode=Mode.OUT) Holder<VnfRollback> rollback ) - throws VnfException, VnfAlreadyExists; + @WebMethod + public void createVfModule(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "vnfType") @XmlElement(required = true) String vnfType, + @WebParam(name = "vnfVersion") @XmlElement(required = false) String vnfVersion, + @WebParam(name = "genericVnfId") @XmlElement(required = true) String genericVnfId, + @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName, + @WebParam(name = "vfModuleId") @XmlElement(required = true) String vfModuleId, + @WebParam(name = "requestType") @XmlElement(required = false) String requestType, + @WebParam(name = "volumeGroupHeatStackId") @XmlElement(required = false) String volumeGroupHeatStackId, + @WebParam(name = "baseVfHeatStackId") @XmlElement(required = false) String baseVfHeatStackId, + @WebParam(name = "modelCustomizationUuid") @XmlElement(required = false) String modelCustomizationUuid, + @WebParam(name = "inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String, Object> inputs, + @WebParam(name = "failIfExists") Boolean failIfExists, @WebParam(name = "backout") Boolean backout, + @WebParam(name = "enableBridge") Boolean enableBridge, @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "vnfId", mode = Mode.OUT) Holder<String> vnfId, + @WebParam(name = "outputs", mode = Mode.OUT) Holder<Map<String, String>> outputs, + @WebParam(name = "rollback", mode = Mode.OUT) Holder<VnfRollback> rollback) + throws VnfException, VnfAlreadyExists; - @WebMethod - public void deleteVfModule (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="vfName") @XmlElement(required=true) String vfName, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name = "vfModuleOutputs", mode = Mode.OUT) Holder<Map<String, String>> vfModuleOutputs) - throws VnfException; + @WebMethod + public void deleteVfModule(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "vfName") @XmlElement(required = true) String vfName, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "vfModuleOutputs", mode = Mode.OUT) Holder<Map<String, String>> vfModuleOutputs) + throws VnfException; - @WebMethod - public void updateVfModule (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="vnfType") @XmlElement(required=true) String vnfType, - @WebParam(name="vnfVersion") @XmlElement(required=false) String vnfVersion, - @WebParam(name="vnfName") @XmlElement(required=true) String vnfName, - @WebParam(name="requestType") @XmlElement(required=false) String requestType, - @WebParam(name="volumeGroupHeatStackId") @XmlElement(required=false) String volumeGroupHeatStackId, - @WebParam(name="baseVfHeatStackId") @XmlElement(required=false) String baseVfHeatStackId, - @WebParam(name="vfModuleStackId") @XmlElement(required=false) String vfModuleStackId, - @WebParam(name = "modelCustomizationUuid") @XmlElement(required = false) String modelCustomizationUuid, - @WebParam(name="inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String,Object> inputs, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="outputs", mode=Mode.OUT) Holder<Map<String,String>> outputs, - @WebParam(name="rollback", mode=Mode.OUT) Holder<VnfRollback> rollback ) - throws VnfException; + @WebMethod + public void updateVfModule(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "vnfType") @XmlElement(required = true) String vnfType, + @WebParam(name = "vnfVersion") @XmlElement(required = false) String vnfVersion, + @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName, + @WebParam(name = "requestType") @XmlElement(required = false) String requestType, + @WebParam(name = "volumeGroupHeatStackId") @XmlElement(required = false) String volumeGroupHeatStackId, + @WebParam(name = "baseVfHeatStackId") @XmlElement(required = false) String baseVfHeatStackId, + @WebParam(name = "vfModuleStackId") @XmlElement(required = false) String vfModuleStackId, + @WebParam(name = "modelCustomizationUuid") @XmlElement(required = false) String modelCustomizationUuid, + @WebParam(name = "inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String, Object> inputs, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "outputs", mode = Mode.OUT) Holder<Map<String, String>> outputs, + @WebParam(name = "rollback", mode = Mode.OUT) Holder<VnfRollback> rollback) throws VnfException; - @WebMethod - public void healthCheck (); + @WebMethod + public void healthCheck(); } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsync.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsync.java index 5642e01a72..13ca78a1f5 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsync.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsync.java @@ -22,90 +22,85 @@ package org.onap.so.adapters.vnf; import java.util.Map; - import javax.jws.Oneway; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - import org.onap.so.entity.MsoRequest; import org.onap.so.openstack.beans.VnfRollback; import org.onap.so.openstack.mappers.MapAdapter; /** - * This webservice defines the Asynchronous versions of VNF adapter calls. - * The notification messages for final responses are documented elsewhere - * (by the client service WSDL). + * This webservice defines the Asynchronous versions of VNF adapter calls. The notification messages for final responses + * are documented elsewhere (by the client service WSDL). * */ -@WebService (name="VnfAdapterAsync", targetNamespace="http://org.onap.so/vnfA") -public interface MsoVnfAdapterAsync -{ - /** - * This is the "Create VNF" Web Service Endpoint definition. - */ - @WebMethod - @Oneway - public void createVnfA (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="vnfType") @XmlElement(required=true) String vnfType, - @WebParam(name="vnfVersion") @XmlElement(required=false) String vnfVersion, - @WebParam(name="vnfName") @XmlElement(required=true) String vnfName, - @WebParam(name="requestType") @XmlElement(required=false) String requestType, - @WebParam(name="volumeGroupHeatStackId") @XmlElement(required=false) String volumeGroupHeatStackId, - @WebParam(name="inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String,Object> inputs, - @WebParam(name="failIfExists") Boolean failIfExists, - @WebParam(name="backout") Boolean backout, - @WebParam(name="enableBridge") Boolean enableBridge, - @WebParam(name="messageId") @XmlElement(required=true) String messageId, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl ); +@WebService(name = "VnfAdapterAsync", targetNamespace = "http://org.onap.so/vnfA") +public interface MsoVnfAdapterAsync { + /** + * This is the "Create VNF" Web Service Endpoint definition. + */ + @WebMethod + @Oneway + public void createVnfA(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "vnfType") @XmlElement(required = true) String vnfType, + @WebParam(name = "vnfVersion") @XmlElement(required = false) String vnfVersion, + @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName, + @WebParam(name = "requestType") @XmlElement(required = false) String requestType, + @WebParam(name = "volumeGroupHeatStackId") @XmlElement(required = false) String volumeGroupHeatStackId, + @WebParam(name = "inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String, Object> inputs, + @WebParam(name = "failIfExists") Boolean failIfExists, @WebParam(name = "backout") Boolean backout, + @WebParam(name = "enableBridge") Boolean enableBridge, + @WebParam(name = "messageId") @XmlElement(required = true) String messageId, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl); - @WebMethod - @Oneway - public void updateVnfA (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="vnfType") @XmlElement(required=true) String vnfType, - @WebParam(name="vnfVersion") @XmlElement(required=false) String vnfVersion, - @WebParam(name="vnfName") @XmlElement(required=true) String vnfName, - @WebParam(name="requestType") @XmlElement(required=false) String requestType, - @WebParam(name="volumeGroupHeatStackId") @XmlElement(required=false) String volumeGroupHeatStackId, - @WebParam(name="inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String,Object> inputs, - @WebParam(name="messageId") @XmlElement(required=true) String messageId, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl ); + @WebMethod + @Oneway + public void updateVnfA(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "vnfType") @XmlElement(required = true) String vnfType, + @WebParam(name = "vnfVersion") @XmlElement(required = false) String vnfVersion, + @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName, + @WebParam(name = "requestType") @XmlElement(required = false) String requestType, + @WebParam(name = "volumeGroupHeatStackId") @XmlElement(required = false) String volumeGroupHeatStackId, + @WebParam(name = "inputs") @XmlJavaTypeAdapter(MapAdapter.class) Map<String, Object> inputs, + @WebParam(name = "messageId") @XmlElement(required = true) String messageId, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl); - @WebMethod - @Oneway - public void queryVnfA (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="vnfName") @XmlElement(required=true) String vnfName, - @WebParam(name="messageId") @XmlElement(required=true) String messageId, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl ); + @WebMethod + @Oneway + public void queryVnfA(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName, + @WebParam(name = "messageId") @XmlElement(required = true) String messageId, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl); - @WebMethod - @Oneway - public void deleteVnfA (@WebParam(name="cloudSiteId") @XmlElement(required=true) String cloudSiteId, - @WebParam(name="cloudOwner") @XmlElement(required=false) String cloudOwner, - @WebParam(name="tenantId") @XmlElement(required=true) String tenantId, - @WebParam(name="vnfName") @XmlElement(required=true) String vnfName, - @WebParam(name="messageId") @XmlElement(required=true) String messageId, - @WebParam(name="request") MsoRequest msoRequest, - @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl ); + @WebMethod + @Oneway + public void deleteVnfA(@WebParam(name = "cloudSiteId") @XmlElement(required = true) String cloudSiteId, + @WebParam(name = "cloudOwner") @XmlElement(required = false) String cloudOwner, + @WebParam(name = "tenantId") @XmlElement(required = true) String tenantId, + @WebParam(name = "vnfName") @XmlElement(required = true) String vnfName, + @WebParam(name = "messageId") @XmlElement(required = true) String messageId, + @WebParam(name = "request") MsoRequest msoRequest, + @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl); - @WebMethod - @Oneway - public void rollbackVnfA (@WebParam(name="rollback") @XmlElement(required=true) VnfRollback rollback, - @WebParam(name="messageId") @XmlElement(required=true) String messageId, - @WebParam(name="notificationUrl") @XmlElement(required=true) String notificationUrl ); + @WebMethod + @Oneway + public void rollbackVnfA(@WebParam(name = "rollback") @XmlElement(required = true) VnfRollback rollback, + @WebParam(name = "messageId") @XmlElement(required = true) String messageId, + @WebParam(name = "notificationUrl") @XmlElement(required = true) String notificationUrl); - @WebMethod - public void healthCheckA (); + @WebMethod + public void healthCheckA(); } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImpl.java index 5e42fa5603..fe11fa07b4 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImpl.java @@ -55,7 +55,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; -@WebService(serviceName = "VnfAdapterAsync", endpointInterface = "org.onap.so.adapters.vnf.MsoVnfAdapterAsync", targetNamespace = "http://org.onap.so/vnfA") +@WebService(serviceName = "VnfAdapterAsync", endpointInterface = "org.onap.so.adapters.vnf.MsoVnfAdapterAsync", + targetNamespace = "http://org.onap.so/vnfA") @Component public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { @@ -74,38 +75,32 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { * Health Check web method. Does nothing but return to show the adapter is deployed. */ @Override - public void healthCheckA () { - logger.debug ("Health check call in VNF Adapter"); + public void healthCheckA() { + logger.debug("Health check call in VNF Adapter"); } /** - * This is the asynchronous "Create VNF" web service implementation. - * It will create a new VNF of the requested type in the specified cloud - * and tenant. The tenant must exist before this service is called. + * This is the asynchronous "Create VNF" web service implementation. It will create a new VNF of the requested type + * in the specified cloud and tenant. The tenant must exist before this service is called. * - * If a VNF with the same name already exists, this can be considered a - * success or failure, depending on the value of the 'failIfExists' parameter. + * If a VNF with the same name already exists, this can be considered a success or failure, depending on the value + * of the 'failIfExists' parameter. * - * All VNF types will be defined in the MSO catalog. The caller must request - * one of these pre-defined types or an error will be returned. Within the - * catalog, each VNF type references (among other things) a Heat template - * which is used to deploy the required VNF artifacts (VMs, networks, etc.) - * to the cloud. + * All VNF types will be defined in the MSO catalog. The caller must request one of these pre-defined types or an + * error will be returned. Within the catalog, each VNF type references (among other things) a Heat template which + * is used to deploy the required VNF artifacts (VMs, networks, etc.) to the cloud. * - * Depending on the Heat template, a variable set of input parameters will - * be defined, some of which are required. The caller is responsible to - * pass the necessary input data for the VNF or an error will be thrown. + * Depending on the Heat template, a variable set of input parameters will be defined, some of which are required. + * The caller is responsible to pass the necessary input data for the VNF or an error will be thrown. * - * The method sends an asynchronous response to the notification URL when - * processing completes. The createAsyncResponse contains the vnfId (the - * canonical name of the stack), a Map of VNF output attributes, and a - * VnfRollback object. This last object can be passed as-is to the - * rollbackVnf operation to undo everything that was created for the VNF. - * This is useful if a VNF is successfully created but the orchestrator - * fails on a subsequent operation. + * The method sends an asynchronous response to the notification URL when processing completes. The + * createAsyncResponse contains the vnfId (the canonical name of the stack), a Map of VNF output attributes, and a + * VnfRollback object. This last object can be passed as-is to the rollbackVnf operation to undo everything that was + * created for the VNF. This is useful if a VNF is successfully created but the orchestrator fails on a subsequent + * operation. * - * Note: this method is implemented by calling the synchronous web method - * and translating the response to an asynchronous notification. + * Note: this method is implemented by calling the synchronous web method and translating the response to an + * asynchronous notification. * * @param cloudSiteId CLLI code of the cloud site in which to create the VNF * @param cloudOwner cloud owner of the cloud site in which to create the VNF @@ -113,74 +108,48 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { * @param vnfType VNF type key, should match a VNF definition in catalog DB * @param vnfName Name to be assigned to the new VNF * @param inputs Map of key=value inputs for VNF stack creation - * @param failIfExists Flag whether already existing VNF should be considered - * a success or failure + * @param failIfExists Flag whether already existing VNF should be considered a success or failure * @param msoRequest Request tracking information for logs * @param notificationURL the target URL for asynchronous response */ @Override - public void createVnfA (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfType, - String vnfVersion, - String vnfName, - String requestType, - String volumeGroupHeatStackId, - Map <String, Object> inputs, - Boolean failIfExists, - Boolean backout, - Boolean enableBridge, - String messageId, - MsoRequest msoRequest, - String notificationUrl) { + public void createVnfA(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, String vnfVersion, + String vnfName, String requestType, String volumeGroupHeatStackId, Map<String, Object> inputs, + Boolean failIfExists, Boolean backout, Boolean enableBridge, String messageId, MsoRequest msoRequest, + String notificationUrl) { logger.info("{} createVnfA", MessageEnum.RA_ASYNC_CREATE_VNF); // Use the synchronous method to perform the actual Create MsoVnfAdapter vnfAdapter = vnfImpl; // Synchronous Web Service Outputs - Holder <String> vnfId = new Holder <> (); - Holder <Map <String, String>> outputs = new Holder <> (); - Holder <VnfRollback> vnfRollback = new Holder <> (); + Holder<String> vnfId = new Holder<>(); + Holder<Map<String, String>> outputs = new Holder<>(); + Holder<VnfRollback> vnfRollback = new Holder<>(); try { - vnfAdapter.createVnf (cloudSiteId, - cloudOwner, - tenantId, - vnfType, - vnfVersion, - vnfName, - requestType, - volumeGroupHeatStackId, - inputs, - failIfExists, - backout, - enableBridge, - msoRequest, - vnfId, - outputs, - vnfRollback); + vnfAdapter.createVnf(cloudSiteId, cloudOwner, tenantId, vnfType, vnfVersion, vnfName, requestType, + volumeGroupHeatStackId, inputs, failIfExists, backout, enableBridge, msoRequest, vnfId, outputs, + vnfRollback); } catch (VnfException e) { logger.error("{} {} VnfException in createVnfA ", MessageEnum.RA_CREATE_VNF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); + ErrorCode.BusinessProcesssError.getValue(), e); org.onap.so.adapters.vnf.async.client.MsoExceptionCategory exCat = null; String eMsg = null; try { - eMsg = e.getFaultInfo ().getMessage (); - exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory.fromValue (e.getFaultInfo () - .getCategory () - .name ()); + eMsg = e.getFaultInfo().getMessage(); + exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory + .fromValue(e.getFaultInfo().getCategory().name()); } catch (Exception e1) { logger.error("{} {} Exception - Fault info ", MessageEnum.RA_FAULT_INFO_EXC, - ErrorCode.BusinessProcesssError.getValue(), e1); + ErrorCode.BusinessProcesssError.getValue(), e1); } // Build and send Asynchronous error response try { - VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl); - notifyPort.createVnfNotification (messageId, false, exCat, eMsg, null, null, null); + VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl); + notifyPort.createVnfNotification(messageId, false, exCat, eMsg, null, null, null); } catch (Exception e1) { logger.error("{} {} Exception sending createVnf notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e1); + ErrorCode.BusinessProcesssError.getValue(), e1); } logger.info("{}", MessageEnum.RA_ASYNC_CREATE_VNF_COMPLETE); return; @@ -188,35 +157,21 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { logger.debug("Async Create VNF: {} VnfId:{}", vnfName, vnfId.value); // Build and send Asynchronous response try { - VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl); - notifyPort.createVnfNotification (messageId, - true, - null, - null, - vnfId.value, - copyCreateOutputs (outputs), - copyVrb (vnfRollback)); + VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl); + notifyPort.createVnfNotification(messageId, true, null, null, vnfId.value, copyCreateOutputs(outputs), + copyVrb(vnfRollback)); } catch (Exception e) { logger.error("{} {} Exception sending createVnf notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); + ErrorCode.BusinessProcesssError.getValue(), e); } logger.info("{} createVnfA", MessageEnum.RA_ASYNC_CREATE_VNF_COMPLETE); return; } @Override - public void updateVnfA (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfType, - String vnfVersion, - String vnfName, - String requestType, - String volumeGroupHeatStackId, - Map <String, Object> inputs, - String messageId, - MsoRequest msoRequest, - String notificationUrl) { + public void updateVnfA(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, String vnfVersion, + String vnfName, String requestType, String volumeGroupHeatStackId, Map<String, Object> inputs, + String messageId, MsoRequest msoRequest, String notificationUrl) { logger.info("{} UpdateVnfA", MessageEnum.RA_ASYNC_UPDATE_VNF); @@ -224,33 +179,33 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { MsoVnfAdapter vnfAdapter = vnfImpl; // Synchronous Web Service Outputs - Holder <String> vnfId = new Holder <> (); - Holder <Map <String, String>> outputs = new Holder <> (); - Holder <VnfRollback> vnfRollback = new Holder <> (); + Holder<String> vnfId = new Holder<>(); + Holder<Map<String, String>> outputs = new Holder<>(); + Holder<VnfRollback> vnfRollback = new Holder<>(); try { - vnfAdapter.updateVnf (cloudSiteId, cloudOwner, tenantId, vnfType,vnfVersion, vnfName, requestType, volumeGroupHeatStackId, inputs, msoRequest, outputs, vnfRollback); + vnfAdapter.updateVnf(cloudSiteId, cloudOwner, tenantId, vnfType, vnfVersion, vnfName, requestType, + volumeGroupHeatStackId, inputs, msoRequest, outputs, vnfRollback); } catch (VnfException e) { logger.error("{} {} Exception sending updateVnf notification ", MessageEnum.RA_UPDATE_VNF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); + ErrorCode.BusinessProcesssError.getValue(), e); org.onap.so.adapters.vnf.async.client.MsoExceptionCategory exCat = null; String eMsg = null; try { - eMsg = e.getFaultInfo ().getMessage (); - exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory.fromValue (e.getFaultInfo () - .getCategory () - .name ()); + eMsg = e.getFaultInfo().getMessage(); + exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory + .fromValue(e.getFaultInfo().getCategory().name()); } catch (Exception e1) { logger.error("{} {} Exception - fault info ", MessageEnum.RA_FAULT_INFO_EXC, - ErrorCode.BusinessProcesssError.getValue(), e1); + ErrorCode.BusinessProcesssError.getValue(), e1); } // Build and send Asynchronous error response try { - VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl); - notifyPort.updateVnfNotification (messageId, false, exCat, eMsg, null, null); + VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl); + notifyPort.updateVnfNotification(messageId, false, exCat, eMsg, null, null); } catch (Exception e1) { logger.error("{} {} Exception sending updateVnf notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e1); + ErrorCode.BusinessProcesssError.getValue(), e1); } logger.info("{} UpdateVnfA", MessageEnum.RA_ASYNC_UPDATE_VNF_COMPLETE); return; @@ -258,27 +213,23 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { logger.debug("Async Update VNF: {} VnfId:{}", vnfName, vnfId.value); // Build and send Asynchronous response try { - VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl); - notifyPort.updateVnfNotification (messageId, - true, - null, - null, - copyUpdateOutputs (outputs), - copyVrb (vnfRollback)); + VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl); + notifyPort.updateVnfNotification(messageId, true, null, null, copyUpdateOutputs(outputs), + copyVrb(vnfRollback)); } catch (Exception e) { logger.error("{} {} Exception sending updateVnf notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); + ErrorCode.BusinessProcesssError.getValue(), e); } logger.info("{} UpdateVnfA", MessageEnum.RA_ASYNC_UPDATE_VNF_COMPLETE); return; } /** - * This is the "Query VNF" web service implementation. - * It will look up a VNF by name or ID in the specified cloud and tenant. + * This is the "Query VNF" web service implementation. It will look up a VNF by name or ID in the specified cloud + * and tenant. * - * The method returns an indicator that the VNF exists, its Openstack internal - * ID, its status, and the set of outputs (from when the stack was created). + * The method returns an indicator that the VNF exists, its Openstack internal ID, its status, and the set of + * outputs (from when the stack was created). * * @param cloudSiteId CLLI code of the cloud site in which to query * @param cloudOwner cloud owner of cloud site in which to query @@ -288,13 +239,8 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { * @param notificationURL the target URL for asynchronous response */ @Override - public void queryVnfA (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfName, - String messageId, - MsoRequest msoRequest, - String notificationUrl) { + public void queryVnfA(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, String messageId, + MsoRequest msoRequest, String notificationUrl) { String serviceName = "QueryVnfA"; logger.info("{}", MessageEnum.RA_ASYNC_QUERY_VNF); @@ -303,59 +249,54 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { MsoVnfAdapter vnfAdapter = vnfImpl; // Synchronous Web Service Outputs - Holder <Boolean> vnfExists = new Holder <> (); - Holder <String> vnfId = new Holder <> (); - Holder <VnfStatus> status = new Holder <> (); - Holder <Map <String, String>> outputs = new Holder <> (); + Holder<Boolean> vnfExists = new Holder<>(); + Holder<String> vnfId = new Holder<>(); + Holder<VnfStatus> status = new Holder<>(); + Holder<Map<String, String>> outputs = new Holder<>(); try { - vnfAdapter.queryVnf (cloudSiteId, cloudOwner, tenantId, vnfName, msoRequest, vnfExists, vnfId, status, outputs); + vnfAdapter.queryVnf(cloudSiteId, cloudOwner, tenantId, vnfName, msoRequest, vnfExists, vnfId, status, + outputs); } catch (VnfException e) { logger.error("{} {} Exception sending queryVnfA notification ", MessageEnum.RA_QUERY_VNF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); + ErrorCode.BusinessProcesssError.getValue(), e); org.onap.so.adapters.vnf.async.client.MsoExceptionCategory exCat = null; String eMsg = null; try { - eMsg = e.getFaultInfo ().getMessage (); - exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory.fromValue (e.getFaultInfo () - .getCategory () - .name ()); + eMsg = e.getFaultInfo().getMessage(); + exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory + .fromValue(e.getFaultInfo().getCategory().name()); } catch (Exception e1) { logger.error("{} {} Exception - fault info ", MessageEnum.RA_FAULT_INFO_EXC, - ErrorCode.BusinessProcesssError.getValue(), e1); + ErrorCode.BusinessProcesssError.getValue(), e1); } // Build and send Asynchronous error response try { - VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl); - notifyPort.queryVnfNotification (messageId, false, exCat, eMsg, null, null, null, null); + VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl); + notifyPort.queryVnfNotification(messageId, false, exCat, eMsg, null, null, null, null); } catch (Exception e1) { logger.error("{} {} Exception sending queryVnf notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e1); + ErrorCode.BusinessProcesssError.getValue(), e1); } logger.info("{} queryVnfA", MessageEnum.RA_ASYNC_QUERY_VNF_COMPLETE); return; } if (!vnfExists.value) { - logger.debug ("Async Query, VNF not found"); + logger.debug("Async Query, VNF not found"); } else { logger.debug("Async Query, VNF={}, status={}", vnfId.value, status.value); } // Build and send Asynchronous response try { - VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl); - org.onap.so.adapters.vnf.async.client.VnfStatus vnfS = org.onap.so.adapters.vnf.async.client.VnfStatus.fromValue (status.value.name ()); - notifyPort.queryVnfNotification (messageId, - true, - null, - null, - vnfExists.value, - vnfId.value, - vnfS, - copyQueryOutputs (outputs)); + VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl); + org.onap.so.adapters.vnf.async.client.VnfStatus vnfS = + org.onap.so.adapters.vnf.async.client.VnfStatus.fromValue(status.value.name()); + notifyPort.queryVnfNotification(messageId, true, null, null, vnfExists.value, vnfId.value, vnfS, + copyQueryOutputs(outputs)); } catch (Exception e) { logger.error("{} {} Exception sending queryVnf notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); + ErrorCode.BusinessProcesssError.getValue(), e); } logger.info("{} queryVnfA", MessageEnum.RA_ASYNC_QUERY_VNF_COMPLETE); @@ -363,8 +304,8 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { } /** - * This is the Asynchronous "Delete VNF" web service implementation. - * It will delete a VNF by name or ID in the specified cloud and tenant. + * This is the Asynchronous "Delete VNF" web service implementation. It will delete a VNF by name or ID in the + * specified cloud and tenant. * * The method has no outputs. * @@ -376,13 +317,8 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { * @param notificationURL the target URL for asynchronous response */ @Override - public void deleteVnfA (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfName, - String messageId, - MsoRequest msoRequest, - String notificationUrl) { + public void deleteVnfA(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, String messageId, + MsoRequest msoRequest, String notificationUrl) { String serviceName = "DeleteVnfA"; logger.info("{}", MessageEnum.RA_ASYNC_DELETE_VNF); @@ -391,28 +327,27 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { MsoVnfAdapter vnfAdapter = vnfImpl; try { - vnfAdapter.deleteVnf (cloudSiteId, cloudOwner, tenantId, vnfName, msoRequest); + vnfAdapter.deleteVnf(cloudSiteId, cloudOwner, tenantId, vnfName, msoRequest); } catch (VnfException e) { logger.error("{} {} Exception sending deleteVnfA notification ", MessageEnum.RA_DELETE_VNF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); + ErrorCode.BusinessProcesssError.getValue(), e); org.onap.so.adapters.vnf.async.client.MsoExceptionCategory exCat = null; String eMsg = null; try { - eMsg = e.getFaultInfo ().getMessage (); - exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory.fromValue (e.getFaultInfo () - .getCategory () - .name ()); + eMsg = e.getFaultInfo().getMessage(); + exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory + .fromValue(e.getFaultInfo().getCategory().name()); } catch (Exception e1) { logger.error("{} {} Exception - fault info ", MessageEnum.RA_FAULT_INFO_EXC, - ErrorCode.BusinessProcesssError.getValue(), e1); + ErrorCode.BusinessProcesssError.getValue(), e1); } // Build and send Asynchronous error response try { - VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl); - notifyPort.deleteVnfNotification (messageId, false, exCat, eMsg); + VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl); + notifyPort.deleteVnfNotification(messageId, false, exCat, eMsg); } catch (Exception e1) { logger.error("{} {} Exception sending deleteVnfA notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e1); + ErrorCode.BusinessProcesssError.getValue(), e1); } logger.info("{} deleteVnfA", MessageEnum.RA_ASYNC_DELETE_VNF_COMPLETE); return; @@ -421,12 +356,12 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { logger.debug("Async Delete VNF: {}", vnfName); // Build and send Asynchronous response try { - VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl); - notifyPort.deleteVnfNotification (messageId, true, null, null); + VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl); + notifyPort.deleteVnfNotification(messageId, true, null, null); } catch (Exception e) { logger.error("{} {} Exception sending deleteVnfA notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); + ErrorCode.BusinessProcesssError.getValue(), e); } logger.info("{} deleteVnfA", MessageEnum.RA_ASYNC_DELETE_VNF_COMPLETE); @@ -434,13 +369,12 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { } /** - * This web service endpoint will rollback a previous Create VNF operation. - * A rollback object is returned to the client in a successful creation - * response. The client can pass that object as-is back to the rollbackVnf - * operation to undo the creation. + * This web service endpoint will rollback a previous Create VNF operation. A rollback object is returned to the + * client in a successful creation response. The client can pass that object as-is back to the rollbackVnf operation + * to undo the creation. */ @Override - public void rollbackVnfA (VnfRollback rollback, String messageId, String notificationUrl) { + public void rollbackVnfA(VnfRollback rollback, String messageId, String notificationUrl) { // rollback may be null (e.g. if stack already existed when Create was called) if (rollback == null) { logger.info("{} rollbackVnfA: Empty Rollback: No action to perform", MessageEnum.RA_ROLLBACK_NULL); @@ -453,200 +387,199 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { MsoVnfAdapter vnfAdapter = vnfImpl; try { - vnfAdapter.rollbackVnf (rollback); + vnfAdapter.rollbackVnf(rollback); } catch (VnfException e) { logger.error("{} {} Exception sending rollbackVnfA notification ", MessageEnum.RA_ROLLBACK_VNF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); + ErrorCode.BusinessProcesssError.getValue(), e); org.onap.so.adapters.vnf.async.client.MsoExceptionCategory exCat = null; String eMsg = null; try { - eMsg = e.getFaultInfo ().getMessage (); - exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory.fromValue (e.getFaultInfo () - .getCategory () - .name ()); + eMsg = e.getFaultInfo().getMessage(); + exCat = org.onap.so.adapters.vnf.async.client.MsoExceptionCategory + .fromValue(e.getFaultInfo().getCategory().name()); } catch (Exception e1) { logger.error("{} {} Exception - fault info ", MessageEnum.RA_FAULT_INFO_EXC, - ErrorCode.BusinessProcesssError.getValue(), e1); + ErrorCode.BusinessProcesssError.getValue(), e1); } // Build and send Asynchronous error response try { - VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl); - notifyPort.rollbackVnfNotification (messageId, false, exCat, eMsg); + VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl); + notifyPort.rollbackVnfNotification(messageId, false, exCat, eMsg); } catch (Exception e1) { logger.error("{} {} Exception sending rollbackVnfA notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e1); + ErrorCode.BusinessProcesssError.getValue(), e1); } logger.info("{} rollbackVnfA", MessageEnum.RA_ASYNC_ROLLBACK_VNF_COMPLETE); return; } - logger.debug ("Async Rollback VNF:" + rollback.getVnfId ()); + logger.debug("Async Rollback VNF:" + rollback.getVnfId()); // Build and send Asynchronous response try { - VnfAdapterNotify notifyPort = getNotifyEP (notificationUrl); - notifyPort.rollbackVnfNotification (messageId, true, null, null); + VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl); + notifyPort.rollbackVnfNotification(messageId, true, null, null); } catch (Exception e) { logger.error("{} {} Exception sending rollbackVnfA notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); + ErrorCode.BusinessProcesssError.getValue(), e); } logger.info("{} rollbackVnfA", MessageEnum.RA_ASYNC_ROLLBACK_VNF_COMPLETE); return; } - private org.onap.so.adapters.vnf.async.client.VnfRollback copyVrb (Holder <VnfRollback> hVrb) { - org.onap.so.adapters.vnf.async.client.VnfRollback cvrb = new org.onap.so.adapters.vnf.async.client.VnfRollback (); + private org.onap.so.adapters.vnf.async.client.VnfRollback copyVrb(Holder<VnfRollback> hVrb) { + org.onap.so.adapters.vnf.async.client.VnfRollback cvrb = + new org.onap.so.adapters.vnf.async.client.VnfRollback(); if (hVrb != null && hVrb.value != null) { - org.onap.so.adapters.vnf.async.client.MsoRequest cmr = new org.onap.so.adapters.vnf.async.client.MsoRequest (); + org.onap.so.adapters.vnf.async.client.MsoRequest cmr = + new org.onap.so.adapters.vnf.async.client.MsoRequest(); - cvrb.setCloudSiteId (hVrb.value.getCloudSiteId ()); + cvrb.setCloudSiteId(hVrb.value.getCloudSiteId()); if (hVrb.value.getMsoRequest() != null) { - cmr.setRequestId (hVrb.value.getMsoRequest ().getRequestId ()); - cmr.setServiceInstanceId (hVrb.value.getMsoRequest ().getServiceInstanceId ()); + cmr.setRequestId(hVrb.value.getMsoRequest().getRequestId()); + cmr.setServiceInstanceId(hVrb.value.getMsoRequest().getServiceInstanceId()); } else { - cmr.setRequestId (null); - cmr.setServiceInstanceId (null); + cmr.setRequestId(null); + cmr.setServiceInstanceId(null); } - cvrb.setMsoRequest (cmr); - cvrb.setVnfId (hVrb.value.getVnfId ()); - cvrb.setTenantId (hVrb.value.getTenantId ()); - cvrb.setTenantCreated (hVrb.value.getTenantCreated ()); - cvrb.setVnfCreated (hVrb.value.getVnfCreated ()); + cvrb.setMsoRequest(cmr); + cvrb.setVnfId(hVrb.value.getVnfId()); + cvrb.setTenantId(hVrb.value.getTenantId()); + cvrb.setTenantCreated(hVrb.value.getTenantCreated()); + cvrb.setVnfCreated(hVrb.value.getVnfCreated()); } return cvrb; } - private CreateVnfNotification.Outputs copyCreateOutputs (Holder <Map <String, String>> hMap) { + private CreateVnfNotification.Outputs copyCreateOutputs(Holder<Map<String, String>> hMap) { - CreateVnfNotification.Outputs outputs = new CreateVnfNotification.Outputs (); + CreateVnfNotification.Outputs outputs = new CreateVnfNotification.Outputs(); if (hMap != null && hMap.value != null) { - Map <String, String> sMap = new HashMap <> (); + Map<String, String> sMap = new HashMap<>(); sMap = hMap.value; - CreateVnfNotification.Outputs.Entry entry = new CreateVnfNotification.Outputs.Entry (); + CreateVnfNotification.Outputs.Entry entry = new CreateVnfNotification.Outputs.Entry(); - for (String key : sMap.keySet ()) { - entry.setKey (key); - entry.setValue (sMap.get (key)); - outputs.getEntry ().add (entry); + for (String key : sMap.keySet()) { + entry.setKey(key); + entry.setValue(sMap.get(key)); + outputs.getEntry().add(entry); } } return outputs; } - private UpdateVnfNotification.Outputs copyUpdateOutputs (Holder <Map <String, String>> hMap) { + private UpdateVnfNotification.Outputs copyUpdateOutputs(Holder<Map<String, String>> hMap) { - UpdateVnfNotification.Outputs outputs = new UpdateVnfNotification.Outputs (); + UpdateVnfNotification.Outputs outputs = new UpdateVnfNotification.Outputs(); if (hMap != null && hMap.value != null) { - Map <String, String> sMap = new HashMap <> (); + Map<String, String> sMap = new HashMap<>(); sMap = hMap.value; - UpdateVnfNotification.Outputs.Entry entry = new UpdateVnfNotification.Outputs.Entry (); - - for (Map.Entry<String,String> mapEntry : sMap.entrySet ()) { - String key = mapEntry.getKey(); - String value = mapEntry.getValue(); - entry.setKey (key); - entry.setValue (value); - outputs.getEntry ().add (entry); + UpdateVnfNotification.Outputs.Entry entry = new UpdateVnfNotification.Outputs.Entry(); + + for (Map.Entry<String, String> mapEntry : sMap.entrySet()) { + String key = mapEntry.getKey(); + String value = mapEntry.getValue(); + entry.setKey(key); + entry.setValue(value); + outputs.getEntry().add(entry); } } return outputs; } - private QueryVnfNotification.Outputs copyQueryOutputs (Holder <Map <String, String>> hMap) { + private QueryVnfNotification.Outputs copyQueryOutputs(Holder<Map<String, String>> hMap) { - QueryVnfNotification.Outputs outputs = new QueryVnfNotification.Outputs (); + QueryVnfNotification.Outputs outputs = new QueryVnfNotification.Outputs(); if (hMap != null && hMap.value != null) { - Map <String, String> sMap = new HashMap <> (); + Map<String, String> sMap = new HashMap<>(); sMap = hMap.value; - QueryVnfNotification.Outputs.Entry entry = new QueryVnfNotification.Outputs.Entry (); + QueryVnfNotification.Outputs.Entry entry = new QueryVnfNotification.Outputs.Entry(); - for (Map.Entry<String,String> mapEntry : sMap.entrySet ()) { - String key = mapEntry.getKey(); - String value = mapEntry.getValue(); - entry.setKey (key); - entry.setValue (value); - outputs.getEntry ().add (entry); + for (Map.Entry<String, String> mapEntry : sMap.entrySet()) { + String key = mapEntry.getKey(); + String value = mapEntry.getValue(); + entry.setKey(key); + entry.setValue(value); + outputs.getEntry().add(entry); } } return outputs; } - private VnfAdapterNotify getNotifyEP (String notificationUrl) { + private VnfAdapterNotify getNotifyEP(String notificationUrl) { URL warWsdlLoc = null; try { - warWsdlLoc = Thread.currentThread ().getContextClassLoader ().getResource ("VnfAdapterNotify.wsdl"); + warWsdlLoc = Thread.currentThread().getContextClassLoader().getResource("VnfAdapterNotify.wsdl"); } catch (Exception e) { logger.error("{} {} Exception - WSDL not found ", MessageEnum.RA_WSDL_NOT_FOUND, - ErrorCode.BusinessProcesssError.getValue(), e); + ErrorCode.BusinessProcesssError.getValue(), e); } if (warWsdlLoc == null) { logger.error("{} {} WSDL not found", MessageEnum.RA_WSDL_NOT_FOUND, - ErrorCode.BusinessProcesssError.getValue()); + ErrorCode.BusinessProcesssError.getValue()); } else { try { logger.debug("VnfAdpaterNotify.wsdl location:{}", warWsdlLoc.toURI().toString()); } catch (Exception e) { logger.error("{} {} Exception - WSDL URL convention ", MessageEnum.RA_WSDL_URL_CONVENTION_EXC, - ErrorCode.BusinessProcesssError.getValue(), e); + ErrorCode.BusinessProcesssError.getValue(), e); } } - VnfAdapterNotify_Service notifySvc = new VnfAdapterNotify_Service (warWsdlLoc, - new QName ("http://org.onap.so/vnfNotify", - "vnfAdapterNotify")); + VnfAdapterNotify_Service notifySvc = + new VnfAdapterNotify_Service(warWsdlLoc, new QName("http://org.onap.so/vnfNotify", "vnfAdapterNotify")); - VnfAdapterNotify notifyPort = notifySvc.getMsoVnfAdapterAsyncImplPort (); + VnfAdapterNotify notifyPort = notifySvc.getMsoVnfAdapterAsyncImplPort(); BindingProvider bp = (BindingProvider) notifyPort; URL epUrl = null; try { - epUrl = new URL (notificationUrl); + epUrl = new URL(notificationUrl); } catch (MalformedURLException e1) { logger.error("{} {} MalformedURLException ", MessageEnum.RA_INIT_NOTIF_EXC, - ErrorCode.BusinessProcesssError.getValue(), e1); + ErrorCode.BusinessProcesssError.getValue(), e1); } - if(null != epUrl) { + if (null != epUrl) { logger.debug("Notification Endpoint URL: {}", epUrl.toExternalForm()); - bp.getRequestContext ().put (BindingProvider.ENDPOINT_ADDRESS_PROPERTY, epUrl.toExternalForm ()); - } - else { - logger.debug ("epUrl is NULL:"); + bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, epUrl.toExternalForm()); + } else { + logger.debug("epUrl is NULL:"); } // authentication try { - Map <String, Object> reqCtx = bp.getRequestContext (); - Map <String, List <String>> headers = new HashMap <> (); + Map<String, Object> reqCtx = bp.getRequestContext(); + Map<String, List<String>> headers = new HashMap<>(); String userCredentials = this.getEncryptedProperty(BPEL_AUTH_PROP, "", ENCRYPTION_KEY_PROP); - String basicAuth = "Basic " + DatatypeConverter.printBase64Binary (userCredentials.getBytes ()); - reqCtx.put (MessageContext.HTTP_REQUEST_HEADERS, headers); - headers.put ("Authorization", Collections.singletonList (basicAuth)); + String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()); + reqCtx.put(MessageContext.HTTP_REQUEST_HEADERS, headers); + headers.put("Authorization", Collections.singletonList(basicAuth)); } catch (Exception e) { logger.error("{} {} Exception - Unable to set authorization in callback request ", - MessageEnum.RA_SET_CALLBACK_AUTH_EXC, ErrorCode.BusinessProcesssError.getValue(), e); + MessageEnum.RA_SET_CALLBACK_AUTH_EXC, ErrorCode.BusinessProcesssError.getValue(), e); } return notifyPort; } public String getEncryptedProperty(String key, String defaultValue, String encryptionKey) { - try { - return CryptoUtils.decrypt(this.environment.getProperty(key), this.environment.getProperty(encryptionKey)); - } catch (GeneralSecurityException e) { - logger.debug("Exception while decrypting property: {} ", this.environment.getProperty(key), e); - } - return defaultValue; - - } + try { + return CryptoUtils.decrypt(this.environment.getProperty(key), this.environment.getProperty(encryptionKey)); + } catch (GeneralSecurityException e) { + logger.debug("Exception while decrypting property: {} ", this.environment.getProperty(key), e); + } + return defaultValue; + + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java index 6e9656a213..5c7e70673b 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java @@ -33,10 +33,8 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; - import javax.jws.WebService; import javax.xml.ws.Holder; - import org.apache.commons.collections.CollectionUtils; import org.onap.so.adapters.valet.GenericValetResponse; import org.onap.so.adapters.valet.ValetClient; @@ -70,7 +68,6 @@ import org.onap.so.heatbridge.HeatBridgeApi; import org.onap.so.heatbridge.HeatBridgeImpl; import org.onap.so.heatbridge.openstack.api.OpenstackClient; import org.onap.so.logger.MessageEnum; - import org.onap.so.openstack.beans.HeatStatus; import org.onap.so.openstack.beans.StackInfo; import org.onap.so.openstack.beans.VnfRollback; @@ -92,21 +89,21 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; - import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -@WebService(serviceName = "VnfAdapter", endpointInterface = "org.onap.so.adapters.vnf.MsoVnfAdapter", targetNamespace = "http://org.onap.so/vnf") +@WebService(serviceName = "VnfAdapter", endpointInterface = "org.onap.so.adapters.vnf.MsoVnfAdapter", + targetNamespace = "http://org.onap.so/vnf") @Component @Transactional public class MsoVnfAdapterImpl implements MsoVnfAdapter { - @Autowired - private CloudConfig cloudConfig; + @Autowired + private CloudConfig cloudConfig; - @Autowired - private Environment environment; + @Autowired + private Environment environment; private static final Logger logger = LoggerFactory.getLogger(MsoVnfAdapterImpl.class); @@ -116,8 +113,9 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { private static final String ADD_GET_FILES_ON_VOLUME_REQ = "org.onap.so.adapters.vnf.addGetFilesOnVolumeReq"; private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); private static final String VALET_ENABLED = "org.onap.so.adapters.vnf.valet_enabled"; - private static final String FAIL_REQUESTS_ON_VALET_FAILURE = "org.onap.so.adapters.vnf.fail_requests_on_valet_failure"; - private static final String SUCCESS_MSG = "Successfully received response from Open Stack"; + private static final String FAIL_REQUESTS_ON_VALET_FAILURE = + "org.onap.so.adapters.vnf.fail_requests_on_valet_failure"; + private static final String SUCCESS_MSG = "Successfully received response from Open Stack"; @Autowired private VFModuleCustomizationRepository vfModuleCustomRepo; @@ -135,44 +133,39 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { /** * DO NOT use that constructor to instantiate this class, the msoPropertiesfactory will be NULL. + * * @see MsoVnfAdapterImpl#MsoVnfAdapterImpl(MsoPropertiesFactory, CloudConfigFactory) */ public MsoVnfAdapterImpl() { - // Do nothing - //DO NOT use that constructor to instantiate this class, the msoPropertiesfactory will be NULL. - } + // Do nothing + // DO NOT use that constructor to instantiate this class, the msoPropertiesfactory will be NULL. + } - /** + /** * Health Check web method. Does nothing but return to show the adapter is deployed. */ @Override - public void healthCheck () { - logger.debug ("Health check call in VNF Adapter"); + public void healthCheck() { + logger.debug("Health check call in VNF Adapter"); } /** - * This is the "Create VNF" web service implementation. - * It will create a new VNF of the requested type in the specified cloud - * and tenant. The tenant must exist before this service is called. + * This is the "Create VNF" web service implementation. It will create a new VNF of the requested type in the + * specified cloud and tenant. The tenant must exist before this service is called. * - * If a VNF with the same name already exists, this can be considered a - * success or failure, depending on the value of the 'failIfExists' parameter. + * If a VNF with the same name already exists, this can be considered a success or failure, depending on the value + * of the 'failIfExists' parameter. * - * All VNF types will be defined in the MSO catalog. The caller must request - * one of these pre-defined types or an error will be returned. Within the - * catalog, each VNF type references (among other things) a Heat template - * which is used to deploy the required VNF artifacts (VMs, networks, etc.) - * to the cloud. + * All VNF types will be defined in the MSO catalog. The caller must request one of these pre-defined types or an + * error will be returned. Within the catalog, each VNF type references (among other things) a Heat template which + * is used to deploy the required VNF artifacts (VMs, networks, etc.) to the cloud. * - * Depending on the Heat template, a variable set of input parameters will - * be defined, some of which are required. The caller is responsible to - * pass the necessary input data for the VNF or an error will be thrown. + * Depending on the Heat template, a variable set of input parameters will be defined, some of which are required. + * The caller is responsible to pass the necessary input data for the VNF or an error will be thrown. * - * The method returns the vnfId (the canonical name), a Map of VNF output - * attributes, and a VnfRollback object. This last object can be passed - * as-is to the rollbackVnf operation to undo everything that was created - * for the VNF. This is useful if a VNF is successfully created but the - * orchestrator fails on a subsequent operation. + * The method returns the vnfId (the canonical name), a Map of VNF output attributes, and a VnfRollback object. This + * last object can be passed as-is to the rollbackVnf operation to undo everything that was created for the VNF. + * This is useful if a VNF is successfully created but the orchestrator fails on a subsequent operation. * * @param cloudSiteId CLLI code of the cloud site in which to create the VNF * @param cloudOwner cloud owner of the cloud region in which to create the VNF @@ -181,124 +174,70 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { * @param vnfVersion VNF version key, should match a VNF definition in catalog DB * @param vnfName Name to be assigned to the new VNF * @param inputs Map of key=value inputs for VNF stack creation - * @param failIfExists Flag whether already existing VNF should be considered - * a success or failure + * @param failIfExists Flag whether already existing VNF should be considered a success or failure * @param msoRequest Request tracking information for logs * @param vnfId Holder for output VNF Openstack ID * @param outputs Holder for Map of VNF outputs from heat (assigned IPs, etc) * @param rollback Holder for returning VnfRollback object */ @Override - public void createVnf (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfType, - String vnfVersion, - String vnfName, - String requestType, - String volumeGroupHeatStackId, - Map <String, Object> inputs, - Boolean failIfExists, - Boolean backout, - Boolean enableBridge, - MsoRequest msoRequest, - Holder <String> vnfId, - Holder <Map <String, String>> outputs, - Holder <VnfRollback> rollback) throws VnfException { + public void createVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, String vnfVersion, + String vnfName, String requestType, String volumeGroupHeatStackId, Map<String, Object> inputs, + Boolean failIfExists, Boolean backout, Boolean enableBridge, MsoRequest msoRequest, Holder<String> vnfId, + Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback) throws VnfException { // parameters used for multicloud adapter String genericVnfId = ""; String vfModuleId = ""; - // Create a hook here to catch shortcut createVf requests: - if (requestType != null && requestType.startsWith("VFMOD")) { - logger.debug("Calling createVfModule from createVnf -- requestType=" + requestType); - String newRequestType = requestType.substring(5); - String vfVolGroupHeatStackId = ""; - String vfBaseHeatStackId = ""; - try { - if (volumeGroupHeatStackId != null) { - vfVolGroupHeatStackId = volumeGroupHeatStackId.substring(0, volumeGroupHeatStackId.lastIndexOf('|')); - vfBaseHeatStackId = volumeGroupHeatStackId.substring(volumeGroupHeatStackId.lastIndexOf('|')+1); - } - } catch (Exception e) { - // might be ok - both are just blank - logger.debug("ERROR trying to parse the volumeGroupHeatStackId {}", volumeGroupHeatStackId,e); - } - this.createVfModule(cloudSiteId, - cloudOwner, - tenantId, - vnfType, - vnfVersion, - genericVnfId, - vnfName, - vfModuleId, - newRequestType, - vfVolGroupHeatStackId, - vfBaseHeatStackId, - null, - inputs, - failIfExists, - backout, - enableBridge, - msoRequest, - vnfId, - outputs, - rollback); - return; - } - // createVf will know if the requestType starts with "X" that it's the "old" way - StringBuilder newRequestTypeSb = new StringBuilder("X"); - String vfVolGroupHeatStackId = ""; - String vfBaseHeatStackId = ""; - if (requestType != null) { - newRequestTypeSb.append(requestType); - } - this.createVfModule(cloudSiteId, - cloudOwner, - tenantId, - vnfType, - vnfVersion, - genericVnfId, - vnfName, - vfModuleId, - newRequestTypeSb.toString(), - vfVolGroupHeatStackId, - vfBaseHeatStackId, - null, - inputs, - failIfExists, - backout, - enableBridge, - msoRequest, - vnfId, - outputs, - rollback); - return; - // End createVf shortcut + // Create a hook here to catch shortcut createVf requests: + if (requestType != null && requestType.startsWith("VFMOD")) { + logger.debug("Calling createVfModule from createVnf -- requestType=" + requestType); + String newRequestType = requestType.substring(5); + String vfVolGroupHeatStackId = ""; + String vfBaseHeatStackId = ""; + try { + if (volumeGroupHeatStackId != null) { + vfVolGroupHeatStackId = + volumeGroupHeatStackId.substring(0, volumeGroupHeatStackId.lastIndexOf('|')); + vfBaseHeatStackId = volumeGroupHeatStackId.substring(volumeGroupHeatStackId.lastIndexOf('|') + 1); + } + } catch (Exception e) { + // might be ok - both are just blank + logger.debug("ERROR trying to parse the volumeGroupHeatStackId {}", volumeGroupHeatStackId, e); + } + this.createVfModule(cloudSiteId, cloudOwner, tenantId, vnfType, vnfVersion, genericVnfId, vnfName, + vfModuleId, newRequestType, vfVolGroupHeatStackId, vfBaseHeatStackId, null, inputs, failIfExists, + backout, enableBridge, msoRequest, vnfId, outputs, rollback); + return; } + // createVf will know if the requestType starts with "X" that it's the "old" way + StringBuilder newRequestTypeSb = new StringBuilder("X"); + String vfVolGroupHeatStackId = ""; + String vfBaseHeatStackId = ""; + if (requestType != null) { + newRequestTypeSb.append(requestType); + } + this.createVfModule(cloudSiteId, cloudOwner, tenantId, vnfType, vnfVersion, genericVnfId, vnfName, vfModuleId, + newRequestTypeSb.toString(), vfVolGroupHeatStackId, vfBaseHeatStackId, null, inputs, failIfExists, + backout, enableBridge, msoRequest, vnfId, outputs, rollback); + return; + // End createVf shortcut + } @Override - public void updateVnf(String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfType, - String vnfVersion, - String vnfName, - String requestType, - String volumeGroupHeatStackId, - Map <String, Object> inputs, - MsoRequest msoRequest, - Holder <Map <String, String>> outputs, - Holder <VnfRollback> rollback) throws VnfException { - // As of 1707 - this method should no longer be called - logger.debug("UpdateVnf called?? This should not be called any longer - update vfModule"); + public void updateVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, String vnfVersion, + String vnfName, String requestType, String volumeGroupHeatStackId, Map<String, Object> inputs, + MsoRequest msoRequest, Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback) + throws VnfException { + // As of 1707 - this method should no longer be called + logger.debug("UpdateVnf called?? This should not be called any longer - update vfModule"); } /** - * This is the "Query VNF" web service implementation. - * It will look up a VNF by name or ID in the specified cloud and tenant. + * This is the "Query VNF" web service implementation. It will look up a VNF by name or ID in the specified cloud + * and tenant. * - * The method returns an indicator that the VNF exists, its Openstack internal - * ID, its status, and the set of outputs (from when the stack was created). + * The method returns an indicator that the VNF exists, its Openstack internal ID, its status, and the set of + * outputs (from when the stack was created). * * @param cloudSiteId CLLI code of the cloud site in which to query * @param tenantId Openstack tenant identifier @@ -309,61 +248,55 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { * @param outputs Holder for Map of VNF outputs from heat (assigned IPs, etc) */ @Override - public void queryVnf (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfName, - MsoRequest msoRequest, - Holder <Boolean> vnfExists, - Holder <String> vnfId, - Holder <VnfStatus> status, - Holder <Map <String, String>> outputs) throws VnfException { + public void queryVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, MsoRequest msoRequest, + Holder<Boolean> vnfExists, Holder<String> vnfId, Holder<VnfStatus> status, + Holder<Map<String, String>> outputs) throws VnfException { logger.debug("Querying VNF {} in {}", vnfName, cloudSiteId + "/" + tenantId); // Will capture execution time for metrics - long startTime = System.currentTimeMillis (); + long startTime = System.currentTimeMillis(); StackInfo heatStack = null; - long subStartTime = System.currentTimeMillis (); + long subStartTime = System.currentTimeMillis(); try { - heatStack = heat.queryStack (cloudSiteId, cloudOwner, tenantId, vnfName); + heatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, vnfName); } catch (MsoException me) { - me.addContext ("QueryVNF"); + me.addContext("QueryVNF"); // Failed to query the Stack due to an openstack exception. // Convert to a generic VnfException - String error = "Query VNF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; + String error = + "Query VNF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudSiteId, - tenantId, "OpenStack", "QueryVNF", ErrorCode.DataError.getValue(), "Exception - queryStack", - me); + tenantId, "OpenStack", "QueryVNF", ErrorCode.DataError.getValue(), "Exception - queryStack", me); logger.debug(error); - throw new VnfException (me); + throw new VnfException(me); } // Populate the outputs based on the returned Stack information // - if (heatStack == null || heatStack.getStatus () == HeatStatus.NOTFOUND) { + if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) { // Not Found vnfExists.value = Boolean.FALSE; status.value = VnfStatus.NOTFOUND; vnfId.value = null; outputs.value = new HashMap<>(); // Return as an empty map - logger.debug ("VNF {} not found", vnfName); + logger.debug("VNF {} not found", vnfName); } else { vnfExists.value = Boolean.TRUE; - status.value = stackStatusToVnfStatus (heatStack.getStatus ()); - vnfId.value = heatStack.getCanonicalName (); - outputs.value = copyStringOutputs (heatStack.getOutputs ()); + status.value = stackStatusToVnfStatus(heatStack.getStatus()); + vnfId.value = heatStack.getCanonicalName(); + outputs.value = copyStringOutputs(heatStack.getOutputs()); - logger.debug ("VNF {} found, ID = {}", vnfName, vnfId.value); + logger.debug("VNF {} found, ID = {}", vnfName, vnfId.value); } return; } /** - * This is the "Delete VNF" web service implementation. - * It will delete a VNF by name or ID in the specified cloud and tenant. + * This is the "Delete VNF" web service implementation. It will delete a VNF by name or ID in the specified cloud + * and tenant. * * The method has no outputs. * @@ -374,33 +307,31 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { * @param msoRequest Request tracking information for logs */ @Override - public void deleteVnf (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfName, - MsoRequest msoRequest) throws VnfException { + public void deleteVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, MsoRequest msoRequest) + throws VnfException { logger.debug("Deleting VNF {} in {}", vnfName, cloudSiteId + "/" + tenantId); // Will capture execution time for metrics - long startTime = System.currentTimeMillis (); + long startTime = System.currentTimeMillis(); // Use the MsoHeatUtils to delete the stack. Set the polling flag to true. // The possible outcomes of deleteStack are a StackInfo object with status // of NOTFOUND (on success) or FAILED (on error). Also, MsoOpenstackException // could be thrown. - long subStartTime = System.currentTimeMillis (); + long subStartTime = System.currentTimeMillis(); try { - heat.deleteStack (tenantId, cloudOwner, cloudSiteId, vnfName, true); + heat.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfName, true); } catch (MsoException me) { - me.addContext ("DeleteVNF"); + me.addContext("DeleteVNF"); // Failed to query the Stack due to an openstack exception. // Convert to a generic VnfException - String error = "Delete VNF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId, - tenantId, "OpenStack", "DeleteVNF", ErrorCode.DataError.getValue(), "Exception - DeleteVNF", - me); + String error = + "Delete VNF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner, + cloudSiteId, tenantId, "OpenStack", "DeleteVNF", ErrorCode.DataError.getValue(), + "Exception - DeleteVNF", me); logger.debug(error); - throw new VnfException (me); + throw new VnfException(me); } // On success, nothing is returned. @@ -408,25 +339,24 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } /** - * This web service endpoint will rollback a previous Create VNF operation. - * A rollback object is returned to the client in a successful creation - * response. The client can pass that object as-is back to the rollbackVnf - * operation to undo the creation. + * This web service endpoint will rollback a previous Create VNF operation. A rollback object is returned to the + * client in a successful creation response. The client can pass that object as-is back to the rollbackVnf operation + * to undo the creation. */ @Override - public void rollbackVnf (VnfRollback rollback) throws VnfException { - long startTime = System.currentTimeMillis (); - // rollback may be null (e.g. if stack already existed when Create was called) + public void rollbackVnf(VnfRollback rollback) throws VnfException { + long startTime = System.currentTimeMillis(); + // rollback may be null (e.g. if stack already existed when Create was called) if (rollback == null) { logger.info(MessageEnum.RA_ROLLBACK_NULL.toString(), "OpenStack", "rollbackVnf"); return; } // Get the elements of the VnfRollback object for easier access - String cloudSiteId = rollback.getCloudSiteId (); - String cloudOwner = rollback.getCloudOwner (); - String tenantId = rollback.getTenantId (); - String vnfId = rollback.getVnfId (); + String cloudSiteId = rollback.getCloudSiteId(); + String cloudOwner = rollback.getCloudOwner(); + String tenantId = rollback.getTenantId(); + String vnfId = rollback.getVnfId(); logger.debug("Rolling Back VNF {} in {}", vnfId, cloudOwner + "/" + cloudSiteId + "/" + tenantId); @@ -435,22 +365,23 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // of NOTFOUND (on success) or FAILED (on error). Also, MsoOpenstackException // could be thrown. try { - heat.deleteStack (tenantId, cloudOwner, cloudSiteId, vnfId, true); + heat.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfId, true); } catch (MsoException me) { // Failed to rollback the Stack due to an openstack exception. // Convert to a generic VnfException - me.addContext ("RollbackVNF"); - String error = "Rollback VNF: " + vnfId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfId, cloudOwner, cloudSiteId, - tenantId, "OpenStack", "DeleteStack", ErrorCode.DataError.getValue(), - "Exception - DeleteStack", me); + me.addContext("RollbackVNF"); + String error = + "Rollback VNF: " + vnfId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfId, cloudOwner, + cloudSiteId, tenantId, "OpenStack", "DeleteStack", ErrorCode.DataError.getValue(), + "Exception - DeleteStack", me); logger.debug(error); - throw new VnfException (me); + throw new VnfException(me); } return; } - private VnfStatus stackStatusToVnfStatus (HeatStatus stackStatus) { + private VnfStatus stackStatusToVnfStatus(HeatStatus stackStatus) { switch (stackStatus) { case CREATED: return VnfStatus.ACTIVE; @@ -463,75 +394,73 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } } - private Map <String, String> copyStringOutputs(Map <String, Object> stackOutputs) { - Map <String, String> stringOutputs = new HashMap <> (); - for (Map.Entry<String,Object> entry : stackOutputs.entrySet ()) { + private Map<String, String> copyStringOutputs(Map<String, Object> stackOutputs) { + Map<String, String> stringOutputs = new HashMap<>(); + for (Map.Entry<String, Object> entry : stackOutputs.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); try { - stringOutputs.put(key, value.toString()); + stringOutputs.put(key, value.toString()); } catch (Exception e) { - StringBuilder msg = new StringBuilder("Unable to add " + key + " to outputs"); - if (value instanceof Integer) { // nothing to add to the message - } else if (value instanceof JsonNode) { - msg.append(" - exception converting JsonNode"); - } else if (value instanceof java.util.LinkedHashMap) { - msg.append(" exception converting LinkedHashMap"); - } else { - msg.append(" - unable to call .toString() " + e.getMessage()); - } - logger.debug(msg.toString(), e); + StringBuilder msg = new StringBuilder("Unable to add " + key + " to outputs"); + if (value instanceof Integer) { // nothing to add to the message + } else if (value instanceof JsonNode) { + msg.append(" - exception converting JsonNode"); + } else if (value instanceof java.util.LinkedHashMap) { + msg.append(" exception converting LinkedHashMap"); + } else { + msg.append(" - unable to call .toString() " + e.getMessage()); + } + logger.debug(msg.toString(), e); } } return stringOutputs; } - private Map <String, Object> copyStringInputs (Map <String, Object> stringInputs) { - return new HashMap <> (stringInputs); + private Map<String, Object> copyStringInputs(Map<String, Object> stringInputs) { + return new HashMap<>(stringInputs); } protected boolean callHeatbridge(String heatStackId) { - String executionDir = "/usr/local/lib/python2.7/dist-packages/heatbridge"; - String openstackIdentityUrl = "", username = "", password = "", tenant = "", region = "", owner = ""; + String executionDir = "/usr/local/lib/python2.7/dist-packages/heatbridge"; + String openstackIdentityUrl = "", username = "", password = "", tenant = "", region = "", owner = ""; long waitTimeMs = 10000L; - try { - String[] cmdarray = - {"/usr/bin/python", "HeatBridgeMain.py", openstackIdentityUrl, username, password, tenant, region, owner, - heatStackId}; - String[] envp = null; - File dir = new File(executionDir); - logger.debug("Calling HeatBridgeMain.py in {} with arguments {}", dir, Arrays.toString(cmdarray)); - Runtime r = Runtime.getRuntime(); - Process p = r.exec(cmdarray, envp, dir); - boolean wait = p.waitFor(waitTimeMs, TimeUnit.MILLISECONDS); - - logger.debug(" HeatBridgeMain.py returned {} with code {}", wait, p.exitValue()); - return wait && p.exitValue() == 0; - } catch (IOException e) { - logger.debug(" HeatBridgeMain.py failed with IO Exception! " + e); - return false; - } catch (RuntimeException e) { - logger.debug(" HeatBridgeMain.py failed during runtime!" + e); - return false; - } - catch (Exception e) { - logger.debug(" HeatBridgeMain.py failed for unknown reasons! " + e); - return false; - } + try { + String[] cmdarray = {"/usr/bin/python", "HeatBridgeMain.py", openstackIdentityUrl, username, password, + tenant, region, owner, heatStackId}; + String[] envp = null; + File dir = new File(executionDir); + logger.debug("Calling HeatBridgeMain.py in {} with arguments {}", dir, Arrays.toString(cmdarray)); + Runtime r = Runtime.getRuntime(); + Process p = r.exec(cmdarray, envp, dir); + boolean wait = p.waitFor(waitTimeMs, TimeUnit.MILLISECONDS); + + logger.debug(" HeatBridgeMain.py returned {} with code {}", wait, p.exitValue()); + return wait && p.exitValue() == 0; + } catch (IOException e) { + logger.debug(" HeatBridgeMain.py failed with IO Exception! " + e); + return false; + } catch (RuntimeException e) { + logger.debug(" HeatBridgeMain.py failed during runtime!" + e); + return false; + } catch (Exception e) { + logger.debug(" HeatBridgeMain.py failed for unknown reasons! " + e); + return false; + } } - private void heatbridge(StackInfo heatStack, String cloudOwner, String cloudSiteId, String tenantId, String genericVnfName, - String vfModuleId) { + private void heatbridge(StackInfo heatStack, String cloudOwner, String cloudSiteId, String tenantId, + String genericVnfName, String vfModuleId) { try { - CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( - () -> new MsoCloudSiteNotFound(cloudSiteId)); + CloudSite cloudSite = + cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId)); CloudIdentity cloudIdentity = cloudSite.getIdentityService(); String heatStackId = heatStack.getCanonicalName().split("/")[1]; List<String> oobMgtNetNames = new ArrayList<>(); - HeatBridgeApi heatBridgeClient = new HeatBridgeImpl(new AAIResourcesClient(), cloudIdentity, - cloudOwner, cloudSiteId, tenantId); + HeatBridgeApi heatBridgeClient = + new HeatBridgeImpl(new AAIResourcesClient(), cloudIdentity, cloudOwner, cloudSiteId, tenantId); OpenstackClient openstackClient = heatBridgeClient.authenticate(); List<Resource> stackResources = heatBridgeClient.queryNestedHeatStackResources(heatStackId); @@ -543,14 +472,14 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { List<Flavor> osFlavors = heatBridgeClient.extractOpenstackFlavorsFromServers(osServers); logger.debug("Successfully queried heat stack{} for resources.", heatStackId); - //os images + // os images if (osImages != null && !osImages.isEmpty()) { heatBridgeClient.buildAddImagesToAaiAction(osImages); logger.debug("Successfully built AAI actions to add images."); } else { logger.debug("No images to update to AAI."); } - //flavors + // flavors if (osFlavors != null && !osFlavors.isEmpty()) { heatBridgeClient.buildAddFlavorsToAaiAction(osFlavors); logger.debug("Successfully built AAI actions to add flavors."); @@ -558,22 +487,22 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { logger.debug("No flavors to update to AAI."); } - //compute resources + // compute resources heatBridgeClient.buildAddVserversToAaiAction(genericVnfName, vfModuleId, osServers); logger.debug("Successfully queried compute resources and built AAI vserver actions."); - //neutron resources + // neutron resources List<String> oobMgtNetIds = new ArrayList<>(); - //if no network-id list is provided, however network-name list is + // if no network-id list is provided, however network-name list is if (!CollectionUtils.isEmpty(oobMgtNetNames)) { oobMgtNetIds = heatBridgeClient.extractNetworkIds(oobMgtNetNames); } heatBridgeClient.buildAddVserverLInterfacesToAaiAction(stackResources, oobMgtNetIds); logger.debug( - "Successfully queried neutron resources and built AAI actions to add l-interfaces to vservers."); + "Successfully queried neutron resources and built AAI actions to add l-interfaces to vservers."); - //Update AAI + // Update AAI heatBridgeClient.submitToAai(); } catch (Exception ex) { logger.debug("Heatbrige failed for stackId: " + heatStack.getCanonicalName(), ex); @@ -585,9 +514,9 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { 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(),jpe); + logger.debug("Error converting json to string: {}", jpe.getMessage(), jpe); } 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]"; } @@ -602,15 +531,15 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { Object obj = objectMap.get(key); if (obj instanceof String) { stringMap.put(key, (String) objectMap.get(key)); - } else if (obj instanceof JsonNode ){ + } else if (obj 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 { String str = this.convertNode((JsonNode) obj); stringMap.put(key, str); } catch (Exception e) { - logger.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode "+ key,e); - //okay in this instance - only string values (fqdn) are expected to be needed + logger.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode " + key, e); + // okay in this instance - only string values (fqdn) are expected to be needed } } else if (obj instanceof java.util.LinkedHashMap) { logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode"); @@ -618,21 +547,23 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { String str = JSON_MAPPER.writeValueAsString(obj); stringMap.put(key, str); } catch (Exception e) { - logger.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap "+ key,e); - } - } else if (obj instanceof Integer) { - try { - String str = "" + obj; - stringMap.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 LinkedHashMap " + key, e); + } + } else if (obj instanceof Integer) { + try { + String str = "" + obj; + stringMap.put(key, str); + } catch (Exception e) { + logger.debug("DANGER WILL ROBINSON: unable to convert value for Integer " + key, e); } } else { try { - String str = obj.toString(); + String str = obj.toString(); stringMap.put(key, str); } catch (Exception e) { - logger.debug("DANGER WILL ROBINSON: unable to convert value "+ key + " (" + e.getMessage() + ")",e); + logger.debug( + "DANGER WILL ROBINSON: unable to convert value " + key + " (" + e.getMessage() + ")", + e); } } } @@ -642,34 +573,21 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } @Override - public void createVfModule(String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfType, - String vnfVersion, - String genericVnfName, - String vnfName, - String vfModuleId, - String requestType, - String volumeGroupHeatStackId, - String baseVfHeatStackId, - String modelCustomizationUuid, - Map <String, Object> inputs, - Boolean failIfExists, - Boolean backout, - Boolean enableBridge, - MsoRequest msoRequest, - Holder <String> vnfId, - Holder <Map <String, String>> outputs, - Holder <VnfRollback> rollback) throws VnfException { - String vfModuleName = vnfName; - String vfModuleType = vnfType; - String vfVersion = vnfVersion; + public void createVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, + String vnfVersion, String genericVnfName, String vnfName, String vfModuleId, String requestType, + String volumeGroupHeatStackId, String baseVfHeatStackId, String modelCustomizationUuid, + Map<String, Object> inputs, Boolean failIfExists, Boolean backout, Boolean enableBridge, + MsoRequest msoRequest, Holder<String> vnfId, Holder<Map<String, String>> outputs, + Holder<VnfRollback> rollback) throws VnfException { + String vfModuleName = vnfName; + String vfModuleType = vnfType; + String vfVersion = vnfVersion; String mcu = modelCustomizationUuid; boolean useMCUuid = false; if (mcu != null && !mcu.isEmpty()) { if ("null".equalsIgnoreCase(mcu)) { - logger.debug("modelCustomizationUuid: passed in as the string 'null' - will ignore: " + modelCustomizationUuid); + logger.debug("modelCustomizationUuid: passed in as the string 'null' - will ignore: " + + modelCustomizationUuid); useMCUuid = false; mcu = ""; } else { @@ -678,37 +596,39 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } } - String requestTypeString = ""; + String requestTypeString = ""; if (requestType != null && !"".equals(requestType)) { - requestTypeString = requestType; + requestTypeString = requestType; } String nestedStackId = null; - if (volumeGroupHeatStackId != null && !"".equals(volumeGroupHeatStackId) && !"null".equalsIgnoreCase(volumeGroupHeatStackId)) { - nestedStackId = volumeGroupHeatStackId; + if (volumeGroupHeatStackId != null && !"".equals(volumeGroupHeatStackId) + && !"null".equalsIgnoreCase(volumeGroupHeatStackId)) { + nestedStackId = volumeGroupHeatStackId; } String nestedBaseStackId = null; if (baseVfHeatStackId != null && !"".equals(baseVfHeatStackId) && !"null".equalsIgnoreCase(baseVfHeatStackId)) { - nestedBaseStackId = baseVfHeatStackId; + nestedBaseStackId = baseVfHeatStackId; } - //This method will also handle doing things the "old" way - i.e., just orchestrate a VNF + // This method will also handle doing things the "old" way - i.e., just orchestrate a VNF boolean oldWay = false; if (requestTypeString.startsWith("X")) { - oldWay = true; + oldWay = true; logger.debug("orchestrating a VNF - *NOT* a module!"); - requestTypeString = requestTypeString.substring(1); + requestTypeString = requestTypeString.substring(1); } // 1607 - let's parse out the request type we're being sent boolean isBaseRequest = false; boolean isVolumeRequest = false; if (requestTypeString.startsWith("VOLUME")) { - isVolumeRequest = true; + isVolumeRequest = true; } - logger.debug("requestTypeString = " + requestTypeString + ", nestedStackId = " + nestedStackId + ", nestedBaseStackId = " + nestedBaseStackId); + logger.debug("requestTypeString = " + requestTypeString + ", nestedStackId = " + nestedStackId + + ", nestedBaseStackId = " + nestedBaseStackId); // Will capture execution time for metrics - long startTime = System.currentTimeMillis (); + long startTime = System.currentTimeMillis(); // Build a default rollback object (no actions performed) VnfRollback vfRollback = new VnfRollback(); @@ -723,145 +643,158 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { vfRollback.setModelCustomizationUuid(mcu); // Put data into A&AI through Heatstack - if(enableBridge != null && enableBridge) { - callHeatbridge(baseVfHeatStackId); + if (enableBridge != null && enableBridge) { + callHeatbridge(baseVfHeatStackId); } StackInfo heatStack = null; - long subStartTime1 = System.currentTimeMillis (); + long subStartTime1 = System.currentTimeMillis(); try { - heatStack = heat.queryStack (cloudSiteId, cloudOwner, tenantId, vfModuleName); + heatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, vfModuleName); } catch (MsoException me) { - String error = "Create VF Module: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, cloudSiteId, - tenantId, "OpenStack", "queryStack", ErrorCode.DataError.getValue(), "Exception - queryStack", - me); + String error = "Create VF Module: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/" + + tenantId + ": " + me; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, + cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack", ErrorCode.DataError.getValue(), + "Exception - queryStack", me); logger.debug(error); // Failed to query the Stack due to an openstack exception. // Convert to a generic VnfException - me.addContext ("CreateVFModule"); - throw new VnfException (me); + me.addContext("CreateVFModule"); + throw new VnfException(me); } // New with 1607 - more precise handling/messaging if the stack already exists if (heatStack != null && heatStack.getStatus() != HeatStatus.NOTFOUND) { - // INIT, CREATED, NOTFOUND, FAILED, BUILDING, DELETING, UNKNOWN, UPDATING, UPDATED - HeatStatus status = heatStack.getStatus(); - if (status == HeatStatus.INIT || status == HeatStatus.BUILDING || status == HeatStatus.DELETING || status == HeatStatus.UPDATING) { - // fail - it's in progress - return meaningful error - String error = "Create VF: Stack " + vfModuleName + " already exists and has status " + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; please wait for it to complete, or fix manually."; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack", ErrorCode.DataError.getValue(), - "Stack " + vfModuleName + " already exists"); - logger.debug(error); - throw new VnfAlreadyExists (vfModuleName, cloudOwner, cloudSiteId, tenantId, heatStack.getCanonicalName ()); - } - if (status == HeatStatus.FAILED) { - // fail - it exists and is in a FAILED state - String error = "Create VF: Stack " + vfModuleName + " already exists and is in FAILED state in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention."; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack", ErrorCode.DataError.getValue(), - "Stack " + vfModuleName + " already exists and is " + "in FAILED state"); - logger.debug(error); - throw new VnfAlreadyExists (vfModuleName, cloudOwner, cloudSiteId, tenantId, heatStack.getCanonicalName ()); - } - if (status == HeatStatus.UNKNOWN || status == HeatStatus.UPDATED) { - // fail - it exists and is in a FAILED state - String error = - "Create VF: Stack " + vfModuleName + " already exists and has status " + status.toString() + " in " - + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention."; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack", ErrorCode.DataError.getValue(), - "Stack " + vfModuleName + " already exists and is " + "in UPDATED or UNKNOWN state"); - logger.debug(error); - throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId, heatStack.getCanonicalName()); - } - if (status == HeatStatus.CREATED) { - // fail - it exists - if (failIfExists != null && failIfExists) { - String error = - "Create VF: Stack " + vfModuleName + " already exists in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId; + // INIT, CREATED, NOTFOUND, FAILED, BUILDING, DELETING, UNKNOWN, UPDATING, UPDATED + HeatStatus status = heatStack.getStatus(); + if (status == HeatStatus.INIT || status == HeatStatus.BUILDING || status == HeatStatus.DELETING + || status == HeatStatus.UPDATING) { + // fail - it's in progress - return meaningful error + String error = "Create VF: Stack " + vfModuleName + " already exists and has status " + + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + + "; please wait for it to complete, or fix manually."; logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack", ErrorCode.DataError.getValue(), - "Stack " + vfModuleName + " already exists"); + cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack", ErrorCode.DataError.getValue(), + "Stack " + vfModuleName + " already exists"); logger.debug(error); - throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId, heatStack.getCanonicalName()); - } else { - logger.debug ("Found Existing stack, status={}", heatStack.getStatus ()); - // Populate the outputs from the existing stack. - vnfId.value = heatStack.getCanonicalName (); - outputs.value = copyStringOutputs (heatStack.getOutputs ()); - rollback.value = vfRollback; // Default rollback - no updates performed - } - } + throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId, + heatStack.getCanonicalName()); + } + if (status == HeatStatus.FAILED) { + // fail - it exists and is in a FAILED state + String error = "Create VF: Stack " + vfModuleName + " already exists and is in FAILED state in " + + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention."; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, + cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack", ErrorCode.DataError.getValue(), + "Stack " + vfModuleName + " already exists and is " + "in FAILED state"); + logger.debug(error); + throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId, + heatStack.getCanonicalName()); + } + if (status == HeatStatus.UNKNOWN || status == HeatStatus.UPDATED) { + // fail - it exists and is in a FAILED state + String error = "Create VF: Stack " + vfModuleName + " already exists and has status " + + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + + "; requires manual intervention."; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, + cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack", ErrorCode.DataError.getValue(), + "Stack " + vfModuleName + " already exists and is " + "in UPDATED or UNKNOWN state"); + logger.debug(error); + throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId, + heatStack.getCanonicalName()); + } + if (status == HeatStatus.CREATED) { + // fail - it exists + if (failIfExists != null && failIfExists) { + String error = "Create VF: Stack " + vfModuleName + " already exists in " + cloudOwner + "/" + + cloudSiteId + "/" + tenantId; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), + vfModuleName, cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack", + ErrorCode.DataError.getValue(), "Stack " + vfModuleName + " already exists"); + logger.debug(error); + throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId, + heatStack.getCanonicalName()); + } else { + logger.debug("Found Existing stack, status={}", heatStack.getStatus()); + // Populate the outputs from the existing stack. + vnfId.value = heatStack.getCanonicalName(); + outputs.value = copyStringOutputs(heatStack.getOutputs()); + rollback.value = vfRollback; // Default rollback - no updates performed + } + } return; } // handle a nestedStackId if sent- this one would be for the volume - so applies to both Vf and Vnf StackInfo nestedHeatStack = null; - long subStartTime2 = System.currentTimeMillis (); + long subStartTime2 = System.currentTimeMillis(); Map<String, Object> nestedVolumeOutputs = null; if (nestedStackId != null) { - try { - logger.debug("Querying for nestedStackId = {}", nestedStackId); - nestedHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedStackId); - } catch (MsoException me) { - // Failed to query the Stack due to an openstack exception. - // Convert to a generic VnfException - me.addContext ("CreateVFModule"); - String error = "Create VFModule: Attached heatStack ID Query " + nestedStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, cloudSiteId, - tenantId, "OpenStack", "queryStack", ErrorCode.BusinessProcesssError.getValue(), - "MsoException trying to query nested stack", me); - logger.debug("ERROR trying to query nested stack= {}", error); - throw new VnfException (me); - } - if (nestedHeatStack == null || nestedHeatStack.getStatus() == HeatStatus.NOTFOUND) { - String error = "Create VFModule: Attached heatStack ID DOES NOT EXIST " + nestedStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR" ; - logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, error, "OpenStack", "queryStack", - ErrorCode.BusinessProcesssError.getValue(), - "Create VFModule: Attached heatStack ID " + "DOES NOT EXIST"); - logger.debug(error); - throw new VnfException (error, MsoExceptionCategory.USERDATA); - } else { - logger.debug("Found nested volume heat stack - copying values to inputs *later*"); - nestedVolumeOutputs = nestedHeatStack.getOutputs(); - } + try { + logger.debug("Querying for nestedStackId = {}", nestedStackId); + nestedHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedStackId); + } catch (MsoException me) { + // Failed to query the Stack due to an openstack exception. + // Convert to a generic VnfException + me.addContext("CreateVFModule"); + String error = "Create VFModule: Attached heatStack ID Query " + nestedStackId + " in " + cloudOwner + + "/" + cloudSiteId + "/" + tenantId + ": " + me; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, + cloudOwner, cloudSiteId, tenantId, "OpenStack", "queryStack", + ErrorCode.BusinessProcesssError.getValue(), "MsoException trying to query nested stack", me); + logger.debug("ERROR trying to query nested stack= {}", error); + throw new VnfException(me); + } + if (nestedHeatStack == null || nestedHeatStack.getStatus() == HeatStatus.NOTFOUND) { + String error = "Create VFModule: Attached heatStack ID DOES NOT EXIST " + nestedStackId + " in " + + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR"; + logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, + cloudOwner, cloudSiteId, tenantId, error, "OpenStack", "queryStack", + ErrorCode.BusinessProcesssError.getValue(), + "Create VFModule: Attached heatStack ID " + "DOES NOT EXIST"); + logger.debug(error); + throw new VnfException(error, MsoExceptionCategory.USERDATA); + } else { + logger.debug("Found nested volume heat stack - copying values to inputs *later*"); + nestedVolumeOutputs = nestedHeatStack.getOutputs(); + } } // handle a nestedBaseStackId if sent- this is the stack ID of the base. Should be null for VNF requests StackInfo nestedBaseHeatStack = null; - long subStartTime3 = System.currentTimeMillis (); + long subStartTime3 = System.currentTimeMillis(); Map<String, Object> baseStackOutputs = null; if (nestedBaseStackId != null) { - try { - logger.debug("Querying for nestedBaseStackId = {}", nestedBaseStackId); - nestedBaseHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedBaseStackId); - } catch (MsoException me) { - // Failed to query the Stack due to an openstack exception. - // Convert to a generic VnfException - me.addContext ("CreateVFModule"); - String error = "Create VFModule: Attached baseHeatStack ID Query " + nestedBaseStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ; - logger - .error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, cloudSiteId, - tenantId, "OpenStack", "QueryStack", ErrorCode.BusinessProcesssError.getValue(), - "MsoException trying to query nested base stack", me); - logger.debug("ERROR trying to query nested base stack= {}", error); - throw new VnfException (me); - } - if (nestedBaseHeatStack == null || nestedBaseHeatStack.getStatus() == HeatStatus.NOTFOUND) { - String error = "Create VFModule: Attached base heatStack ID DOES NOT EXIST " + nestedBaseStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR" ; - logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, error, "OpenStack", "QueryStack", - ErrorCode.BusinessProcesssError.getValue(), - "Create VFModule: Attached base heatStack ID DOES NOT EXIST"); - logger.debug("Exception occurred", error); - throw new VnfException (error, MsoExceptionCategory.USERDATA); - } else { - logger.debug("Found nested base heat stack - these values will be copied to inputs *later*"); - baseStackOutputs = nestedBaseHeatStack.getOutputs(); - } + try { + logger.debug("Querying for nestedBaseStackId = {}", nestedBaseStackId); + nestedBaseHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedBaseStackId); + } catch (MsoException me) { + // Failed to query the Stack due to an openstack exception. + // Convert to a generic VnfException + me.addContext("CreateVFModule"); + String error = "Create VFModule: Attached baseHeatStack ID Query " + nestedBaseStackId + " in " + + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, + cloudOwner, cloudSiteId, tenantId, "OpenStack", "QueryStack", + ErrorCode.BusinessProcesssError.getValue(), "MsoException trying to query nested base stack", + me); + logger.debug("ERROR trying to query nested base stack= {}", error); + throw new VnfException(me); + } + if (nestedBaseHeatStack == null || nestedBaseHeatStack.getStatus() == HeatStatus.NOTFOUND) { + String error = "Create VFModule: Attached base heatStack ID DOES NOT EXIST " + nestedBaseStackId + + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR"; + logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, + cloudOwner, cloudSiteId, tenantId, error, "OpenStack", "QueryStack", + ErrorCode.BusinessProcesssError.getValue(), + "Create VFModule: Attached base heatStack ID DOES NOT EXIST"); + logger.debug("Exception occurred", error); + throw new VnfException(error, MsoExceptionCategory.USERDATA); + } else { + logger.debug("Found nested base heat stack - these values will be copied to inputs *later*"); + baseStackOutputs = nestedBaseHeatStack.getOutputs(); + } } // Ready to deploy the new VNF @@ -870,30 +803,31 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { try { // Retrieve the VF - VfModule vf = null; - VnfResource vnfResource = null; - VfModuleCustomization vfmc = null; - logger.debug("version: {}", vfVersion); + VfModule vf = null; + VnfResource vnfResource = null; + VfModuleCustomization vfmc = null; + logger.debug("version: {}", vfVersion); if (useMCUuid) { - // 1707 - db refactoring - vfmc = vfModuleCustomRepo.findFirstByModelCustomizationUUIDOrderByCreatedDesc(mcu); - if(vfmc != null) - vf=vfmc.getVfModule(); - else - vf=null; + // 1707 - db refactoring + vfmc = vfModuleCustomRepo.findFirstByModelCustomizationUUIDOrderByCreatedDesc(mcu); + if (vfmc != null) + vf = vfmc.getVfModule(); + else + vf = null; // 1702 - this will be the new way going forward. We find the vf by mcu - otherwise, code is the same. if (vf == null) { - logger.debug("Unable to find vfModuleCust with modelCustomizationUuid={}", mcu); - String error = "Create vfModule error: Unable to find vfModuleCust with modelCustomizationUuid=" + mcu; + logger.debug("Unable to find vfModuleCust with modelCustomizationUuid={}", mcu); + String error = + "Create vfModule error: Unable to find vfModuleCust with modelCustomizationUuid=" + mcu; logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), - "VF Module ModelCustomizationUuid", modelCustomizationUuid, "OpenStack", - ErrorCode.DataError.getValue(), - "Create VF Module: Unable to find vfModule with " + "modelCustomizationUuid=" + mcu); + "VF Module ModelCustomizationUuid", modelCustomizationUuid, "OpenStack", + ErrorCode.DataError.getValue(), + "Create VF Module: Unable to find vfModule with " + "modelCustomizationUuid=" + mcu); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); } else { - logger.trace("Found vfModuleCust entry {}", vfmc.toString()); + logger.trace("Found vfModuleCust entry {}", vfmc.toString()); } if (vf.getIsBase()) { isBaseRequest = true; @@ -901,166 +835,170 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } else { logger.debug("This is *not* a BASE VF request!"); if (!isVolumeRequest && nestedBaseStackId == null) { - logger.debug("DANGER WILL ROBINSON! This is unexpected - no nestedBaseStackId with this non-base request"); + logger.debug( + "DANGER WILL ROBINSON! This is unexpected - no nestedBaseStackId with this non-base request"); } } - } - - else { // This is to support gamma only - get info from vnf_resource table - if (vfVersion != null && !vfVersion.isEmpty()) { - vnfResource = vnfResourceRepo.findByModelNameAndModelVersion(vnfType, vnfVersion); - } else { - vnfResource = vnfResourceRepo.findByModelName(vnfType); - } - if (vnfResource == null) { - String error = "Create VNF: Unknown VNF Type: " + vnfType; - logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VNF Type", vnfType, - "OpenStack", ErrorCode.DataError.getValue(), "Create VNF: Unknown VNF Type"); - logger.debug(error); - throw new VnfException(error, MsoExceptionCategory.USERDATA); - } + } + + else { // This is to support gamma only - get info from vnf_resource table + if (vfVersion != null && !vfVersion.isEmpty()) { + vnfResource = vnfResourceRepo.findByModelNameAndModelVersion(vnfType, vnfVersion); + } else { + vnfResource = vnfResourceRepo.findByModelName(vnfType); + } + if (vnfResource == null) { + String error = "Create VNF: Unknown VNF Type: " + vnfType; + logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VNF Type", vnfType, + "OpenStack", ErrorCode.DataError.getValue(), "Create VNF: Unknown VNF Type"); + logger.debug(error); + throw new VnfException(error, MsoExceptionCategory.USERDATA); + } logger.debug("Got VNF module definition from Catalog: {}", vnfResource.toString()); } - // By here - we have either a vf or vnfResource + // By here - we have either a vf or vnfResource - //1607 - Add version check + // 1607 - Add version check // First - see if it's in the VnfResource record // if we have a vf Module - then we have to query to get the VnfResource record. if (!oldWay && vf.getVnfResources() != null) { - vnfResource = vf.getVnfResources(); - if (vnfResource == null) { - logger.debug("Unable to find vnfResource will not error for now..."); - } + vnfResource = vf.getVnfResources(); + if (vnfResource == null) { + logger.debug("Unable to find vnfResource will not error for now..."); + } } String minVersionVnf = null; String maxVersionVnf = null; if (vnfResource != null) { - try { - minVersionVnf = vnfResource.getAicVersionMin(); - maxVersionVnf = vnfResource.getAicVersionMax(); - } catch (Exception e) { - logger.debug("Unable to pull min/max version for this VNF Resource entry",e); - minVersionVnf = null; - maxVersionVnf = null; - } - if (minVersionVnf != null && "".equals(minVersionVnf)) { - minVersionVnf = null; - } - if (maxVersionVnf != null && "".equals(maxVersionVnf)) { - maxVersionVnf = null; - } - } - if (minVersionVnf != null && maxVersionVnf != null) { - MavenLikeVersioning aicV = new MavenLikeVersioning(); - - // double check - if (this.cloudConfig != null) { + try { + minVersionVnf = vnfResource.getAicVersionMin(); + maxVersionVnf = vnfResource.getAicVersionMax(); + } catch (Exception e) { + logger.debug("Unable to pull min/max version for this VNF Resource entry", e); + minVersionVnf = null; + maxVersionVnf = null; + } + if (minVersionVnf != null && "".equals(minVersionVnf)) { + minVersionVnf = null; + } + if (maxVersionVnf != null && "".equals(maxVersionVnf)) { + maxVersionVnf = null; + } + } + if (minVersionVnf != null && maxVersionVnf != null) { + MavenLikeVersioning aicV = new MavenLikeVersioning(); + + // double check + if (this.cloudConfig != null) { Optional<CloudSite> cloudSiteOpt = this.cloudConfig.getCloudSite(cloudSiteId); if (cloudSiteOpt.isPresent()) { aicV.setVersion(cloudSiteOpt.get().getCloudVersion()); - // Add code to handle unexpected values in here - boolean moreThanMin = true; - boolean equalToMin = true; - boolean moreThanMax = true; - boolean equalToMax = true; - boolean doNotTest = false; - try { - moreThanMin = aicV.isMoreRecentThan(minVersionVnf); - equalToMin = aicV.isTheSameVersion(minVersionVnf); - moreThanMax = aicV.isMoreRecentThan(maxVersionVnf); - equalToMax = aicV.isTheSameVersion(maxVersionVnf); - } catch (Exception e) { - logger.debug("An exception occurred while trying to test AIC Version {} - will default to not check", - e.getMessage(), e); - doNotTest = true; - } - if (!doNotTest) { - if ((moreThanMin || equalToMin) // aic >= min - && (equalToMax || !(moreThanMax))) { //aic <= max - logger.debug( - "VNF Resource " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUUID() - + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " supported on Cloud: " - + cloudSiteId + " with AIC_Version:" + cloudSiteOpt.get().getCloudVersion()); - } else { - // ERROR - String error = "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUUID() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " + cloudSiteId + " with AIC_Version:" + cloudSiteOpt.get().getCloudVersion(); - logger.error("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, "OpenStack", - ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion"); - logger.debug(error); - throw new VnfException(error, MsoExceptionCategory.USERDATA); - } - } else { - logger.debug("bypassing testing AIC version..."); - } - } // let this error out downstream to avoid introducing uncertainty at this stage - } else { - logger.debug("cloudConfig is NULL - cannot check cloud site version"); - } - } else { - logger.debug("AIC Version not set in VNF_Resource - this is expected thru 1607 - do not error here - not checked" - + "."); - } - // End Version check 1607 - - - - - // By the time we get here - heatTemplateId and heatEnvtId should be populated (or null) - HeatTemplate heatTemplate = null; + // Add code to handle unexpected values in here + boolean moreThanMin = true; + boolean equalToMin = true; + boolean moreThanMax = true; + boolean equalToMax = true; + boolean doNotTest = false; + try { + moreThanMin = aicV.isMoreRecentThan(minVersionVnf); + equalToMin = aicV.isTheSameVersion(minVersionVnf); + moreThanMax = aicV.isMoreRecentThan(maxVersionVnf); + equalToMax = aicV.isTheSameVersion(maxVersionVnf); + } catch (Exception e) { + logger.debug( + "An exception occurred while trying to test AIC Version {} - will default to not check", + e.getMessage(), e); + doNotTest = true; + } + if (!doNotTest) { + if ((moreThanMin || equalToMin) // aic >= min + && (equalToMax || !(moreThanMax))) { // aic <= max + logger.debug("VNF Resource " + vnfResource.getModelName() + ", ModelUuid=" + + vnfResource.getModelUUID() + " VersionMin=" + minVersionVnf + " VersionMax:" + + maxVersionVnf + " supported on Cloud: " + cloudSiteId + " with AIC_Version:" + + cloudSiteOpt.get().getCloudVersion()); + } else { + // ERROR + String error = "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" + + vnfResource.getModelUUID() + " VersionMin=" + minVersionVnf + " VersionMax:" + + maxVersionVnf + " NOT supported on Cloud: " + cloudSiteId + + " with AIC_Version:" + cloudSiteOpt.get().getCloudVersion(); + logger.error("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, "OpenStack", + ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion"); + logger.debug(error); + throw new VnfException(error, MsoExceptionCategory.USERDATA); + } + } else { + logger.debug("bypassing testing AIC version..."); + } + } // let this error out downstream to avoid introducing uncertainty at this stage + } else { + logger.debug("cloudConfig is NULL - cannot check cloud site version"); + } + } else { + logger.debug( + "AIC Version not set in VNF_Resource - this is expected thru 1607 - do not error here - not checked" + + "."); + } + // End Version check 1607 + + + + // By the time we get here - heatTemplateId and heatEnvtId should be populated (or null) + HeatTemplate heatTemplate = null; HeatEnvironment heatEnvironment = null; if (oldWay) { - //This will handle old Gamma BrocadeVCE VNF - heatTemplate = vnfResource.getHeatTemplates(); - } - else { - if (vf != null) { - if (isVolumeRequest) { - heatTemplate = vf.getVolumeHeatTemplate(); - heatEnvironment = vfmc.getVolumeHeatEnv(); - } else { - heatTemplate = vf.getModuleHeatTemplate(); - heatEnvironment = vfmc.getHeatEnvironment(); - } - } - } - - if (heatTemplate == null) { - String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType + ", reqType=" + requestTypeString; - logger - .error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", vfModuleType, - "OpenStack", ErrorCode.DataError.getValue(), error); - logger.debug(error); - throw new VnfException(error, MsoExceptionCategory.INTERNAL); - } else { - logger.debug("Got HEAT Template from DB: {}", heatTemplate.getHeatTemplate()); - } - - if (oldWay) { - //This will handle old Gamma BrocadeVCE VNF - logger.debug("No environment parameter found for this Type " + vfModuleType); - } else { - if (heatEnvironment == null) { - String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType; - logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID", - "OpenStack", ErrorCode.DataError.getValue(), error); - logger.debug(error); - throw new VnfException (error, MsoExceptionCategory.INTERNAL); - } else { - logger.debug("Got Heat Environment from DB: {}", heatEnvironment.getEnvironment()); - } - } + // This will handle old Gamma BrocadeVCE VNF + heatTemplate = vnfResource.getHeatTemplates(); + } else { + if (vf != null) { + if (isVolumeRequest) { + heatTemplate = vf.getVolumeHeatTemplate(); + heatEnvironment = vfmc.getVolumeHeatEnv(); + } else { + heatTemplate = vf.getModuleHeatTemplate(); + heatEnvironment = vfmc.getHeatEnvironment(); + } + } + } + + if (heatTemplate == null) { + String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType + + ", reqType=" + requestTypeString; + logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", + vfModuleType, "OpenStack", ErrorCode.DataError.getValue(), error); + logger.debug(error); + throw new VnfException(error, MsoExceptionCategory.INTERNAL); + } else { + logger.debug("Got HEAT Template from DB: {}", heatTemplate.getHeatTemplate()); + } + + if (oldWay) { + // This will handle old Gamma BrocadeVCE VNF + logger.debug("No environment parameter found for this Type " + vfModuleType); + } else { + if (heatEnvironment == null) { + String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType; + logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID", + "OpenStack", ErrorCode.DataError.getValue(), error); + logger.debug(error); + throw new VnfException(error, MsoExceptionCategory.INTERNAL); + } else { + logger.debug("Got Heat Environment from DB: {}", heatEnvironment.getEnvironment()); + } + } logger.debug("In MsoVnfAdapterImpl, about to call db.getNestedTemplates avec templateId=" - + heatTemplate.getArtifactUuid ()); + + heatTemplate.getArtifactUuid()); List<HeatTemplate> nestedTemplates = heatTemplate.getChildTemplates(); - Map <String, Object> nestedTemplatesChecked = new HashMap <> (); + Map<String, Object> nestedTemplatesChecked = new HashMap<>(); if (nestedTemplates != null && !nestedTemplates.isEmpty()) { // for debugging print them out logger.debug("Contents of nestedTemplates - to be added to files: on stack:"); for (HeatTemplate entry : nestedTemplates) { - nestedTemplatesChecked.put (entry.getTemplateName(), entry.getTemplateBody()); + nestedTemplatesChecked.put(entry.getTemplateName(), entry.getTemplateBody()); logger.debug(entry.getTemplateName() + " -> " + entry.getTemplateBody()); } } else { @@ -1072,51 +1010,53 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // *if* there are any List<HeatFiles> heatFiles = null; - Map<String, Object> heatFilesObjects = new HashMap<>(); + Map<String, Object> heatFilesObjects = new HashMap<>(); // Add ability to turn on adding get_files with volume requests (by property). boolean addGetFilesOnVolumeReq = false; try { - String propertyString = this.environment.getProperty(MsoVnfAdapterImpl.ADD_GET_FILES_ON_VOLUME_REQ); - if ("true".equalsIgnoreCase(propertyString) || "y".equalsIgnoreCase(propertyString)) { - addGetFilesOnVolumeReq = true; - logger.debug("AddGetFilesOnVolumeReq - setting to true! {}", propertyString); - } + String propertyString = this.environment.getProperty(MsoVnfAdapterImpl.ADD_GET_FILES_ON_VOLUME_REQ); + if ("true".equalsIgnoreCase(propertyString) || "y".equalsIgnoreCase(propertyString)) { + addGetFilesOnVolumeReq = true; + logger.debug("AddGetFilesOnVolumeReq - setting to true! {}", propertyString); + } } catch (Exception e) { logger.debug("An error occured trying to get property " + MsoVnfAdapterImpl.ADD_GET_FILES_ON_VOLUME_REQ - + " - default to false", e); - } - - if (!isVolumeRequest || addGetFilesOnVolumeReq) { - if (oldWay) { - logger.debug("In MsoVnfAdapterImpl createVfModule, this should not happen - old way is gamma only - no heat " - + "files!"); - } else { - // 1607 - now use VF_MODULE_TO_HEAT_FILES table - logger.debug("In MsoVnfAdapterImpl createVfModule, about to call db.getHeatFilesForVfModule avec vfModuleId=" - + vf.getModelUUID()); - heatFiles = vf.getHeatFiles(); - } - if (heatFiles != null && !heatFiles.isEmpty()) { - // add these to stack - to be done in createStack - // here, we will map them to Map<String, Object> from - // Map<String, HeatFiles> - // this will match the nested templates format - logger.debug("Contents of heatFiles - to be added to files: on stack"); - - for (HeatFiles heatfile : heatFiles) { - logger.debug(heatfile.getFileName() + " -> " + heatfile.getFileBody()); - heatFilesObjects.put(heatfile.getFileName(), heatfile.getFileBody()); + + " - default to false", e); + } + + if (!isVolumeRequest || addGetFilesOnVolumeReq) { + if (oldWay) { + logger.debug( + "In MsoVnfAdapterImpl createVfModule, this should not happen - old way is gamma only - no heat " + + "files!"); + } else { + // 1607 - now use VF_MODULE_TO_HEAT_FILES table + logger.debug( + "In MsoVnfAdapterImpl createVfModule, about to call db.getHeatFilesForVfModule avec vfModuleId=" + + vf.getModelUUID()); + heatFiles = vf.getHeatFiles(); + } + if (heatFiles != null && !heatFiles.isEmpty()) { + // add these to stack - to be done in createStack + // here, we will map them to Map<String, Object> from + // Map<String, HeatFiles> + // this will match the nested templates format + logger.debug("Contents of heatFiles - to be added to files: on stack"); + + for (HeatFiles heatfile : heatFiles) { + logger.debug(heatfile.getFileName() + " -> " + heatfile.getFileBody()); + heatFilesObjects.put(heatfile.getFileName(), heatfile.getFileBody()); + } + } else { + logger.debug("No heat files found -nothing to do here"); + heatFilesObjects = null; + } } - } else { - logger.debug("No heat files found -nothing to do here"); - heatFilesObjects = null; - } - } // Check that required parameters have been supplied String missingParams = null; - List <String> paramList = new ArrayList <> (); + List<String> paramList = new ArrayList<>(); // New for 1510 - consult the PARAM_ALIAS field to see if we've been // supplied an alias. Only check if we don't find it initially. @@ -1125,11 +1065,11 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // shouldn't boolean checkRequiredParameters = true; try { - String propertyString = this.environment.getProperty (MsoVnfAdapterImpl.CHECK_REQD_PARAMS); - if ("false".equalsIgnoreCase (propertyString) || "n".equalsIgnoreCase (propertyString)) { + String propertyString = this.environment.getProperty(MsoVnfAdapterImpl.CHECK_REQD_PARAMS); + if ("false".equalsIgnoreCase(propertyString) || "n".equalsIgnoreCase(propertyString)) { checkRequiredParameters = false; logger.debug("CheckRequiredParameters is FALSE. Will still check but then skip blocking..." - + MsoVnfAdapterImpl.CHECK_REQD_PARAMS); + + MsoVnfAdapterImpl.CHECK_REQD_PARAMS); } } catch (Exception e) { // No problem - default is true @@ -1140,21 +1080,22 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // Part 2: only submit to openstack the parameters in the envt that are in the heat template // Note this also removes any comments MsoHeatEnvironmentEntry mhee = null; - if (heatEnvironment != null && heatEnvironment.getEnvironment() != null && heatEnvironment.getEnvironment().contains ("parameters:")) { + if (heatEnvironment != null && heatEnvironment.getEnvironment() != null + && heatEnvironment.getEnvironment().contains("parameters:")) { - logger.debug("Enhanced environment checking enabled - 1604"); + logger.debug("Enhanced environment checking enabled - 1604"); StringBuilder sb = new StringBuilder(heatEnvironment.getEnvironment()); mhee = new MsoHeatEnvironmentEntry(sb); StringBuilder sb2 = new StringBuilder("\nHeat Template Parameters:\n"); for (HeatTemplateParam parm : heatTemplate.getParameters()) { - sb2.append("\t" + parm.getParamName() + ", required=" + parm.isRequired()); + sb2.append("\t" + parm.getParamName() + ", required=" + parm.isRequired()); } if (!mhee.isValid()) { - sb2.append("Environment says it's not valid! " + mhee.getErrorString()); + sb2.append("Environment says it's not valid! " + mhee.getErrorString()); } else { - sb2.append("\nEnvironment:"); - sb2.append(mhee.toFullString()); + sb2.append("\nEnvironment:"); + sb2.append(mhee.toFullString()); } logger.debug(sb2.toString()); } else { @@ -1169,18 +1110,18 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { StringBuilder sb = new StringBuilder("\nTemplate Parameters:\n"); int cntr = 0; try { - for (HeatTemplateParam htp : heatTemplate.getParameters()) { - sb.append("param[" + cntr++ + "]=" + htp.getParamName()); - parameterNames.add(htp.getParamName()); - if (htp.getParamAlias() != null && !"".equals(htp.getParamAlias())) { - aliasToParam.put(htp.getParamAlias(), htp.getParamName()); - sb.append(" ** (alias=" + htp.getParamAlias() + ")"); - } - sb.append("\n"); - } + for (HeatTemplateParam htp : heatTemplate.getParameters()) { + sb.append("param[" + cntr++ + "]=" + htp.getParamName()); + parameterNames.add(htp.getParamName()); + if (htp.getParamAlias() != null && !"".equals(htp.getParamAlias())) { + aliasToParam.put(htp.getParamAlias(), htp.getParamName()); + sb.append(" ** (alias=" + htp.getParamAlias() + ")"); + } + sb.append("\n"); + } logger.debug(sb.toString()); } catch (Exception e) { - logger.debug("??An exception occurred trying to go through Parameter Names {}", e.getMessage(),e); + logger.debug("??An exception occurred trying to go through Parameter Names {}", e.getMessage(), e); } // Step 1 - convert what we got as inputs (Map<String, String>) to a // Map<String, Object> - where the object matches the param type identified in the template @@ -1193,176 +1134,164 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { logger.debug("Now add in the volume stack outputs if applicable"); heat.copyBaseOutputsToInputs(goldenInputs, nestedVolumeOutputs, parameterNames, aliasToParam); - for (HeatTemplateParam parm : heatTemplate.getParameters ()) { - logger.debug( - "Parameter:'" + parm.getParamName() + "', isRequired=" + parm.isRequired() + ", alias=" + parm - .getParamAlias()); + for (HeatTemplateParam parm : heatTemplate.getParameters()) { + logger.debug("Parameter:'" + parm.getParamName() + "', isRequired=" + parm.isRequired() + ", alias=" + + parm.getParamAlias()); - if (parm.isRequired () && (goldenInputs == null || !goldenInputs.containsKey (parm.getParamName ()))) { - // The check for an alias was moved to the method in MsoHeatUtils - when we converted the Map<String, String> to Map<String, Object> - logger.debug("**Parameter " + parm.getParamName() + " is required and not in the inputs...check " - + "environment"); + if (parm.isRequired() && (goldenInputs == null || !goldenInputs.containsKey(parm.getParamName()))) { + // The check for an alias was moved to the method in MsoHeatUtils - when we converted the + // Map<String, String> to Map<String, Object> + logger.debug("**Parameter " + parm.getParamName() + " is required and not in the inputs...check " + + "environment"); if (mhee != null && mhee.containsParameter(parm.getParamName())) { logger.debug("Required parameter {} appears to be in environment - do not count as missing", - parm.getParamName()); + parm.getParamName()); } else { logger.debug("adding to missing parameters list: {}", parm.getParamName()); if (missingParams == null) { - missingParams = parm.getParamName (); + missingParams = parm.getParamName(); } else { - missingParams += "," + parm.getParamName (); + missingParams += "," + parm.getParamName(); } } } - paramList.add (parm.getParamName ()); + paramList.add(parm.getParamName()); } if (missingParams != null) { - if (checkRequiredParameters) { - // Problem - missing one or more required parameters - String error = "Create VFModule: Missing Required inputs: " + missingParams; - logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, "OpenStack", - ErrorCode.DataError.getValue(), "Create VFModule: Missing Required inputs"); - logger.debug(error); - throw new VnfException (error, MsoExceptionCategory.USERDATA); - } else { - logger.debug ("found missing parameters - but checkRequiredParameters is false - will not block"); - } + if (checkRequiredParameters) { + // Problem - missing one or more required parameters + String error = "Create VFModule: Missing Required inputs: " + missingParams; + logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, "OpenStack", + ErrorCode.DataError.getValue(), "Create VFModule: Missing Required inputs"); + logger.debug(error); + throw new VnfException(error, MsoExceptionCategory.USERDATA); + } else { + logger.debug("found missing parameters - but checkRequiredParameters is false - will not block"); + } } else { - logger.debug ("No missing parameters found - ok to proceed"); + logger.debug("No missing parameters found - ok to proceed"); } // We can now remove the recreating of the ENV with only legit params - that check is done for us, // and it causes problems with json that has arrays String newEnvironmentString = null; if (mhee != null) { - newEnvironmentString = mhee.getRawEntry().toString(); + newEnvironmentString = mhee.getRawEntry().toString(); } // "Fix" the template if it has CR/LF (getting this from Oracle) - String template = heatTemplate.getHeatTemplate (); - template = template.replaceAll ("\r\n", "\n"); + String template = heatTemplate.getHeatTemplate(); + template = template.replaceAll("\r\n", "\n"); // Valet - 1806 boolean isValetEnabled = this.checkBooleanProperty(MsoVnfAdapterImpl.VALET_ENABLED, false); - boolean failRequestOnValetFailure = this.checkBooleanProperty(MsoVnfAdapterImpl.FAIL_REQUESTS_ON_VALET_FAILURE, false); + boolean failRequestOnValetFailure = + this.checkBooleanProperty(MsoVnfAdapterImpl.FAIL_REQUESTS_ON_VALET_FAILURE, false); logger.debug("isValetEnabled={}, failRequestsOnValetFailure={}", isValetEnabled, failRequestOnValetFailure); if (oldWay || isVolumeRequest) { - isValetEnabled = false; + isValetEnabled = false; logger.debug("do not send to valet for volume requests or brocade"); } boolean sendResponseToValet = false; if (isValetEnabled) { - Holder<Map<String, Object>> valetModifiedParamsHolder = new Holder<>(); - sendResponseToValet = this.valetCreateRequest(cloudSiteId, cloudOwner, tenantId, heatFilesObjects, - nestedTemplatesChecked, vfModuleName, backout, heatTemplate, newEnvironmentString, goldenInputs, - msoRequest, inputs, failRequestOnValetFailure, valetModifiedParamsHolder); - if (sendResponseToValet) { - goldenInputs = valetModifiedParamsHolder.value; - } + Holder<Map<String, Object>> valetModifiedParamsHolder = new Holder<>(); + sendResponseToValet = this.valetCreateRequest(cloudSiteId, cloudOwner, tenantId, heatFilesObjects, + nestedTemplatesChecked, vfModuleName, backout, heatTemplate, newEnvironmentString, goldenInputs, + msoRequest, inputs, failRequestOnValetFailure, valetModifiedParamsHolder); + if (sendResponseToValet) { + goldenInputs = valetModifiedParamsHolder.value; + } } // Have the tenant. Now deploy the stack itself // Ignore MsoTenantNotFound and MsoStackAlreadyExists exceptions // because we already checked for those. - long createStackStarttime = System.currentTimeMillis (); + long createStackStarttime = System.currentTimeMillis(); try { // heatStack = heat.createStack(cloudSiteId, tenantId, vnfName, template, inputs, true, // heatTemplate.getTimeoutMinutes()); - if (backout == null) { - backout = true; - } - if (heat != null) { - logger.debug("heat is not null!!"); - - heatStack = heat.createStack (cloudSiteId, - cloudOwner, - tenantId, - vfModuleName, - null, - template, - goldenInputs, - true, - heatTemplate.getTimeoutMinutes(), - newEnvironmentString, - nestedTemplatesChecked, - heatFilesObjects, - backout.booleanValue()); - } - else { - logger.debug("heat is null!"); - throw new MsoHeatNotFoundException(); - } + if (backout == null) { + backout = true; + } + if (heat != null) { + logger.debug("heat is not null!!"); + + heatStack = heat.createStack(cloudSiteId, cloudOwner, tenantId, vfModuleName, null, template, + goldenInputs, true, heatTemplate.getTimeoutMinutes(), newEnvironmentString, + nestedTemplatesChecked, heatFilesObjects, backout.booleanValue()); + } else { + logger.debug("heat is null!"); + throw new MsoHeatNotFoundException(); + } } catch (MsoException me) { - me.addContext ("CreateVFModule"); - String error = "Create VF Module " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger - .error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, cloudSiteId, - tenantId, "OpenStack", ErrorCode.DataError.getValue(), "MsoException - createStack", - me); + me.addContext("CreateVFModule"); + String error = "Create VF Module " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + + tenantId + ": " + me; + logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, + cloudOwner, cloudSiteId, tenantId, "OpenStack", ErrorCode.DataError.getValue(), + "MsoException - createStack", me); logger.debug(error); if (isValetEnabled && sendResponseToValet) { - logger.debug("valet is enabled, the orchestration failed - now sending rollback to valet"); - try { - GenericValetResponse<ValetRollbackResponse> gvr = this.vci.callValetRollbackRequest(msoRequest.getRequestId(), null, backout, me.getMessage()); - // Nothing to really do here whether it succeeded or not other than log it. - logger.debug("Return code from Rollback response is {}", gvr.getStatusCode()); - } catch (Exception e) { - logger.error("Exception encountered while sending Rollback to Valet ", e); - } + logger.debug("valet is enabled, the orchestration failed - now sending rollback to valet"); + try { + GenericValetResponse<ValetRollbackResponse> gvr = this.vci + .callValetRollbackRequest(msoRequest.getRequestId(), null, backout, me.getMessage()); + // Nothing to really do here whether it succeeded or not other than log it. + logger.debug("Return code from Rollback response is {}", gvr.getStatusCode()); + } catch (Exception e) { + logger.error("Exception encountered while sending Rollback to Valet ", e); + } } - throw new VnfException (me); + throw new VnfException(me); } catch (NullPointerException npe) { - String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + npe; - logger - .error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, cloudSiteId, - tenantId, "OpenStack", ErrorCode.DataError.getValue(), + String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + + tenantId + ": " + npe; + logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, + cloudOwner, cloudSiteId, tenantId, "OpenStack", ErrorCode.DataError.getValue(), "NullPointerException - createStack", npe); logger.debug(error); logger.debug("NULL POINTER EXCEPTION at heat.createStack"); - //npe.addContext ("CreateVNF"); - throw new VnfException ("NullPointerException during heat.createStack"); + // npe.addContext ("CreateVNF"); + throw new VnfException("NullPointerException during heat.createStack"); } catch (Exception e) { - logger.debug("unhandled exception at heat.createStack",e); - throw new VnfException("Exception during heat.createStack! " + e.getMessage()); + logger.debug("unhandled exception at heat.createStack", e); + throw new VnfException("Exception during heat.createStack! " + e.getMessage()); } // Reach this point if createStack is successful. // Populate remaining rollback info and response parameters. - vfRollback.setVnfId (heatStack.getCanonicalName ()); - vfRollback.setVnfCreated (true); + vfRollback.setVnfId(heatStack.getCanonicalName()); + vfRollback.setVnfCreated(true); - vnfId.value = heatStack.getCanonicalName (); - outputs.value = copyStringOutputs (heatStack.getOutputs ()); + vnfId.value = heatStack.getCanonicalName(); + outputs.value = copyStringOutputs(heatStack.getOutputs()); rollback.value = vfRollback; if (isValetEnabled && sendResponseToValet) { - logger.debug("valet is enabled, the orchestration succeeded - now send confirm to valet with stack id"); - try { - GenericValetResponse<ValetConfirmResponse> gvr = this.vci.callValetConfirmRequest(msoRequest.getRequestId(), heatStack.getCanonicalName()); + logger.debug("valet is enabled, the orchestration succeeded - now send confirm to valet with stack id"); + try { + GenericValetResponse<ValetConfirmResponse> gvr = + this.vci.callValetConfirmRequest(msoRequest.getRequestId(), heatStack.getCanonicalName()); // Nothing to really do here whether it succeeded or not other than log it. logger.debug("Return code from Confirm response is {}", gvr.getStatusCode()); } catch (Exception e) { logger.error("Exception encountered while sending Confirm to Valet ", e); } } - logger.debug ("VF Module {} successfully created", vfModuleName); - //call heatbridge + logger.debug("VF Module {} successfully created", vfModuleName); + // call heatbridge heatbridge(heatStack, cloudOwner, cloudSiteId, tenantId, genericVnfName, vfModuleId); return; } catch (Exception e) { - logger.debug("unhandled exception in create VF",e); - throw new VnfException("Exception during create VF " + e.getMessage()); + logger.debug("unhandled exception in create VF", e); + throw new VnfException("Exception during create VF " + e.getMessage()); } } @Override - public void deleteVfModule (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfName, - MsoRequest msoRequest, - Holder <Map <String, String>> outputs) throws VnfException { + public void deleteVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, + MsoRequest msoRequest, Holder<Map<String, String>> outputs) throws VnfException { logger.debug("Deleting VF {} in ", vnfName, cloudOwner + "/" + cloudSiteId + "/" + tenantId); // Will capture execution time for metrics - long startTime = System.currentTimeMillis (); + long startTime = System.currentTimeMillis(); // 1702 capture the output parameters on a delete // so we'll need to query first @@ -1372,62 +1301,69 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } catch (MsoException me) { // Failed to query the Stack due to an openstack exception. // Convert to a generic VnfException - me.addContext ("DeleteVFModule"); - String error = "Delete VFModule: Query to get outputs: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId, - tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(), "Exception - QueryStack", - me); + me.addContext("DeleteVFModule"); + String error = "Delete VFModule: Query to get outputs: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + + "/" + tenantId + ": " + me; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, + cloudSiteId, tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(), + "Exception - QueryStack", me); logger.debug(error); - throw new VnfException (me); + throw new VnfException(me); } - // call method which handles the conversion from Map<String,Object> to Map<String,String> for our expected Object types + // call method which handles the conversion from Map<String,Object> to Map<String,String> for our expected + // Object types outputs.value = this.convertMapStringObjectToStringString(stackOutputs); boolean isValetEnabled = this.checkBooleanProperty(MsoVnfAdapterImpl.VALET_ENABLED, false); - boolean failRequestOnValetFailure = this.checkBooleanProperty(MsoVnfAdapterImpl.FAIL_REQUESTS_ON_VALET_FAILURE, false); + boolean failRequestOnValetFailure = + this.checkBooleanProperty(MsoVnfAdapterImpl.FAIL_REQUESTS_ON_VALET_FAILURE, false); logger.debug("isValetEnabled={}, failRequestsOnValetFailure={}", isValetEnabled, failRequestOnValetFailure); boolean valetDeleteRequestSucceeded = false; if (isValetEnabled) { - valetDeleteRequestSucceeded = this.valetDeleteRequest(cloudSiteId, cloudOwner, tenantId, vnfName, msoRequest, failRequestOnValetFailure); + valetDeleteRequestSucceeded = this.valetDeleteRequest(cloudSiteId, cloudOwner, tenantId, vnfName, + msoRequest, failRequestOnValetFailure); } // Use the MsoHeatUtils to delete the stack. Set the polling flag to true. // The possible outcomes of deleteStack are a StackInfo object with status // of NOTFOUND (on success) or FAILED (on error). Also, MsoOpenstackException // could be thrown. - long subStartTime = System.currentTimeMillis (); + long subStartTime = System.currentTimeMillis(); try { - heat.deleteStack (tenantId, cloudOwner, cloudSiteId, vnfName, true); + heat.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfName, true); } catch (MsoException me) { - me.addContext ("DeleteVNF"); + me.addContext("DeleteVNF"); // Failed to query the Stack due to an openstack exception. // Convert to a generic VnfException - String error = "Delete VF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId, - tenantId, "OpenStack", "DeleteStack", ErrorCode.DataError.getValue(), - "Exception - deleteStack", me); + String error = + "Delete VF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner, + cloudSiteId, tenantId, "OpenStack", "DeleteStack", ErrorCode.DataError.getValue(), + "Exception - deleteStack", me); logger.debug(error); if (isValetEnabled && valetDeleteRequestSucceeded) { - logger.debug("valet is enabled, the orchestration failed - now sending rollback to valet"); - try { - GenericValetResponse<ValetRollbackResponse> gvr = this.vci.callValetRollbackRequest(msoRequest.getRequestId(), vnfName, false, me.getMessage()); - // Nothing to really do here whether it succeeded or not other than log it. - logger.debug("Return code from Rollback response is {}", gvr.getStatusCode()); - } catch (Exception e) { - logger.error("Exception encountered while sending Rollback to Valet ", e); - } + logger.debug("valet is enabled, the orchestration failed - now sending rollback to valet"); + try { + GenericValetResponse<ValetRollbackResponse> gvr = this.vci + .callValetRollbackRequest(msoRequest.getRequestId(), vnfName, false, me.getMessage()); + // Nothing to really do here whether it succeeded or not other than log it. + logger.debug("Return code from Rollback response is {}", gvr.getStatusCode()); + } catch (Exception e) { + logger.error("Exception encountered while sending Rollback to Valet ", e); + } } - throw new VnfException (me); + throw new VnfException(me); } if (isValetEnabled && valetDeleteRequestSucceeded) { - // only if the original request succeeded do we send a confirm - logger.debug("valet is enabled, the delete succeeded - now send confirm to valet"); - try { - GenericValetResponse<ValetConfirmResponse> gvr = this.vci.callValetConfirmRequest(msoRequest.getRequestId(), vnfName); + // only if the original request succeeded do we send a confirm + logger.debug("valet is enabled, the delete succeeded - now send confirm to valet"); + try { + GenericValetResponse<ValetConfirmResponse> gvr = + this.vci.callValetConfirmRequest(msoRequest.getRequestId(), vnfName); // Nothing to really do here whether it succeeded or not other than log it. - logger.debug("Return code from Confirm response is {}", gvr.getStatusCode()); + logger.debug("Return code from Confirm response is {}", gvr.getStatusCode()); } catch (Exception e) { - logger.error("Exception encountered while sending Confirm to Valet ", e); + logger.error("Exception encountered while sending Confirm to Valet ", e); } } @@ -1436,47 +1372,37 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } @Override - public void updateVfModule (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfType, - String vnfVersion, - String vnfName, - String requestType, - String volumeGroupHeatStackId, - String baseVfHeatStackId, - String vfModuleStackId, - String modelCustomizationUuid, - Map <String, Object> inputs, - MsoRequest msoRequest, - Holder <Map <String, String>> outputs, - Holder <VnfRollback> rollback) throws VnfException { - String vfModuleName = vnfName; - String vfModuleType = vnfType; - String methodName = "updateVfModule"; - String serviceName = VNF_ADAPTER_SERVICE_NAME + methodName; - - StringBuilder sbInit = new StringBuilder(); - sbInit.append("updateVfModule: \n"); - sbInit.append("cloudOwner=" + cloudOwner + "\n"); + public void updateVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, + String vnfVersion, String vnfName, String requestType, String volumeGroupHeatStackId, + String baseVfHeatStackId, String vfModuleStackId, String modelCustomizationUuid, Map<String, Object> inputs, + MsoRequest msoRequest, Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback) + throws VnfException { + String vfModuleName = vnfName; + String vfModuleType = vnfType; + String methodName = "updateVfModule"; + String serviceName = VNF_ADAPTER_SERVICE_NAME + methodName; + + StringBuilder sbInit = new StringBuilder(); + sbInit.append("updateVfModule: \n"); + sbInit.append("cloudOwner=" + cloudOwner + "\n"); sbInit.append("cloudSiteId=" + cloudSiteId + "\n"); - sbInit.append("tenantId=" + tenantId + "\n"); - sbInit.append("vnfType=" + vnfType + "\n"); - sbInit.append("vnfVersion=" + vnfVersion + "\n"); - sbInit.append("vnfName=" + vnfName + "\n"); - sbInit.append("requestType=" + requestType + "\n"); - sbInit.append("volumeGroupHeatStackId=" + volumeGroupHeatStackId + "\n"); - sbInit.append("baseVfHeatStackId=" + baseVfHeatStackId + "\n"); - sbInit.append("vfModuleStackId=" + vfModuleStackId + "\n"); - sbInit.append("modelCustomizationUuid=" + modelCustomizationUuid + "\n"); - logger.debug(sbInit.toString()); + sbInit.append("tenantId=" + tenantId + "\n"); + sbInit.append("vnfType=" + vnfType + "\n"); + sbInit.append("vnfVersion=" + vnfVersion + "\n"); + sbInit.append("vnfName=" + vnfName + "\n"); + sbInit.append("requestType=" + requestType + "\n"); + sbInit.append("volumeGroupHeatStackId=" + volumeGroupHeatStackId + "\n"); + sbInit.append("baseVfHeatStackId=" + baseVfHeatStackId + "\n"); + sbInit.append("vfModuleStackId=" + vfModuleStackId + "\n"); + sbInit.append("modelCustomizationUuid=" + modelCustomizationUuid + "\n"); + logger.debug(sbInit.toString()); String mcu = modelCustomizationUuid; boolean useMCUuid = false; if (mcu != null && !mcu.isEmpty()) { if ("null".equalsIgnoreCase(mcu)) { logger.debug("modelCustomizationUuid: passed in as the string 'null' - will ignore: {}", - modelCustomizationUuid); + modelCustomizationUuid); useMCUuid = false; mcu = ""; } else { @@ -1485,47 +1411,50 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } } - String requestTypeString = ""; + String requestTypeString = ""; if (requestType != null && !"".equals(requestType)) { - requestTypeString = requestType; + requestTypeString = requestType; } String nestedStackId = null; - if (volumeGroupHeatStackId != null && !"".equals(volumeGroupHeatStackId) && !"null".equalsIgnoreCase(volumeGroupHeatStackId)) { - nestedStackId = volumeGroupHeatStackId; + if (volumeGroupHeatStackId != null && !"".equals(volumeGroupHeatStackId) + && !"null".equalsIgnoreCase(volumeGroupHeatStackId)) { + nestedStackId = volumeGroupHeatStackId; } String nestedBaseStackId = null; if (baseVfHeatStackId != null && !"".equals(baseVfHeatStackId) && !"null".equalsIgnoreCase(baseVfHeatStackId)) { - nestedBaseStackId = baseVfHeatStackId; + nestedBaseStackId = baseVfHeatStackId; } if (inputs == null) { - // Create an empty set of inputs - inputs = new HashMap<>(); + // Create an empty set of inputs + inputs = new HashMap<>(); logger.debug("inputs == null - setting to empty"); } boolean isBaseRequest = false; boolean isVolumeRequest = false; if (requestTypeString.startsWith("VOLUME")) { - isVolumeRequest = true; + isVolumeRequest = true; } if ((vfModuleName == null || "".equals(vfModuleName.trim())) && vfModuleStackId != null) { - vfModuleName = this.getVfModuleNameFromModuleStackId(vfModuleStackId); + vfModuleName = this.getVfModuleNameFromModuleStackId(vfModuleStackId); } - logger.debug ("Updating VFModule: " + vfModuleName + " of type " + vfModuleType + "in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId); - logger.debug("requestTypeString = " + requestTypeString + ", nestedVolumeStackId = " + nestedStackId + ", nestedBaseStackId = " + nestedBaseStackId); + logger.debug("Updating VFModule: " + vfModuleName + " of type " + vfModuleType + "in " + cloudOwner + "/" + + cloudSiteId + "/" + tenantId); + logger.debug("requestTypeString = " + requestTypeString + ", nestedVolumeStackId = " + nestedStackId + + ", nestedBaseStackId = " + nestedBaseStackId); // Will capture execution time for metrics - long startTime = System.currentTimeMillis (); + long startTime = System.currentTimeMillis(); // Build a default rollback object (no actions performed) - VnfRollback vfRollback = new VnfRollback (); - vfRollback.setCloudSiteId (cloudSiteId); - vfRollback.setCloudOwner (cloudOwner); - vfRollback.setTenantId (tenantId); - vfRollback.setMsoRequest (msoRequest); + VnfRollback vfRollback = new VnfRollback(); + vfRollback.setCloudSiteId(cloudSiteId); + vfRollback.setCloudOwner(cloudOwner); + vfRollback.setTenantId(tenantId); + vfRollback.setMsoRequest(msoRequest); vfRollback.setRequestType(requestTypeString); vfRollback.setVolumeGroupHeatStackId(volumeGroupHeatStackId); vfRollback.setBaseGroupHeatStackId(baseVfHeatStackId); @@ -1534,575 +1463,569 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { vfRollback.setModelCustomizationUuid(mcu); StackInfo heatStack = null; - long queryStackStarttime = System.currentTimeMillis (); + long queryStackStarttime = System.currentTimeMillis(); logger.debug("UpdateVfModule - querying for {}", vfModuleName); try { - heatStack = heat.queryStack (cloudSiteId, cloudOwner, tenantId, vfModuleName); + heatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, vfModuleName); } catch (MsoException me) { // Failed to query the Stack due to an openstack exception. // Convert to a generic VnfException - me.addContext ("UpdateVFModule"); - String error = "Update VFModule: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, cloudSiteId, - tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(), "Exception - QueryStack", - me); + me.addContext("UpdateVFModule"); + String error = "Update VFModule: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/" + + tenantId + ": " + me; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, + cloudOwner, cloudSiteId, tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(), + "Exception - QueryStack", me); logger.debug(error); - throw new VnfException (me); + throw new VnfException(me); } - //TODO - do we need to check for the other status possibilities? - if (heatStack == null || heatStack.getStatus () == HeatStatus.NOTFOUND) { + // TODO - do we need to check for the other status possibilities? + if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) { // Not Found - String error = "Update VF: Stack " + vfModuleName + " does not exist in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_NOT_EXIST.toString(), vfModuleName, cloudOwner, cloudSiteId, - tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(), error); - throw new VnfNotFound (cloudSiteId, cloudOwner, tenantId, vfModuleName); + String error = "Update VF: Stack " + vfModuleName + " does not exist in " + cloudOwner + "/" + cloudSiteId + + "/" + tenantId; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_NOT_EXIST.toString(), vfModuleName, + cloudOwner, cloudSiteId, tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(), + error); + throw new VnfNotFound(cloudSiteId, cloudOwner, tenantId, vfModuleName); } else { logger.debug("Found Existing stack, status={}", heatStack.getStatus()); // Populate the outputs from the existing stack. - outputs.value = copyStringOutputs (heatStack.getOutputs ()); + outputs.value = copyStringOutputs(heatStack.getOutputs()); rollback.value = vfRollback; // Default rollback - no updates performed } // 1604 Cinder Volume support - handle a nestedStackId if sent (volumeGroupHeatStackId): StackInfo nestedHeatStack = null; - long queryStackStarttime2 = System.currentTimeMillis (); + long queryStackStarttime2 = System.currentTimeMillis(); Map<String, Object> nestedVolumeOutputs = null; if (nestedStackId != null) { - try { - logger.debug("Querying for nestedStackId = {}", nestedStackId); - nestedHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedStackId); - } catch (MsoException me) { - // Failed to query the Stack due to an openstack exception. - // Convert to a generic VnfException - me.addContext ("UpdateVFModule"); - String error = "Update VF: Attached heatStack ID Query " + nestedStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId, - tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(), "Exception - " + error, - me); - logger.debug("ERROR trying to query nested stack= {}", error); - throw new VnfException (me); - } - if (nestedHeatStack == null || nestedHeatStack.getStatus() == HeatStatus.NOTFOUND) { - String error = "Update VFModule: Attached volume heatStack ID DOES NOT EXIST " + nestedStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR" ; - logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId, - tenantId, error, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(), error); - logger.debug(error); - throw new VnfException (error, MsoExceptionCategory.USERDATA); - } else { - logger.debug("Found nested heat stack - copying values to inputs *later*"); - nestedVolumeOutputs = nestedHeatStack.getOutputs(); - heat.copyStringOutputsToInputs(inputs, nestedHeatStack.getOutputs(), false); - } + try { + logger.debug("Querying for nestedStackId = {}", nestedStackId); + nestedHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedStackId); + } catch (MsoException me) { + // Failed to query the Stack due to an openstack exception. + // Convert to a generic VnfException + me.addContext("UpdateVFModule"); + String error = "Update VF: Attached heatStack ID Query " + nestedStackId + " in " + cloudOwner + "/" + + cloudSiteId + "/" + tenantId + ": " + me; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, + cloudSiteId, tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(), + "Exception - " + error, me); + logger.debug("ERROR trying to query nested stack= {}", error); + throw new VnfException(me); + } + if (nestedHeatStack == null || nestedHeatStack.getStatus() == HeatStatus.NOTFOUND) { + String error = "Update VFModule: Attached volume heatStack ID DOES NOT EXIST " + nestedStackId + " in " + + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR"; + logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, + cloudOwner, cloudSiteId, tenantId, error, "OpenStack", "QueryStack", + ErrorCode.DataError.getValue(), error); + logger.debug(error); + throw new VnfException(error, MsoExceptionCategory.USERDATA); + } else { + logger.debug("Found nested heat stack - copying values to inputs *later*"); + nestedVolumeOutputs = nestedHeatStack.getOutputs(); + heat.copyStringOutputsToInputs(inputs, nestedHeatStack.getOutputs(), false); + } } // handle a nestedBaseStackId if sent - this is the stack ID of the base. StackInfo nestedBaseHeatStack = null; Map<String, Object> baseStackOutputs = null; if (nestedBaseStackId != null) { - long queryStackStarttime3 = System.currentTimeMillis (); - try { - logger.debug("Querying for nestedBaseStackId = {}", nestedBaseStackId); - nestedBaseHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedBaseStackId); - } catch (MsoException me) { - // Failed to query the Stack due to an openstack exception. - // Convert to a generic VnfException - me.addContext ("UpdateVfModule"); - String error = "Update VFModule: Attached baseHeatStack ID Query " + nestedBaseStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ; - logger - .error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, cloudSiteId, - tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(), - "Exception - " + error, me); - logger.debug("ERROR trying to query nested base stack= {}", error); - throw new VnfException (me); - } - if (nestedBaseHeatStack == null || nestedBaseHeatStack.getStatus() == HeatStatus.NOTFOUND) { - String error = "Update VFModule: Attached base heatStack ID DOES NOT EXIST " + nestedBaseStackId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR" ; - logger.error ("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, error, "OpenStack", - "QueryStack", ErrorCode.DataError.getValue(), error); - logger.debug(error); - throw new VnfException (error, MsoExceptionCategory.USERDATA); - } else { - logger.debug("Found nested base heat stack - copying values to inputs *later*"); - baseStackOutputs = nestedBaseHeatStack.getOutputs(); - heat.copyStringOutputsToInputs(inputs, nestedBaseHeatStack.getOutputs(), false); - } + long queryStackStarttime3 = System.currentTimeMillis(); + try { + logger.debug("Querying for nestedBaseStackId = {}", nestedBaseStackId); + nestedBaseHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedBaseStackId); + } catch (MsoException me) { + // Failed to query the Stack due to an openstack exception. + // Convert to a generic VnfException + me.addContext("UpdateVfModule"); + String error = "Update VFModule: Attached baseHeatStack ID Query " + nestedBaseStackId + " in " + + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, + cloudOwner, cloudSiteId, tenantId, "OpenStack", "QueryStack", ErrorCode.DataError.getValue(), + "Exception - " + error, me); + logger.debug("ERROR trying to query nested base stack= {}", error); + throw new VnfException(me); + } + if (nestedBaseHeatStack == null || nestedBaseHeatStack.getStatus() == HeatStatus.NOTFOUND) { + String error = "Update VFModule: Attached base heatStack ID DOES NOT EXIST " + nestedBaseStackId + + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR"; + logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, + cloudOwner, cloudSiteId, tenantId, error, "OpenStack", "QueryStack", + ErrorCode.DataError.getValue(), error); + logger.debug(error); + throw new VnfException(error, MsoExceptionCategory.USERDATA); + } else { + logger.debug("Found nested base heat stack - copying values to inputs *later*"); + baseStackOutputs = nestedBaseHeatStack.getOutputs(); + heat.copyStringOutputsToInputs(inputs, nestedBaseHeatStack.getOutputs(), false); + } } // Ready to deploy the new VNF - // Retrieve the VF definition - VnfResource vnfResource = null; - VfModule vf = null; - VfModuleCustomization vfmc = null; - if (useMCUuid){ - vfmc = vfModuleCustomRepo.findFirstByModelCustomizationUUIDOrderByCreatedDesc(modelCustomizationUuid); - vf = vfmc != null ? vfmc.getVfModule() : null; - if (vf == null) { - logger.debug("Unable to find a vfModule matching modelCustomizationUuid={}", mcu); - } - } else { - logger.debug("1707 and later - MUST PROVIDE Model Customization UUID!"); - } - if (vf == null) { - String error = "Update VfModule: unable to find vfModule with modelCustomizationUuid=" + mcu; - logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VF Module Type", - vfModuleType, "OpenStack", ErrorCode.DataError.getValue(), error); - throw new VnfException(error, MsoExceptionCategory.USERDATA); - } - logger.debug("Got VF module definition from Catalog: {}", vf.toString()); - if (vf.getIsBase()) { - isBaseRequest = true; - logger.debug("This a BASE update request"); - } else { - logger.debug("This is *not* a BASE VF update request"); - if (!isVolumeRequest && nestedBaseStackId == null) { - logger.debug("DANGER WILL ROBINSON! This is unexpected - no nestedBaseStackId with this non-base request"); - } + // Retrieve the VF definition + VnfResource vnfResource = null; + VfModule vf = null; + VfModuleCustomization vfmc = null; + if (useMCUuid) { + vfmc = vfModuleCustomRepo.findFirstByModelCustomizationUUIDOrderByCreatedDesc(modelCustomizationUuid); + vf = vfmc != null ? vfmc.getVfModule() : null; + if (vf == null) { + logger.debug("Unable to find a vfModule matching modelCustomizationUuid={}", mcu); + } + } else { + logger.debug("1707 and later - MUST PROVIDE Model Customization UUID!"); + } + if (vf == null) { + String error = "Update VfModule: unable to find vfModule with modelCustomizationUuid=" + mcu; + logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VF Module Type", + vfModuleType, "OpenStack", ErrorCode.DataError.getValue(), error); + throw new VnfException(error, MsoExceptionCategory.USERDATA); + } + logger.debug("Got VF module definition from Catalog: {}", vf.toString()); + if (vf.getIsBase()) { + isBaseRequest = true; + logger.debug("This a BASE update request"); + } else { + logger.debug("This is *not* a BASE VF update request"); + if (!isVolumeRequest && nestedBaseStackId == null) { + logger.debug( + "DANGER WILL ROBINSON! This is unexpected - no nestedBaseStackId with this non-base request"); } + } - //1607 - Add version check - // First - see if it's in the VnfResource record - // if we have a vf Module - then we have to query to get the VnfResource record. - if (vf.getModelUUID() != null) { - String vnfResourceModelUuid = vf.getModelUUID(); + // 1607 - Add version check + // First - see if it's in the VnfResource record + // if we have a vf Module - then we have to query to get the VnfResource record. + if (vf.getModelUUID() != null) { + String vnfResourceModelUuid = vf.getModelUUID(); - vnfResource = vf.getVnfResources(); - if (vnfResource == null) { - logger.debug("Unable to find vnfResource at ? will not error for now...", vnfResourceModelUuid); - } + vnfResource = vf.getVnfResources(); + if (vnfResource == null) { + logger.debug("Unable to find vnfResource at ? will not error for now...", vnfResourceModelUuid); } + } - String minVersionVnf = null; - String maxVersionVnf = null; - if (vnfResource != null) { - try { - minVersionVnf = vnfResource.getAicVersionMin(); - maxVersionVnf = vnfResource.getAicVersionMax(); - } catch (Exception e) { - logger.debug("Unable to pull min/max version for this VNF Resource entry",e); - minVersionVnf = null; - maxVersionVnf = null; - } - if (minVersionVnf != null && "".equals(minVersionVnf)) { - minVersionVnf = null; - } - if (maxVersionVnf != null && "".equals(maxVersionVnf)) { - maxVersionVnf = null; - } - } - if (minVersionVnf != null && maxVersionVnf != null) { - MavenLikeVersioning aicV = new MavenLikeVersioning(); - - // double check - if (this.cloudConfig != null) { - Optional<CloudSite> cloudSiteOpt = this.cloudConfig.getCloudSite(cloudSiteId); - if (cloudSiteOpt.isPresent()) { - aicV.setVersion(cloudSiteOpt.get().getCloudVersion()); - boolean moreThanMin = true; - boolean equalToMin = true; - boolean moreThanMax = true; - boolean equalToMax = true; - boolean doNotTest = false; - try { - moreThanMin = aicV.isMoreRecentThan(minVersionVnf); - equalToMin = aicV.isTheSameVersion(minVersionVnf); - moreThanMax = aicV.isMoreRecentThan(maxVersionVnf); - equalToMax = aicV.isTheSameVersion(maxVersionVnf); - } catch (Exception e) { - logger.debug("An exception occured while trying to test AIC Version {} - will default to not check", - e.getMessage(), e); - doNotTest = true; - } - if (!doNotTest) { - if ((moreThanMin || equalToMin) // aic >= min - && ((equalToMax) || !(moreThanMax))) { // aic <= max - logger.debug( - "VNF Resource " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + " VersionMax:" - + maxVersionVnf + " supported on Cloud: " + cloudSiteId + " with AIC_Version:" + aicV); + String minVersionVnf = null; + String maxVersionVnf = null; + if (vnfResource != null) { + try { + minVersionVnf = vnfResource.getAicVersionMin(); + maxVersionVnf = vnfResource.getAicVersionMax(); + } catch (Exception e) { + logger.debug("Unable to pull min/max version for this VNF Resource entry", e); + minVersionVnf = null; + maxVersionVnf = null; + } + if (minVersionVnf != null && "".equals(minVersionVnf)) { + minVersionVnf = null; + } + if (maxVersionVnf != null && "".equals(maxVersionVnf)) { + maxVersionVnf = null; + } + } + if (minVersionVnf != null && maxVersionVnf != null) { + MavenLikeVersioning aicV = new MavenLikeVersioning(); + + // double check + if (this.cloudConfig != null) { + Optional<CloudSite> cloudSiteOpt = this.cloudConfig.getCloudSite(cloudSiteId); + if (cloudSiteOpt.isPresent()) { + aicV.setVersion(cloudSiteOpt.get().getCloudVersion()); + boolean moreThanMin = true; + boolean equalToMin = true; + boolean moreThanMax = true; + boolean equalToMax = true; + boolean doNotTest = false; + try { + moreThanMin = aicV.isMoreRecentThan(minVersionVnf); + equalToMin = aicV.isTheSameVersion(minVersionVnf); + moreThanMax = aicV.isMoreRecentThan(maxVersionVnf); + equalToMax = aicV.isTheSameVersion(maxVersionVnf); + } catch (Exception e) { + logger.debug( + "An exception occured while trying to test AIC Version {} - will default to not check", + e.getMessage(), e); + doNotTest = true; + } + if (!doNotTest) { + if ((moreThanMin || equalToMin) // aic >= min + && ((equalToMax) || !(moreThanMax))) { // aic <= max + logger.debug("VNF Resource " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + + " VersionMax:" + maxVersionVnf + " supported on Cloud: " + cloudSiteId + + " with AIC_Version:" + aicV); + } else { + // ERROR + String error = "VNF Resource type: " + vnfResource.getModelName() + " VersionMin=" + + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " + + cloudSiteId + " with AIC_Version:" + aicV; + logger.error("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, "OpenStack", + ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion"); + logger.debug(error); + throw new VnfException(error, MsoExceptionCategory.USERDATA); + } + } else { + logger.debug("bypassing testing AIC version..."); + } + } // let this error out downstream to avoid introducing uncertainty at this stage } else { - // ERROR - String error = "VNF Resource type: " + vnfResource.getModelName() + " VersionMin=" - + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " - + cloudSiteId + " with AIC_Version:" + aicV; - logger.error("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, "OpenStack", - ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion"); - logger.debug(error); - throw new VnfException(error, MsoExceptionCategory.USERDATA); - } - } else { - logger.debug("bypassing testing AIC version..."); - } - } // let this error out downstream to avoid introducing uncertainty at this stage - } else { - logger.debug("cloudConfig is NULL - cannot check cloud site version"); - } - - } else { - logger.debug("AIC Version not set in VNF_Resource - do not error for now - not checked."); + logger.debug("cloudConfig is NULL - cannot check cloud site version"); } - // End Version check 1607 - HeatTemplate heatTemplate = null; - HeatEnvironment heatEnvironment = null; - if (isVolumeRequest) { - heatTemplate = vf.getVolumeHeatTemplate(); - heatEnvironment = vfmc.getVolumeHeatEnv(); - } else { - heatTemplate = vf.getModuleHeatTemplate(); - heatEnvironment = vfmc.getHeatEnvironment(); - } - - if (heatTemplate == null) { - String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType + ", reqType=" + requestTypeString; - logger - .error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", vfModuleType, - "OpenStack", ErrorCode.DataError.getValue(), error); - throw new VnfException(error, MsoExceptionCategory.INTERNAL); - } else { - logger.debug("Got HEAT Template from DB: {}", heatTemplate.getHeatTemplate()); - } - - if (heatEnvironment == null) { - String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType; - logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID", + } else { + logger.debug("AIC Version not set in VNF_Resource - do not error for now - not checked."); + } + // End Version check 1607 + + HeatTemplate heatTemplate = null; + HeatEnvironment heatEnvironment = null; + if (isVolumeRequest) { + heatTemplate = vf.getVolumeHeatTemplate(); + heatEnvironment = vfmc.getVolumeHeatEnv(); + } else { + heatTemplate = vf.getModuleHeatTemplate(); + heatEnvironment = vfmc.getHeatEnvironment(); + } + + if (heatTemplate == null) { + String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType + + ", reqType=" + requestTypeString; + logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", + vfModuleType, "OpenStack", ErrorCode.DataError.getValue(), error); + throw new VnfException(error, MsoExceptionCategory.INTERNAL); + } else { + logger.debug("Got HEAT Template from DB: {}", heatTemplate.getHeatTemplate()); + } + + if (heatEnvironment == null) { + String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType; + logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID", "OpenStack", ErrorCode.DataError.getValue(), error); - throw new VnfException (error, MsoExceptionCategory.INTERNAL); - } else { - logger.debug ("Got Heat Environment from DB: {}", heatEnvironment.getEnvironment()); - } + throw new VnfException(error, MsoExceptionCategory.INTERNAL); + } else { + logger.debug("Got Heat Environment from DB: {}", heatEnvironment.getEnvironment()); + } logger.debug("In MsoVnfAdapterImpl, about to call db.getNestedTemplates avec templateId={}", - heatTemplate.getArtifactUuid()); + heatTemplate.getArtifactUuid()); - List<HeatTemplate> nestedTemplates = heatTemplate.getChildTemplates(); - Map <String, Object> nestedTemplatesChecked = new HashMap <> (); - if (nestedTemplates != null && !nestedTemplates.isEmpty()) { - // for debugging print them out - logger.debug("Contents of nestedTemplates - to be added to files: on stack:"); - for (HeatTemplate entry : nestedTemplates) { + List<HeatTemplate> nestedTemplates = heatTemplate.getChildTemplates(); + Map<String, Object> nestedTemplatesChecked = new HashMap<>(); + if (nestedTemplates != null && !nestedTemplates.isEmpty()) { + // for debugging print them out + logger.debug("Contents of nestedTemplates - to be added to files: on stack:"); + for (HeatTemplate entry : nestedTemplates) { - nestedTemplatesChecked.put (entry.getTemplateName(), entry.getTemplateBody()); - logger.debug(entry.getTemplateName() + " -> " + entry.getTemplateBody()); - } - } else { - logger.debug("No nested templates found - nothing to do here"); - nestedTemplatesChecked = null; + nestedTemplatesChecked.put(entry.getTemplateName(), entry.getTemplateBody()); + logger.debug(entry.getTemplateName() + " -> " + entry.getTemplateBody()); } + } else { + logger.debug("No nested templates found - nothing to do here"); + nestedTemplatesChecked = null; + } - // Also add the files: for any get_files associated with this VfModule - // *if* there are any - logger.debug("In MsoVnfAdapterImpl.updateVfModule, about to call db.getHeatFiles avec vfModuleId={}", - vf.getModelUUID()); + // Also add the files: for any get_files associated with this VfModule + // *if* there are any + logger.debug("In MsoVnfAdapterImpl.updateVfModule, about to call db.getHeatFiles avec vfModuleId={}", + vf.getModelUUID()); - List<HeatFiles> heatFiles = null; - Map <String, Object> heatFilesObjects = new HashMap <> (); + List<HeatFiles> heatFiles = null; + Map<String, Object> heatFilesObjects = new HashMap<>(); - // Add ability to turn on adding get_files with volume requests (by property). - boolean addGetFilesOnVolumeReq = false; - try { - String propertyString = this.environment.getProperty(MsoVnfAdapterImpl.ADD_GET_FILES_ON_VOLUME_REQ); - if ("true".equalsIgnoreCase(propertyString) || "y".equalsIgnoreCase(propertyString)) { - addGetFilesOnVolumeReq = true; - logger.debug("AddGetFilesOnVolumeReq - setting to true! {}", propertyString); - } - } catch (Exception e) { - logger.debug("An error occured trying to get property {} - default to false", - MsoVnfAdapterImpl.ADD_GET_FILES_ON_VOLUME_REQ, e); + // Add ability to turn on adding get_files with volume requests (by property). + boolean addGetFilesOnVolumeReq = false; + try { + String propertyString = this.environment.getProperty(MsoVnfAdapterImpl.ADD_GET_FILES_ON_VOLUME_REQ); + if ("true".equalsIgnoreCase(propertyString) || "y".equalsIgnoreCase(propertyString)) { + addGetFilesOnVolumeReq = true; + logger.debug("AddGetFilesOnVolumeReq - setting to true! {}", propertyString); } - if (!isVolumeRequest || addGetFilesOnVolumeReq) { + } catch (Exception e) { + logger.debug("An error occured trying to get property {} - default to false", + MsoVnfAdapterImpl.ADD_GET_FILES_ON_VOLUME_REQ, e); + } + if (!isVolumeRequest || addGetFilesOnVolumeReq) { logger.debug("In MsoVnfAdapterImpl updateVfModule, about to call db.getHeatFilesForVfModule avec " - + "vfModuleId={}", vf.getModelUUID()); - - heatFiles = vf.getHeatFiles(); - if (heatFiles != null && !heatFiles.isEmpty()) { - // add these to stack - to be done in createStack - // here, we will map them to Map<String, Object> from Map<String, HeatFiles> - // this will match the nested templates format - logger.debug("Contents of heatFiles - to be added to files: on stack:"); - for (HeatFiles heatfile : heatFiles) { - logger.debug(heatfile.getFileName() + " -> " + heatfile.getFileBody()); - heatFilesObjects.put(heatfile.getFileName(), heatfile.getFileBody()); - } - } else { - logger.debug("No heat files found -nothing to do here"); - heatFilesObjects = null; + + "vfModuleId={}", vf.getModelUUID()); + + heatFiles = vf.getHeatFiles(); + if (heatFiles != null && !heatFiles.isEmpty()) { + // add these to stack - to be done in createStack + // here, we will map them to Map<String, Object> from Map<String, HeatFiles> + // this will match the nested templates format + logger.debug("Contents of heatFiles - to be added to files: on stack:"); + for (HeatFiles heatfile : heatFiles) { + logger.debug(heatfile.getFileName() + " -> " + heatfile.getFileBody()); + heatFilesObjects.put(heatfile.getFileName(), heatfile.getFileBody()); } + } else { + logger.debug("No heat files found -nothing to do here"); + heatFilesObjects = null; } + } - // Check that required parameters have been supplied - String missingParams = null; - List <String> paramList = new ArrayList <> (); + // Check that required parameters have been supplied + String missingParams = null; + List<String> paramList = new ArrayList<>(); - // New for 1510 - consult the PARAM_ALIAS field to see if we've been - // supplied an alias. Only check if we don't find it initially. - // Also new in 1510 - don't flag missing parameters if there's an environment - because they might be there. - // And also new - add parameter to turn off checking all together if we find we're blocking orders we - // shouldn't - boolean checkRequiredParameters = true; - try { - String propertyString = this.environment.getProperty (MsoVnfAdapterImpl.CHECK_REQD_PARAMS); - if ("false".equalsIgnoreCase (propertyString) || "n".equalsIgnoreCase (propertyString)) { - checkRequiredParameters = false; - logger.debug("CheckRequiredParameters is FALSE. Will still check but then skip blocking...", + // New for 1510 - consult the PARAM_ALIAS field to see if we've been + // supplied an alias. Only check if we don't find it initially. + // Also new in 1510 - don't flag missing parameters if there's an environment - because they might be there. + // And also new - add parameter to turn off checking all together if we find we're blocking orders we + // shouldn't + boolean checkRequiredParameters = true; + try { + String propertyString = this.environment.getProperty(MsoVnfAdapterImpl.CHECK_REQD_PARAMS); + if ("false".equalsIgnoreCase(propertyString) || "n".equalsIgnoreCase(propertyString)) { + checkRequiredParameters = false; + logger.debug("CheckRequiredParameters is FALSE. Will still check but then skip blocking...", MsoVnfAdapterImpl.CHECK_REQD_PARAMS); - } - } catch (Exception e) { - // No problem - default is true - logger.debug ("An exception occured trying to get property {}", MsoVnfAdapterImpl.CHECK_REQD_PARAMS, - e); } - // 1604 - Add enhanced environment & parameter checking - // Part 1: parse envt entries to see if reqd parameter is there (before used a simple grep - // Part 2: only submit to openstack the parameters in the envt that are in the heat template - // Note this also removes any comments - MsoHeatEnvironmentEntry mhee = null; - if (heatEnvironment != null && heatEnvironment.getEnvironment().toLowerCase ().contains ("parameters:")) { - logger.debug("Enhanced environment checking enabled - 1604"); - StringBuilder sb = new StringBuilder(heatEnvironment.getEnvironment()); - mhee = new MsoHeatEnvironmentEntry(sb); - StringBuilder sb2 = new StringBuilder("\nHeat Template Parameters:\n"); - for (HeatTemplateParam parm : heatTemplate.getParameters()) { - sb2.append("\t" + parm.getParamName() + ", required=" + parm.isRequired()); - } - if (!mhee.isValid()) { - sb2.append("Environment says it's not valid! " + mhee.getErrorString()); - } else { - sb2.append("\nEnvironment:"); - sb2.append(mhee.toFullString()); - } - logger.debug(sb2.toString()); + } catch (Exception e) { + // No problem - default is true + logger.debug("An exception occured trying to get property {}", MsoVnfAdapterImpl.CHECK_REQD_PARAMS, e); + } + // 1604 - Add enhanced environment & parameter checking + // Part 1: parse envt entries to see if reqd parameter is there (before used a simple grep + // Part 2: only submit to openstack the parameters in the envt that are in the heat template + // Note this also removes any comments + MsoHeatEnvironmentEntry mhee = null; + if (heatEnvironment != null && heatEnvironment.getEnvironment().toLowerCase().contains("parameters:")) { + logger.debug("Enhanced environment checking enabled - 1604"); + StringBuilder sb = new StringBuilder(heatEnvironment.getEnvironment()); + mhee = new MsoHeatEnvironmentEntry(sb); + StringBuilder sb2 = new StringBuilder("\nHeat Template Parameters:\n"); + for (HeatTemplateParam parm : heatTemplate.getParameters()) { + sb2.append("\t" + parm.getParamName() + ", required=" + parm.isRequired()); + } + if (!mhee.isValid()) { + sb2.append("Environment says it's not valid! " + mhee.getErrorString()); } else { - logger.debug("NO ENVIRONMENT for this entry"); - } - // New for 1607 - support params of json type - HashMap<String, JsonNode> jsonParams = new HashMap<>(); - boolean hasJson = false; - - for (HeatTemplateParam parm : heatTemplate.getParameters ()) { - logger.debug ("Parameter:'" + parm.getParamName () - + "', isRequired=" - + parm.isRequired () - + ", alias=" - + parm.getParamAlias ()); - // handle json - String parameterType = parm.getParamType(); - if (parameterType == null || "".equals(parameterType.trim())) { - parameterType = "String"; - } - JsonNode jsonNode = null; - if ("json".equalsIgnoreCase(parameterType) && inputs != null) { - if (inputs.containsKey(parm.getParamName()) ) { - hasJson = true; - String jsonString = null; - try { - jsonString = JSON_MAPPER.writeValueAsString(inputs.get(parm.getParamName())); - jsonNode = JSON_MAPPER.readTree(jsonString); - } catch (JsonParseException jpe) { - //TODO - what to do here? - //for now - send the error to debug - logger.debug("Json Error Converting {} - {}", parm.getParamName(), jpe.getMessage(), jpe); - hasJson = false; - jsonNode = null; - } catch (Exception e) { + sb2.append("\nEnvironment:"); + sb2.append(mhee.toFullString()); + } + logger.debug(sb2.toString()); + } else { + logger.debug("NO ENVIRONMENT for this entry"); + } + // New for 1607 - support params of json type + HashMap<String, JsonNode> jsonParams = new HashMap<>(); + boolean hasJson = false; + + for (HeatTemplateParam parm : heatTemplate.getParameters()) { + logger.debug("Parameter:'" + parm.getParamName() + "', isRequired=" + parm.isRequired() + ", alias=" + + parm.getParamAlias()); + // handle json + String parameterType = parm.getParamType(); + if (parameterType == null || "".equals(parameterType.trim())) { + parameterType = "String"; + } + JsonNode jsonNode = null; + if ("json".equalsIgnoreCase(parameterType) && inputs != null) { + if (inputs.containsKey(parm.getParamName())) { + hasJson = true; + String jsonString = null; + try { + jsonString = JSON_MAPPER.writeValueAsString(inputs.get(parm.getParamName())); + jsonNode = JSON_MAPPER.readTree(jsonString); + } catch (JsonParseException jpe) { + // TODO - what to do here? + // for now - send the error to debug + logger.debug("Json Error Converting {} - {}", parm.getParamName(), jpe.getMessage(), jpe); + hasJson = false; + jsonNode = null; + } catch (Exception e) { // or here? logger.debug("Json Error Converting {} {}", parm.getParamName(), e.getMessage(), e); hasJson = false; jsonNode = null; } - if (jsonNode != null) { - jsonParams.put(parm.getParamName(), jsonNode); - } - } else if (inputs.containsKey(parm.getParamAlias())) { - hasJson = true; - String jsonString = null; - try { - jsonString = (String)inputs.get(parm.getParamAlias()); - jsonNode = JSON_MAPPER.readTree(jsonString); - } catch (JsonParseException jpe) { - //TODO - what to do here? - //for now - send the error to debug, but just leave it as a String - String errorMessage = jpe.getMessage(); - logger.debug("Json Error Converting " + parm.getParamName() + " - " + errorMessage,jpe); - hasJson = false; - jsonNode = null; - } catch (Exception e) { - // or here? - logger.debug("Json Error Converting " + parm.getParamName() + " " + e.getMessage(), e); - hasJson = false; - jsonNode = null; - } - if (jsonNode != null) { - // Notice here - we add it to the jsonParams hashMap with the actual name - - // then manipulate the inputs so when we check for aliases below - it will not - // get flagged. - jsonParams.put(parm.getParamName(), jsonNode); - inputs.remove(parm.getParamAlias()); - inputs.put(parm.getParamName(), jsonString); - } - } //TODO add a check for the parameter in the env file - } - - if (parm.isRequired () && (inputs == null || !inputs.containsKey (parm.getParamName ()))) { - if (inputs.containsKey (parm.getParamAlias ())) { - // They've submitted using an alias name. Remove that from inputs, and add back using real name. - String realParamName = parm.getParamName (); - String alias = parm.getParamAlias (); - Object value = inputs.get (alias); - logger.debug ("*Found an Alias: paramName=" + realParamName - + ",alias=" - + alias - + ",value=" - + value); - inputs.remove (alias); - inputs.put (realParamName, value); - logger.debug ("{} entry removed from inputs, added back using {}", alias, realParamName); + if (jsonNode != null) { + jsonParams.put(parm.getParamName(), jsonNode); + } + } else if (inputs.containsKey(parm.getParamAlias())) { + hasJson = true; + String jsonString = null; + try { + jsonString = (String) inputs.get(parm.getParamAlias()); + jsonNode = JSON_MAPPER.readTree(jsonString); + } catch (JsonParseException jpe) { + // TODO - what to do here? + // for now - send the error to debug, but just leave it as a String + String errorMessage = jpe.getMessage(); + logger.debug("Json Error Converting " + parm.getParamName() + " - " + errorMessage, jpe); + hasJson = false; + jsonNode = null; + } catch (Exception e) { + // or here? + logger.debug("Json Error Converting " + parm.getParamName() + " " + e.getMessage(), e); + hasJson = false; + jsonNode = null; + } + if (jsonNode != null) { + // Notice here - we add it to the jsonParams hashMap with the actual name - + // then manipulate the inputs so when we check for aliases below - it will not + // get flagged. + jsonParams.put(parm.getParamName(), jsonNode); + inputs.remove(parm.getParamAlias()); + inputs.put(parm.getParamName(), jsonString); } - // enhanced - check if it's in the Environment (note: that method - else if (mhee != null && mhee.containsParameter(parm.getParamName())) { + } // TODO add a check for the parameter in the env file + } - logger.debug("Required parameter {} appears to be in environment - do not count as missing", + if (parm.isRequired() && (inputs == null || !inputs.containsKey(parm.getParamName()))) { + if (inputs.containsKey(parm.getParamAlias())) { + // They've submitted using an alias name. Remove that from inputs, and add back using real name. + String realParamName = parm.getParamName(); + String alias = parm.getParamAlias(); + Object value = inputs.get(alias); + logger.debug("*Found an Alias: paramName=" + realParamName + ",alias=" + alias + ",value=" + value); + inputs.remove(alias); + inputs.put(realParamName, value); + logger.debug("{} entry removed from inputs, added back using {}", alias, realParamName); + } + // enhanced - check if it's in the Environment (note: that method + else if (mhee != null && mhee.containsParameter(parm.getParamName())) { + + logger.debug("Required parameter {} appears to be in environment - do not count as missing", parm.getParamName()); - } - else { - logger.debug("adding to missing parameters list: {}", parm.getParamName()); - if (missingParams == null) { - missingParams = parm.getParamName (); - } else { - missingParams += "," + parm.getParamName (); - } + } else { + logger.debug("adding to missing parameters list: {}", parm.getParamName()); + if (missingParams == null) { + missingParams = parm.getParamName(); + } else { + missingParams += "," + parm.getParamName(); } } - paramList.add (parm.getParamName ()); } + paramList.add(parm.getParamName()); + } - if (missingParams != null) { - // Problem - missing one or more required parameters - if (checkRequiredParameters) { + if (missingParams != null) { + // Problem - missing one or more required parameters + if (checkRequiredParameters) { String error = "Update VNF: Missing Required inputs: " + missingParams; - logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, "OpenStack", - ErrorCode.DataError.getValue(), error); - throw new VnfException (error, MsoExceptionCategory.USERDATA); - } else { - logger.debug("found missing parameters - but checkRequiredParameters is false - will not block"); - } + logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, "OpenStack", + ErrorCode.DataError.getValue(), error); + throw new VnfException(error, MsoExceptionCategory.USERDATA); } else { - logger.debug("No missing parameters found - ok to proceed"); + logger.debug("found missing parameters - but checkRequiredParameters is false - will not block"); } + } else { + logger.debug("No missing parameters found - ok to proceed"); + } - // Just submit the envt entry as received from the database - String newEnvironmentString = null; - if (mhee != null) { - newEnvironmentString = mhee.getRawEntry().toString(); - } - // Remove any extraneous parameters (don't throw an error) - if (inputs != null) { - List <String> extraParams = new ArrayList <> (); - extraParams.addAll (inputs.keySet ()); - // This is not a valid parameter for this template - extraParams.removeAll (paramList); - if (!extraParams.isEmpty ()) { - logger.warn("{} {} {} {} {} {}", MessageEnum.RA_VNF_EXTRA_PARAM.toString(), vnfType, + // Just submit the envt entry as received from the database + String newEnvironmentString = null; + if (mhee != null) { + newEnvironmentString = mhee.getRawEntry().toString(); + } + // Remove any extraneous parameters (don't throw an error) + if (inputs != null) { + List<String> extraParams = new ArrayList<>(); + extraParams.addAll(inputs.keySet()); + // This is not a valid parameter for this template + extraParams.removeAll(paramList); + if (!extraParams.isEmpty()) { + logger.warn("{} {} {} {} {} {}", MessageEnum.RA_VNF_EXTRA_PARAM.toString(), vnfType, extraParams.toString(), "OpenStack", ErrorCode.DataError.getValue(), "Extra params"); - inputs.keySet ().removeAll (extraParams); - } + inputs.keySet().removeAll(extraParams); } - Map<String, Object> goldenInputs = copyStringInputs(inputs); - // 1607 - when we get here - we have clean inputs. Create inputsTwo in case we have json - Map<String, Object> inputsTwo = null; - if (hasJson && jsonParams.size() > 0) { - inputsTwo = new HashMap<>(); - for (Map.Entry<String, Object> entry : inputs.entrySet()) { - String keyParamName = entry.getKey(); - Object value = entry.getValue(); - if (jsonParams.containsKey(keyParamName)) { - inputsTwo.put(keyParamName, jsonParams.get(keyParamName)); - } else { - inputsTwo.put(keyParamName, value); - } - } - goldenInputs = inputsTwo; + } + Map<String, Object> goldenInputs = copyStringInputs(inputs); + // 1607 - when we get here - we have clean inputs. Create inputsTwo in case we have json + Map<String, Object> inputsTwo = null; + if (hasJson && jsonParams.size() > 0) { + inputsTwo = new HashMap<>(); + for (Map.Entry<String, Object> entry : inputs.entrySet()) { + String keyParamName = entry.getKey(); + Object value = entry.getValue(); + if (jsonParams.containsKey(keyParamName)) { + inputsTwo.put(keyParamName, jsonParams.get(keyParamName)); + } else { + inputsTwo.put(keyParamName, value); + } } + goldenInputs = inputsTwo; + } - // "Fix" the template if it has CR/LF (getting this from Oracle) - String template = heatTemplate.getHeatTemplate (); - template = template.replaceAll ("\r\n", "\n"); + // "Fix" the template if it has CR/LF (getting this from Oracle) + String template = heatTemplate.getHeatTemplate(); + template = template.replaceAll("\r\n", "\n"); - boolean isValetEnabled = this.checkBooleanProperty(MsoVnfAdapterImpl.VALET_ENABLED, false); - boolean failRequestOnValetFailure = this.checkBooleanProperty(MsoVnfAdapterImpl.FAIL_REQUESTS_ON_VALET_FAILURE, false); - logger.debug("isValetEnabled={}, failRequestsOnValetFailure={}", isValetEnabled, failRequestOnValetFailure); - if (isVolumeRequest) { - isValetEnabled = false; - logger.debug("never send a volume request to valet"); + boolean isValetEnabled = this.checkBooleanProperty(MsoVnfAdapterImpl.VALET_ENABLED, false); + boolean failRequestOnValetFailure = + this.checkBooleanProperty(MsoVnfAdapterImpl.FAIL_REQUESTS_ON_VALET_FAILURE, false); + logger.debug("isValetEnabled={}, failRequestsOnValetFailure={}", isValetEnabled, failRequestOnValetFailure); + if (isVolumeRequest) { + isValetEnabled = false; + logger.debug("never send a volume request to valet"); + } + boolean sendResponseToValet = false; + if (isValetEnabled) { + Holder<Map<String, Object>> valetModifiedParamsHolder = new Holder<>(); + String parsedVfModuleName = this.getVfModuleNameFromModuleStackId(vfModuleStackId); + // Make sure it is set to something. + if (parsedVfModuleName == null || parsedVfModuleName.isEmpty()) { + parsedVfModuleName = "unknown"; } - boolean sendResponseToValet = false; - if (isValetEnabled) { - Holder<Map<String, Object>> valetModifiedParamsHolder = new Holder<>(); - String parsedVfModuleName = this.getVfModuleNameFromModuleStackId(vfModuleStackId); - // Make sure it is set to something. - if (parsedVfModuleName == null || parsedVfModuleName.isEmpty()) { - parsedVfModuleName = "unknown"; - } - sendResponseToValet = this.valetUpdateRequest(cloudSiteId, cloudOwner, tenantId, heatFilesObjects, - nestedTemplatesChecked, parsedVfModuleName, false, heatTemplate, newEnvironmentString, (HashMap<String, Object>) goldenInputs, - msoRequest, inputs, failRequestOnValetFailure, valetModifiedParamsHolder); - if (sendResponseToValet) { - goldenInputs = valetModifiedParamsHolder.value; - } + sendResponseToValet = this.valetUpdateRequest(cloudSiteId, cloudOwner, tenantId, heatFilesObjects, + nestedTemplatesChecked, parsedVfModuleName, false, heatTemplate, newEnvironmentString, + (HashMap<String, Object>) goldenInputs, msoRequest, inputs, failRequestOnValetFailure, + valetModifiedParamsHolder); + if (sendResponseToValet) { + goldenInputs = valetModifiedParamsHolder.value; } + } - // Have the tenant. Now deploy the stack itself - // Ignore MsoTenantNotFound and MsoStackAlreadyExists exceptions - // because we already checked for those. - long updateStackStarttime = System.currentTimeMillis (); - try { - heatStack = heatU.updateStack( - cloudSiteId, - cloudOwner, - tenantId, - vfModuleName, - template, - goldenInputs, - true, - heatTemplate.getTimeoutMinutes(), - newEnvironmentString, - //heatEnvironmentString, - nestedTemplatesChecked, - heatFilesObjects - ); - } catch (MsoException me) { - me.addContext ("UpdateVFModule"); - String error = "Update VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger - .error("{} {} {} {} {} {} {} {}", MessageEnum.RA_UPDATE_VNF_ERR.toString(), vfModuleType, cloudOwner, cloudSiteId, - tenantId, "OpenStack", ErrorCode.DataError.getValue(), "Exception - " + error, me); - if (isValetEnabled && sendResponseToValet) { - logger.debug("valet is enabled, the orchestration failed - now sending rollback to valet"); - try { - GenericValetResponse<ValetRollbackResponse> gvr = this.vci.callValetRollbackRequest(msoRequest.getRequestId(), null, false, me.getMessage()); - // Nothing to really do here whether it succeeded or not other than log it. - logger.debug("Return code from Rollback response is {}", gvr.getStatusCode()); - } catch (Exception e) { - logger.error("Exception encountered while sending Rollback to Valet ", e); - } + // Have the tenant. Now deploy the stack itself + // Ignore MsoTenantNotFound and MsoStackAlreadyExists exceptions + // because we already checked for those. + long updateStackStarttime = System.currentTimeMillis(); + try { + heatStack = heatU.updateStack(cloudSiteId, cloudOwner, tenantId, vfModuleName, template, goldenInputs, true, + heatTemplate.getTimeoutMinutes(), newEnvironmentString, + // heatEnvironmentString, + nestedTemplatesChecked, heatFilesObjects); + } catch (MsoException me) { + me.addContext("UpdateVFModule"); + String error = "Update VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + + ": " + me; + logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_UPDATE_VNF_ERR.toString(), vfModuleType, cloudOwner, + cloudSiteId, tenantId, "OpenStack", ErrorCode.DataError.getValue(), "Exception - " + error, me); + if (isValetEnabled && sendResponseToValet) { + logger.debug("valet is enabled, the orchestration failed - now sending rollback to valet"); + try { + GenericValetResponse<ValetRollbackResponse> gvr = + this.vci.callValetRollbackRequest(msoRequest.getRequestId(), null, false, me.getMessage()); + // Nothing to really do here whether it succeeded or not other than log it. + logger.debug("Return code from Rollback response is {}", gvr.getStatusCode()); + } catch (Exception e) { + logger.error("Exception encountered while sending Rollback to Valet ", e); } - throw new VnfException (me); } + throw new VnfException(me); + } // Reach this point if updateStack is successful. // Populate remaining rollback info and response parameters. - vfRollback.setVnfId (heatStack.getCanonicalName ()); - vfRollback.setVnfCreated (true); + vfRollback.setVnfId(heatStack.getCanonicalName()); + vfRollback.setVnfCreated(true); if (isValetEnabled && sendResponseToValet) { - logger.debug("valet is enabled, the update succeeded - now send confirm to valet with stack id"); - try { - GenericValetResponse<ValetConfirmResponse> gvr = this.vci.callValetConfirmRequest(msoRequest.getRequestId(), heatStack.getCanonicalName()); + logger.debug("valet is enabled, the update succeeded - now send confirm to valet with stack id"); + try { + GenericValetResponse<ValetConfirmResponse> gvr = + this.vci.callValetConfirmRequest(msoRequest.getRequestId(), heatStack.getCanonicalName()); // Nothing to really do here whether it succeeded or not other than log it. logger.debug("Return code from Confirm response is {}", gvr.getStatusCode()); } catch (Exception e) { @@ -2110,72 +2033,74 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } } - outputs.value = copyStringOutputs (heatStack.getOutputs ()); + outputs.value = copyStringOutputs(heatStack.getOutputs()); rollback.value = vfRollback; return; } private String getVfModuleNameFromModuleStackId(String vfModuleStackId) { - // expected format of vfModuleStackId is "MSOTEST51-vSAMP3_base_module-0/1fc1f86c-7b35-447f-99a6-c23ec176ae24" - // before the "/" is the vfModuleName and after the "/" is the heat stack id in Openstack - if (vfModuleStackId == null) - return null; - int index = vfModuleStackId.lastIndexOf('/'); - if (index <= 0) - return null; - String vfModuleName = null; - try { - vfModuleName = vfModuleStackId.substring(0, index); - } catch (Exception e) { - logger.debug("Exception", e); - vfModuleName = null; - } - return vfModuleName; + // expected format of vfModuleStackId is "MSOTEST51-vSAMP3_base_module-0/1fc1f86c-7b35-447f-99a6-c23ec176ae24" + // before the "/" is the vfModuleName and after the "/" is the heat stack id in Openstack + if (vfModuleStackId == null) + return null; + int index = vfModuleStackId.lastIndexOf('/'); + if (index <= 0) + return null; + String vfModuleName = null; + try { + vfModuleName = vfModuleStackId.substring(0, index); + } catch (Exception e) { + logger.debug("Exception", e); + vfModuleName = null; + } + return vfModuleName; } /* * Helper method to check a boolean property value - on error return provided default */ private boolean checkBooleanProperty(String propertyName, boolean defaultValue) { - boolean property = defaultValue; - try { - String propertyString = this.environment.getProperty(propertyName); - if ("true".equalsIgnoreCase(propertyString) || "y".equalsIgnoreCase(propertyString)) { - property = true; - } else if ("false".equalsIgnoreCase(propertyString) || "n".equalsIgnoreCase(propertyString)) { - property = false; - } - } catch (Exception e) { - logger.debug("An exception occured trying to get property {} - defaulting to ", propertyName, defaultValue, e); - property = defaultValue; - } - return property; + boolean property = defaultValue; + try { + String propertyString = this.environment.getProperty(propertyName); + if ("true".equalsIgnoreCase(propertyString) || "y".equalsIgnoreCase(propertyString)) { + property = true; + } else if ("false".equalsIgnoreCase(propertyString) || "n".equalsIgnoreCase(propertyString)) { + property = false; + } + } catch (Exception e) { + logger.debug("An exception occured trying to get property {} - defaulting to ", propertyName, defaultValue, + e); + property = defaultValue; + } + return property; } /* * Helper method to combine getFiles and nestedTemplates in to a single Map */ - private Map<String, Object> combineGetFilesAndNestedTemplates(Map<String, Object> getFiles, Map<String, Object> nestedTemplates) { - boolean haveGetFiles = true; - boolean haveNestedTemplates = true; - Map<String, Object> files = new HashMap<String, Object>(); - if (getFiles == null || getFiles.isEmpty()) { - haveGetFiles = false; - } - if (nestedTemplates == null || nestedTemplates.isEmpty()) { - haveNestedTemplates = false; - } + private Map<String, Object> combineGetFilesAndNestedTemplates(Map<String, Object> getFiles, + Map<String, Object> nestedTemplates) { + boolean haveGetFiles = true; + boolean haveNestedTemplates = true; + Map<String, Object> files = new HashMap<String, Object>(); + if (getFiles == null || getFiles.isEmpty()) { + haveGetFiles = false; + } + if (nestedTemplates == null || nestedTemplates.isEmpty()) { + haveNestedTemplates = false; + } if (haveGetFiles && haveNestedTemplates) { - for (String keyString : getFiles.keySet ()) { - files.put (keyString, getFiles.get (keyString)); + for (String keyString : getFiles.keySet()) { + files.put(keyString, getFiles.get(keyString)); } - for (String keyString : nestedTemplates.keySet ()) { - files.put (keyString, nestedTemplates.get (keyString)); + for (String keyString : nestedTemplates.keySet()) { + files.put(keyString, nestedTemplates.get(keyString)); } } else { // Handle if we only have one or neither: if (haveGetFiles) { - files = getFiles; + files = getFiles; } if (haveNestedTemplates) { files = nestedTemplates; @@ -2187,171 +2112,173 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { /* * Valet Create request */ - private boolean valetCreateRequest(String cloudSiteId, String cloudOwner, String tenantId, Map<String, Object> heatFilesObjects, Map<String, Object> nestedTemplatesChecked, - String vfModuleName, boolean backout, HeatTemplate heatTemplate, String newEnvironmentString, Map<String, Object> goldenInputs, - MsoRequest msoRequest, Map<String, Object> inputs, boolean failRequestOnValetFailure, Holder<Map<String, Object>> valetModifiedParamsHolder) throws VnfException { - boolean valetSucceeded = false; - String valetErrorMessage = "more detail not available"; - try { - String keystoneUrl = heat.getCloudSiteKeystoneUrl(cloudSiteId); - Map<String, Object> files = this.combineGetFilesAndNestedTemplates(heatFilesObjects, - nestedTemplatesChecked); - HeatRequest heatRequest = new HeatRequest(vfModuleName, backout, heatTemplate.getTimeoutMinutes(), - heatTemplate.getTemplateBody(), newEnvironmentString, files, goldenInputs); - GenericValetResponse<ValetCreateResponse> createReq = this.vci.callValetCreateRequest(msoRequest.getRequestId(), - cloudSiteId, cloudOwner, tenantId, msoRequest.getServiceInstanceId(), (String)inputs.get("vnf_id"), - (String)inputs.get("vnf_name"), (String)inputs.get("vf_module_id"), (String)inputs.get("vf_module_name"), keystoneUrl, - heatRequest); - ValetCreateResponse vcr = createReq.getReturnObject(); - if (vcr != null && createReq.getStatusCode() == 200) { - ValetStatus status = vcr.getStatus(); - if (status != null) { - String statusCode = status.getStatus(); // "ok" or "failed" - if ("ok".equalsIgnoreCase(statusCode)) { - Map<String, Object> newInputs = vcr.getParameters(); - if (newInputs != null) { - Map<String, Object> oldGold = goldenInputs; - logger.debug("parameters before being modified by valet:{}", oldGold.toString()); - goldenInputs = new HashMap<String, Object>(); - for (String key : newInputs.keySet()) { - goldenInputs.put(key, newInputs.get(key)); - } - valetModifiedParamsHolder.value = goldenInputs; - logger.debug("parameters after being modified by valet:{}", goldenInputs.toString()); - valetSucceeded = true; - } - } else { - valetErrorMessage = status.getMessage(); - } - } - } else { - logger.debug("Got a bad response back from valet"); - valetErrorMessage = "Bad response back from Valet"; - valetSucceeded = false; - } - } catch (Exception e) { - logger.error("An exception occurred trying to call valet ...", e); - valetSucceeded = false; - valetErrorMessage = e.getMessage(); - } - if (failRequestOnValetFailure && !valetSucceeded) { - // The valet request failed - and property says to fail the request - //TODO Create a new exception class for valet? - throw new VnfException("A failure occurred with Valet: " + valetErrorMessage); - } - return valetSucceeded; + private boolean valetCreateRequest(String cloudSiteId, String cloudOwner, String tenantId, + Map<String, Object> heatFilesObjects, Map<String, Object> nestedTemplatesChecked, String vfModuleName, + boolean backout, HeatTemplate heatTemplate, String newEnvironmentString, Map<String, Object> goldenInputs, + MsoRequest msoRequest, Map<String, Object> inputs, boolean failRequestOnValetFailure, + Holder<Map<String, Object>> valetModifiedParamsHolder) throws VnfException { + boolean valetSucceeded = false; + String valetErrorMessage = "more detail not available"; + try { + String keystoneUrl = heat.getCloudSiteKeystoneUrl(cloudSiteId); + Map<String, Object> files = + this.combineGetFilesAndNestedTemplates(heatFilesObjects, nestedTemplatesChecked); + HeatRequest heatRequest = new HeatRequest(vfModuleName, backout, heatTemplate.getTimeoutMinutes(), + heatTemplate.getTemplateBody(), newEnvironmentString, files, goldenInputs); + GenericValetResponse<ValetCreateResponse> createReq = this.vci.callValetCreateRequest( + msoRequest.getRequestId(), cloudSiteId, cloudOwner, tenantId, msoRequest.getServiceInstanceId(), + (String) inputs.get("vnf_id"), (String) inputs.get("vnf_name"), (String) inputs.get("vf_module_id"), + (String) inputs.get("vf_module_name"), keystoneUrl, heatRequest); + ValetCreateResponse vcr = createReq.getReturnObject(); + if (vcr != null && createReq.getStatusCode() == 200) { + ValetStatus status = vcr.getStatus(); + if (status != null) { + String statusCode = status.getStatus(); // "ok" or "failed" + if ("ok".equalsIgnoreCase(statusCode)) { + Map<String, Object> newInputs = vcr.getParameters(); + if (newInputs != null) { + Map<String, Object> oldGold = goldenInputs; + logger.debug("parameters before being modified by valet:{}", oldGold.toString()); + goldenInputs = new HashMap<String, Object>(); + for (String key : newInputs.keySet()) { + goldenInputs.put(key, newInputs.get(key)); + } + valetModifiedParamsHolder.value = goldenInputs; + logger.debug("parameters after being modified by valet:{}", goldenInputs.toString()); + valetSucceeded = true; + } + } else { + valetErrorMessage = status.getMessage(); + } + } + } else { + logger.debug("Got a bad response back from valet"); + valetErrorMessage = "Bad response back from Valet"; + valetSucceeded = false; + } + } catch (Exception e) { + logger.error("An exception occurred trying to call valet ...", e); + valetSucceeded = false; + valetErrorMessage = e.getMessage(); + } + if (failRequestOnValetFailure && !valetSucceeded) { + // The valet request failed - and property says to fail the request + // TODO Create a new exception class for valet? + throw new VnfException("A failure occurred with Valet: " + valetErrorMessage); + } + return valetSucceeded; } /* * Valet update request */ - private boolean valetUpdateRequest(String cloudSiteId, String cloudOwnerId, String tenantId, - Map<String, Object> heatFilesObjects, Map<String, Object> nestedTemplatesChecked, String vfModuleName, - boolean backout, HeatTemplate heatTemplate, String newEnvironmentString, - Map<String, Object> goldenInputs, MsoRequest msoRequest, Map<String, Object> inputs, - boolean failRequestOnValetFailure, Holder<Map<String, Object>> valetModifiedParamsHolder) throws VnfException { - - boolean valetSucceeded = false; - String valetErrorMessage = "more detail not available"; - try { - String keystoneUrl = heat.getCloudSiteKeystoneUrl(cloudSiteId); - Map<String, Object> files = this.combineGetFilesAndNestedTemplates(heatFilesObjects, - nestedTemplatesChecked); - HeatRequest heatRequest = new HeatRequest(vfModuleName, false, heatTemplate.getTimeoutMinutes(), - heatTemplate.getTemplateBody(), newEnvironmentString, files, goldenInputs); - // vnf name is not sent to MSO on update requests - so we will set it to the vf module name for now - GenericValetResponse<ValetUpdateResponse> updateReq = this.vci.callValetUpdateRequest(msoRequest.getRequestId(), - cloudSiteId, cloudOwnerId, tenantId, msoRequest.getServiceInstanceId(), (String)inputs.get("vnf_id"), - vfModuleName, (String)inputs.get("vf_module_id"), vfModuleName, keystoneUrl, - heatRequest); - ValetUpdateResponse vur = updateReq.getReturnObject(); - if (vur != null && updateReq.getStatusCode() == 200) { - ValetStatus status = vur.getStatus(); - if (status != null) { - String statusCode = status.getStatus(); // "ok" or "failed" - if ("ok".equalsIgnoreCase(statusCode)) { - Map<String, Object> newInputs = vur.getParameters(); - if (newInputs != null) { - Map<String, Object> oldGold = goldenInputs; - logger.debug("parameters before being modified by valet:{}", oldGold.toString()); - goldenInputs = new HashMap<String, Object>(); - for (String key : newInputs.keySet()) { - goldenInputs.put(key, newInputs.get(key)); - } - valetModifiedParamsHolder.value = goldenInputs; - logger.debug("parameters after being modified by valet:{}", goldenInputs.toString()); - valetSucceeded = true; - } - } else { - valetErrorMessage = status.getMessage(); - } - } - } else { - logger.debug("Got a bad response back from valet"); - valetErrorMessage = "Got a bad response back from valet"; - valetSucceeded = false; - } - } catch (Exception e) { - logger.error("An exception occurred trying to call valet - will continue processing for now...", e); - valetErrorMessage = e.getMessage(); - valetSucceeded = false; + private boolean valetUpdateRequest(String cloudSiteId, String cloudOwnerId, String tenantId, + Map<String, Object> heatFilesObjects, Map<String, Object> nestedTemplatesChecked, String vfModuleName, + boolean backout, HeatTemplate heatTemplate, String newEnvironmentString, Map<String, Object> goldenInputs, + MsoRequest msoRequest, Map<String, Object> inputs, boolean failRequestOnValetFailure, + Holder<Map<String, Object>> valetModifiedParamsHolder) throws VnfException { + + boolean valetSucceeded = false; + String valetErrorMessage = "more detail not available"; + try { + String keystoneUrl = heat.getCloudSiteKeystoneUrl(cloudSiteId); + Map<String, Object> files = + this.combineGetFilesAndNestedTemplates(heatFilesObjects, nestedTemplatesChecked); + HeatRequest heatRequest = new HeatRequest(vfModuleName, false, heatTemplate.getTimeoutMinutes(), + heatTemplate.getTemplateBody(), newEnvironmentString, files, goldenInputs); + // vnf name is not sent to MSO on update requests - so we will set it to the vf module name for now + GenericValetResponse<ValetUpdateResponse> updateReq = + this.vci.callValetUpdateRequest(msoRequest.getRequestId(), cloudSiteId, cloudOwnerId, tenantId, + msoRequest.getServiceInstanceId(), (String) inputs.get("vnf_id"), vfModuleName, + (String) inputs.get("vf_module_id"), vfModuleName, keystoneUrl, heatRequest); + ValetUpdateResponse vur = updateReq.getReturnObject(); + if (vur != null && updateReq.getStatusCode() == 200) { + ValetStatus status = vur.getStatus(); + if (status != null) { + String statusCode = status.getStatus(); // "ok" or "failed" + if ("ok".equalsIgnoreCase(statusCode)) { + Map<String, Object> newInputs = vur.getParameters(); + if (newInputs != null) { + Map<String, Object> oldGold = goldenInputs; + logger.debug("parameters before being modified by valet:{}", oldGold.toString()); + goldenInputs = new HashMap<String, Object>(); + for (String key : newInputs.keySet()) { + goldenInputs.put(key, newInputs.get(key)); + } + valetModifiedParamsHolder.value = goldenInputs; + logger.debug("parameters after being modified by valet:{}", goldenInputs.toString()); + valetSucceeded = true; + } + } else { + valetErrorMessage = status.getMessage(); + } + } + } else { + logger.debug("Got a bad response back from valet"); + valetErrorMessage = "Got a bad response back from valet"; + valetSucceeded = false; + } + } catch (Exception e) { + logger.error("An exception occurred trying to call valet - will continue processing for now...", e); + valetErrorMessage = e.getMessage(); + valetSucceeded = false; + } + if (failRequestOnValetFailure && !valetSucceeded) { + // The valet request failed - and property says to fail the request + // TODO Create a new exception class for valet? + throw new VnfException("A failure occurred with Valet: " + valetErrorMessage); + } + return valetSucceeded; } - if (failRequestOnValetFailure && !valetSucceeded) { - // The valet request failed - and property says to fail the request - // TODO Create a new exception class for valet? - throw new VnfException("A failure occurred with Valet: " + valetErrorMessage); - } - return valetSucceeded; - } - - /* - * Valet delete request - */ - private boolean valetDeleteRequest(String cloudSiteId, String cloudOwnerId, String tenantId, String vnfName, - MsoRequest msoRequest, boolean failRequestOnValetFailure) { - boolean valetDeleteRequestSucceeded = false; - String valetErrorMessage = "more detail not available"; - try { - String vfModuleId = vnfName; - String vfModuleName = vnfName; - try { - vfModuleName = vnfName.substring(0, vnfName.indexOf('/')); - vfModuleId = vnfName.substring(vnfName.indexOf('/') + 1); - } catch (Exception e) { - // do nothing - send what we got for vnfName for both to valet - logger.error("An exception occurred trying to call MsoVnfAdapterImpl.valetDeleteRequest() method", e); - } - GenericValetResponse<ValetDeleteResponse> deleteReq = this.vci.callValetDeleteRequest(msoRequest.getRequestId(), - cloudSiteId, cloudOwnerId, tenantId, vfModuleId, vfModuleName); - ValetDeleteResponse vdr = deleteReq.getReturnObject(); - if (vdr != null && deleteReq.getStatusCode() == 200) { - ValetStatus status = vdr.getStatus(); - if (status != null) { - String statusCode = status.getStatus(); // "ok" or "failed" - if ("ok".equalsIgnoreCase(statusCode)) { - logger.debug("delete request to valet returned success"); - valetDeleteRequestSucceeded = true; + + /* + * Valet delete request + */ + private boolean valetDeleteRequest(String cloudSiteId, String cloudOwnerId, String tenantId, String vnfName, + MsoRequest msoRequest, boolean failRequestOnValetFailure) { + boolean valetDeleteRequestSucceeded = false; + String valetErrorMessage = "more detail not available"; + try { + String vfModuleId = vnfName; + String vfModuleName = vnfName; + try { + vfModuleName = vnfName.substring(0, vnfName.indexOf('/')); + vfModuleId = vnfName.substring(vnfName.indexOf('/') + 1); + } catch (Exception e) { + // do nothing - send what we got for vnfName for both to valet + logger.error("An exception occurred trying to call MsoVnfAdapterImpl.valetDeleteRequest() method", e); + } + GenericValetResponse<ValetDeleteResponse> deleteReq = this.vci.callValetDeleteRequest( + msoRequest.getRequestId(), cloudSiteId, cloudOwnerId, tenantId, vfModuleId, vfModuleName); + ValetDeleteResponse vdr = deleteReq.getReturnObject(); + if (vdr != null && deleteReq.getStatusCode() == 200) { + ValetStatus status = vdr.getStatus(); + if (status != null) { + String statusCode = status.getStatus(); // "ok" or "failed" + if ("ok".equalsIgnoreCase(statusCode)) { + logger.debug("delete request to valet returned success"); + valetDeleteRequestSucceeded = true; + } else { + logger.debug("delete request to valet returned failure"); + valetDeleteRequestSucceeded = false; + valetErrorMessage = status.getMessage(); + } + } } else { - logger.debug("delete request to valet returned failure"); + logger.debug("Got a bad response back from valet - delete request failed"); valetDeleteRequestSucceeded = false; - valetErrorMessage = status.getMessage(); - } - } - } else { - logger.debug("Got a bad response back from valet - delete request failed"); - valetDeleteRequestSucceeded = false; - valetErrorMessage = "Got a bad response back from valet - delete request failed"; - } - } catch (Exception e) { - logger.error("An exception occurred trying to call valet - valetDeleteRequest failed", e); - valetDeleteRequestSucceeded = false; - valetErrorMessage = e.getMessage(); + valetErrorMessage = "Got a bad response back from valet - delete request failed"; + } + } catch (Exception e) { + logger.error("An exception occurred trying to call valet - valetDeleteRequest failed", e); + valetDeleteRequestSucceeded = false; + valetErrorMessage = e.getMessage(); + } + if (valetDeleteRequestSucceeded == false && failRequestOnValetFailure == true) { + logger.error("ValetDeleteRequestFailed - del req still will be sent to openstack", + new VnfException("ValetDeleteRequestFailedError")); + } + return valetDeleteRequestSucceeded; } - if (valetDeleteRequestSucceeded == false && failRequestOnValetFailure == true) { - logger.error("ValetDeleteRequestFailed - del req still will be sent to openstack", new VnfException - ("ValetDeleteRequestFailedError")); - } - return valetDeleteRequestSucceeded; - } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImpl.java index dc695615cb..2ea7ff417c 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImpl.java @@ -30,10 +30,8 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; - import javax.jws.WebService; import javax.xml.ws.Holder; - import org.onap.so.adapters.vnf.exceptions.VnfAlreadyExists; import org.onap.so.adapters.vnf.exceptions.VnfException; import org.onap.so.cloud.CloudConfig; @@ -54,7 +52,6 @@ import org.onap.so.db.catalog.utils.MavenLikeVersioning; import org.onap.so.entity.MsoRequest; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; - import org.onap.so.openstack.beans.MsoTenant; import org.onap.so.openstack.beans.VnfRollback; import org.onap.so.openstack.beans.VnfStatus; @@ -69,7 +66,6 @@ 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.JsonParseException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @@ -77,7 +73,8 @@ import org.springframework.transaction.annotation.Transactional; @Component @Transactional -@WebService(serviceName = "VnfAdapter", endpointInterface = "org.onap.so.adapters.vnf.MsoVnfAdapter", targetNamespace = "http://org.onap.so/vnf") +@WebService(serviceName = "VnfAdapter", endpointInterface = "org.onap.so.adapters.vnf.MsoVnfAdapter", + targetNamespace = "http://org.onap.so/vnf") public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { private static Logger logger = LoggerFactory.getLogger(MsoVnfCloudifyAdapterImpl.class); @@ -87,8 +84,8 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { private static final String LOG_REPLY_NAME = "MSO-VnfAdapter:MSO-BPMN."; private static final String CHECK_REQD_PARAMS = "org.onap.so.adapters.vnf.checkRequiredParameters"; private static final String ADD_GET_FILES_ON_VOLUME_REQ = "org.onap.so.adapters.vnf.addGetFilesOnVolumeReq"; - private static final String CLOUDIFY_RESPONSE_SUCCESS="Successfully received response from Cloudify"; - private static final String CLOUDIFY="Cloudify"; + private static final String CLOUDIFY_RESPONSE_SUCCESS = "Successfully received response from Cloudify"; + private static final String CLOUDIFY = "Cloudify"; private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); @@ -106,16 +103,18 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { @Autowired protected MsoCloudifyUtils cloudifyUtils; + /** * Health Check web method. Does nothing but return to show the adapter is deployed. */ @Override - public void healthCheck () { + public void healthCheck() { logger.debug("Health check call in VNF Cloudify Adapter"); } /** * DO NOT use that constructor to instantiate this class, the msoPropertiesfactory will be NULL. + * * @see MsoVnfCloudifyAdapterImpl#MsoVnfAdapterImpl(MsoPropertiesFactory, CloudConfigFactory) */ public MsoVnfCloudifyAdapterImpl() { @@ -123,57 +122,31 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { } /** - * This is the "Create VNF" web service implementation. - * This function is now unsupported and will return an error. + * This is the "Create VNF" web service implementation. This function is now unsupported and will return an error. * */ @Override - public void createVnf (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfType, - String vnfVersion, - String vnfName, - String requestType, - String volumeGroupHeatStackId, - Map <String, Object> inputs, - Boolean failIfExists, - Boolean backout, - Boolean enableBridge, - MsoRequest msoRequest, - Holder <String> vnfId, - Holder <Map <String, String>> outputs, - Holder <VnfRollback> rollback) - throws VnfException - { - // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules. + public void createVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, String vnfVersion, + String vnfName, String requestType, String volumeGroupHeatStackId, Map<String, Object> inputs, + Boolean failIfExists, Boolean backout, Boolean enableBridge, MsoRequest msoRequest, Holder<String> vnfId, + Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback) throws VnfException { + // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules. logger.debug("CreateVNF command attempted but not supported"); throw new VnfException("CreateVNF: Unsupported command", MsoExceptionCategory.USERDATA); } /** - * This is the "Update VNF" web service implementation. - * This function is now unsupported and will return an error. + * This is the "Update VNF" web service implementation. This function is now unsupported and will return an error. * */ @Override - public void updateVnf (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfType, - String vnfVersion, - String vnfName, - String requestType, - String volumeGroupHeatStackId, - Map <String, Object> inputs, - MsoRequest msoRequest, - Holder <Map <String, String>> outputs, - Holder <VnfRollback> rollback) - throws VnfException - { - // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules. - logger.debug("UpdateVNF command attempted but not supported"); - throw new VnfException ("UpdateVNF: Unsupported command", MsoExceptionCategory.USERDATA); + public void updateVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, String vnfVersion, + String vnfName, String requestType, String volumeGroupHeatStackId, Map<String, Object> inputs, + MsoRequest msoRequest, Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback) + throws VnfException { + // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules. + logger.debug("UpdateVNF command attempted but not supported"); + throw new VnfException("UpdateVNF: Unsupported command", MsoExceptionCategory.USERDATA); } /** @@ -181,13 +154,13 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { * * This really should be QueryVfModule, but nobody ever changed it. * - * For Cloudify, this will look up a deployment by its deployment ID, which is really the same - * as deployment name, since it assigned by the client when a deployment is created. - * Also, the input cloudSiteId is used only to identify which Cloudify instance to query, - * and the tenantId is ignored (since that really only applies for Openstack/Heat). + * For Cloudify, this will look up a deployment by its deployment ID, which is really the same as deployment name, + * since it assigned by the client when a deployment is created. Also, the input cloudSiteId is used only to + * identify which Cloudify instance to query, and the tenantId is ignored (since that really only applies for + * Openstack/Heat). * - * The method returns an indicator that the VNF exists, along with its status and outputs. - * The input "vnfName" will also be reflected back as its ID. + * The method returns an indicator that the VNF exists, along with its status and outputs. The input "vnfName" will + * also be reflected back as its ID. * * @param cloudSiteId CLLI code of the cloud site in which to query * @param cloudOwner cloud owner of the cloud site in which to query @@ -199,44 +172,35 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { * @param outputs Holder for Map of VNF outputs from Cloudify deployment (assigned IPs, etc) */ @Override - public void queryVnf (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfName, - MsoRequest msoRequest, - Holder <Boolean> vnfExists, - Holder <String> vnfId, - Holder <VnfStatus> status, - Holder <Map <String, String>> outputs) - throws VnfException - { - logger.debug ("Querying VNF {} in {}", vnfName, cloudSiteId + "/" + tenantId); + public void queryVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, MsoRequest msoRequest, + Holder<Boolean> vnfExists, Holder<String> vnfId, Holder<VnfStatus> status, + Holder<Map<String, String>> outputs) throws VnfException { + logger.debug("Querying VNF {} in {}", vnfName, cloudSiteId + "/" + tenantId); // Will capture execution time for metrics - long startTime = System.currentTimeMillis (); - long subStartTime = System.currentTimeMillis (); - - DeploymentInfo deployment = null; - - try { - deployment = cloudifyUtils.queryDeployment(cloudSiteId, tenantId, vnfName); - } - catch (MsoCloudifyManagerNotFound e) { - // This site does not have a Cloudify Manager. - // This isn't an error, just means we won't find the VNF here. - deployment = null; - } - catch (MsoException me) { - // Failed to query the Deployment due to a cloudify exception. - // Convert to a generic VnfException - me.addContext("QueryVNF"); - String error = "Query VNF (Cloudify): " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger - .error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId, tenantId, - CLOUDIFY, "QueryVNF", ErrorCode.DataError.getValue(), "Exception - queryDeployment", me); - logger.debug(error); - throw new VnfException(me); - } + long startTime = System.currentTimeMillis(); + long subStartTime = System.currentTimeMillis(); + + DeploymentInfo deployment = null; + + try { + deployment = cloudifyUtils.queryDeployment(cloudSiteId, tenantId, vnfName); + } catch (MsoCloudifyManagerNotFound e) { + // This site does not have a Cloudify Manager. + // This isn't an error, just means we won't find the VNF here. + deployment = null; + } catch (MsoException me) { + // Failed to query the Deployment due to a cloudify exception. + // Convert to a generic VnfException + me.addContext("QueryVNF"); + String error = "Query VNF (Cloudify): " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + + ": " + me; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, + cloudSiteId, tenantId, CLOUDIFY, "QueryVNF", ErrorCode.DataError.getValue(), + "Exception - queryDeployment", me); + logger.debug(error); + throw new VnfException(me); + } if (deployment != null && deployment.getStatus() != DeploymentStatus.NOTFOUND) { vnfExists.value = Boolean.TRUE; @@ -258,37 +222,31 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { /** - * This is the "Delete VNF" web service implementation. - * This function is now unsupported and will return an error. + * This is the "Delete VNF" web service implementation. This function is now unsupported and will return an error. * */ @Override - public void deleteVnf (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfName, - MsoRequest msoRequest) throws VnfException { + public void deleteVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, MsoRequest msoRequest) + throws VnfException { - // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules. + // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules. logger.debug("DeleteVNF command attempted but not supported"); - throw new VnfException ("DeleteVNF: Unsupported command", MsoExceptionCategory.USERDATA); + throw new VnfException("DeleteVNF: Unsupported command", MsoExceptionCategory.USERDATA); } /** - * This web service endpoint will rollback a previous Create VNF operation. - * A rollback object is returned to the client in a successful creation - * response. The client can pass that object as-is back to the rollbackVnf - * operation to undo the creation. + * This web service endpoint will rollback a previous Create VNF operation. A rollback object is returned to the + * client in a successful creation response. The client can pass that object as-is back to the rollbackVnf operation + * to undo the creation. * - * TODO: This should be rollbackVfModule and/or rollbackVolumeGroup, - * but APIs were apparently never updated. + * TODO: This should be rollbackVfModule and/or rollbackVolumeGroup, but APIs were apparently never updated. */ @Override - public void rollbackVnf (VnfRollback rollback) throws VnfException { - long startTime = System.currentTimeMillis (); - // rollback may be null (e.g. if stack already existed when Create was called) + public void rollbackVnf(VnfRollback rollback) throws VnfException { + long startTime = System.currentTimeMillis(); + // rollback may be null (e.g. if stack already existed when Create was called) if (rollback == null) { - logger.info ("{} {} {}", MessageEnum.RA_ROLLBACK_NULL.toString(), "OpenStack", "rollbackVnf"); + logger.info("{} {} {}", MessageEnum.RA_ROLLBACK_NULL.toString(), "OpenStack", "rollbackVnf"); return; } @@ -298,104 +256,102 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { } // Get the elements of the VnfRollback object for easier access - String cloudSiteId = rollback.getCloudSiteId (); + String cloudSiteId = rollback.getCloudSiteId(); String cloudOwner = rollback.getCloudOwner(); - String tenantId = rollback.getTenantId (); - String vfModuleId = rollback.getVfModuleStackId (); + String tenantId = rollback.getTenantId(); + String vfModuleId = rollback.getVfModuleStackId(); logger.debug("Rolling Back VF Module {} in {}", vfModuleId, cloudOwner + "/" + cloudSiteId + "/" + tenantId); - DeploymentInfo deployment = null; + DeploymentInfo deployment = null; // Use the MsoCloudifyUtils to delete the deployment. Set the polling flag to true. // The possible outcomes of deleteStack are a StackInfo object with status // of NOTFOUND (on success) or FAILED (on error). Also, MsoOpenstackException // could be thrown. - long subStartTime = System.currentTimeMillis (); + long subStartTime = System.currentTimeMillis(); try { - // KLUDGE - Cloudify requires Tenant Name for Openstack. We have the ID. - // Go directly to Keystone until APIs could be updated to supply the name. - MsoTenant msoTenant = keystoneUtils.queryTenant(tenantId, cloudSiteId); - String tenantName = (msoTenant != null? msoTenant.getTenantName() : tenantId); + // KLUDGE - Cloudify requires Tenant Name for Openstack. We have the ID. + // Go directly to Keystone until APIs could be updated to supply the name. + MsoTenant msoTenant = keystoneUtils.queryTenant(tenantId, cloudSiteId); + String tenantName = (msoTenant != null ? msoTenant.getTenantName() : tenantId); - // TODO: Get a reasonable timeout. Use a global property, or store the creation timeout in rollback object and use that. + // TODO: Get a reasonable timeout. Use a global property, or store the creation timeout in rollback object + // and use that. deployment = cloudifyUtils.uninstallAndDeleteDeployment(cloudSiteId, tenantName, vfModuleId, 5); logger.debug("Rolled back deployment: {}", deployment.getId()); } catch (MsoException me) { // Failed to rollback the VNF due to a cloudify exception. // Convert to a generic VnfException - me.addContext ("RollbackVNF"); - String error = "Rollback VF Module: " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vfModuleId, cloudOwner, cloudSiteId, - tenantId, CLOUDIFY, "DeleteDeployment", ErrorCode.DataError.getValue(), - "Exception - DeleteDeployment", me); + me.addContext("RollbackVNF"); + String error = "Rollback VF Module: " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + + tenantId + ": " + me; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vfModuleId, cloudOwner, + cloudSiteId, tenantId, CLOUDIFY, "DeleteDeployment", ErrorCode.DataError.getValue(), + "Exception - DeleteDeployment", me); logger.debug(error); - throw new VnfException (me); + throw new VnfException(me); } return; } - private VnfStatus deploymentStatusToVnfStatus (DeploymentInfo deployment) { - // Determine the status based on last action & status - // DeploymentInfo object should be enhanced to report a better status internally. - DeploymentStatus status = deployment.getStatus(); - String lastAction = deployment.getLastAction(); - - if (status == null || lastAction == null) { - return VnfStatus.UNKNOWN; - } - else if (status == DeploymentStatus.NOTFOUND) { - return VnfStatus.NOTFOUND; - } - else if (status == DeploymentStatus.INSTALLED) { - return VnfStatus.ACTIVE; - } - else if (status == DeploymentStatus.CREATED) { - // Should have an INACTIVE status for this case. Shouldn't really happen, but - // Install was never run, or Uninstall was done but deployment didn't get deleted. - return VnfStatus.UNKNOWN; - } - else if (status == DeploymentStatus.FAILED) { - return VnfStatus.FAILED; - } - - return VnfStatus.UNKNOWN; + private VnfStatus deploymentStatusToVnfStatus(DeploymentInfo deployment) { + // Determine the status based on last action & status + // DeploymentInfo object should be enhanced to report a better status internally. + DeploymentStatus status = deployment.getStatus(); + String lastAction = deployment.getLastAction(); + + if (status == null || lastAction == null) { + return VnfStatus.UNKNOWN; + } else if (status == DeploymentStatus.NOTFOUND) { + return VnfStatus.NOTFOUND; + } else if (status == DeploymentStatus.INSTALLED) { + return VnfStatus.ACTIVE; + } else if (status == DeploymentStatus.CREATED) { + // Should have an INACTIVE status for this case. Shouldn't really happen, but + // Install was never run, or Uninstall was done but deployment didn't get deleted. + return VnfStatus.UNKNOWN; + } else if (status == DeploymentStatus.FAILED) { + return VnfStatus.FAILED; + } + + return VnfStatus.UNKNOWN; } - private Map <String, String> copyStringOutputs (Map <String, Object> stackOutputs) { - Map <String, String> stringOutputs = new HashMap <String, String> (); - for (String key : stackOutputs.keySet ()) { - if (stackOutputs.get (key) instanceof String) { - stringOutputs.put (key, (String) stackOutputs.get (key)); - } else if (stackOutputs.get(key) instanceof Integer) { - try { - String str = "" + stackOutputs.get(key); - stringOutputs.put(key, str); - } catch (Exception e) { - logger.debug("Unable to add " + key + " to outputs"); - } + private Map<String, String> copyStringOutputs(Map<String, Object> stackOutputs) { + Map<String, String> stringOutputs = new HashMap<String, String>(); + for (String key : stackOutputs.keySet()) { + if (stackOutputs.get(key) instanceof String) { + stringOutputs.put(key, (String) stackOutputs.get(key)); + } else if (stackOutputs.get(key) instanceof Integer) { + try { + String str = "" + stackOutputs.get(key); + stringOutputs.put(key, str); + } catch (Exception e) { + logger.debug("Unable to add " + key + " to outputs"); + } } else if (stackOutputs.get(key) instanceof JsonNode) { - try { - String str = this.convertNode((JsonNode) stackOutputs.get(key)); - stringOutputs.put(key, str); - } catch (Exception e) { - logger.debug("Unable to add " + key + " to outputs - exception converting JsonNode"); - } + try { + String str = this.convertNode((JsonNode) stackOutputs.get(key)); + stringOutputs.put(key, str); + } catch (Exception e) { + logger.debug("Unable to add " + key + " to outputs - exception converting JsonNode"); + } } else if (stackOutputs.get(key) instanceof java.util.LinkedHashMap) { - try { - String str = JSON_MAPPER.writeValueAsString(stackOutputs.get(key)); - stringOutputs.put(key, str); - } catch (Exception e) { - logger.debug("Unable to add " + key + " to outputs - exception converting LinkedHashMap"); - } + try { + String str = JSON_MAPPER.writeValueAsString(stackOutputs.get(key)); + stringOutputs.put(key, str); + } catch (Exception e) { + logger.debug("Unable to add " + key + " to outputs - exception converting LinkedHashMap"); + } } else { - try { - String str = stackOutputs.get(key).toString(); - stringOutputs.put(key, str); - } catch (Exception e) { - logger.debug("Unable to add " + key + " to outputs - unable to call .toString() " + e.getMessage()); - } + try { + String str = stackOutputs.get(key).toString(); + stringOutputs.put(key, str); + } catch (Exception e) { + logger.debug("Unable to add " + key + " to outputs - unable to call .toString() " + e.getMessage()); + } } } return stringOutputs; @@ -403,43 +359,41 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { private void sendMapToDebug(Map<String, Object> inputs, String optionalName) { - int i = 0; - StringBuilder sb = new StringBuilder(optionalName == null ? "\ninputs" : "\n" + optionalName); - if (inputs == null) { - sb.append("\tNULL"); - } - else if (inputs.size() < 1) { - sb.append("\tEMPTY"); - } else { - for (String str : inputs.keySet()) { - String outputString; - try { - outputString = inputs.get(str).toString(); - } catch (Exception e) { - outputString = "Unable to call toString() on the value for " + str; - } - sb.append("\t\nitem " + i++ + ": '" + str + "'='" + outputString + "'"); - } - } - logger.debug(sb.toString()); - return; + int i = 0; + StringBuilder sb = new StringBuilder(optionalName == null ? "\ninputs" : "\n" + optionalName); + if (inputs == null) { + sb.append("\tNULL"); + } else if (inputs.size() < 1) { + sb.append("\tEMPTY"); + } else { + for (String str : inputs.keySet()) { + String outputString; + try { + outputString = inputs.get(str).toString(); + } catch (Exception e) { + outputString = "Unable to call toString() on the value for " + str; + } + sb.append("\t\nitem " + i++ + ": '" + str + "'='" + outputString + "'"); + } + } + logger.debug(sb.toString()); + return; } private void sendMapToDebug(Map<String, Object> inputs) { - int i = 0; - StringBuilder sb = new StringBuilder("inputs:"); - if (inputs == null) { - sb.append("\tNULL"); - } - else if (inputs.size() < 1) { - sb.append("\tEMPTY"); - } else { - for (String str : inputs.keySet()) { - sb.append("\titem " + i++ + ": " + str + "=" + inputs.get(str)); - } - } - logger.debug(sb.toString()); - return; + int i = 0; + StringBuilder sb = new StringBuilder("inputs:"); + if (inputs == null) { + sb.append("\tNULL"); + } else if (inputs.size() < 1) { + sb.append("\tEMPTY"); + } else { + for (String str : inputs.keySet()) { + sb.append("\titem " + i++ + ": " + str + "=" + inputs.get(str)); + } + } + logger.debug(sb.toString()); + return; } private String convertNode(final JsonNode node) { @@ -465,15 +419,15 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { Object obj = objectMap.get(key); if (obj instanceof String) { stringMap.put(key, (String) objectMap.get(key)); - } else if (obj instanceof JsonNode ){ + } else if (obj 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 { String str = this.convertNode((JsonNode) obj); stringMap.put(key, str); } catch (Exception e) { - logger.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode "+ key); - //okay in this instance - only string values (fqdn) are expected to be needed + logger.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode " + key); + // okay in this instance - only string values (fqdn) are expected to be needed } } else if (obj instanceof java.util.LinkedHashMap) { logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode"); @@ -481,21 +435,22 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { String str = JSON_MAPPER.writeValueAsString(obj); stringMap.put(key, str); } catch (Exception e) { - logger.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap "+ key); - } - } else if (obj instanceof Integer) { - try { - String str = "" + obj; - stringMap.put(key, str); - } catch (Exception e) { - logger.debug("DANGER WILL ROBINSON: unable to convert value for Integer "+ key); + logger.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap " + key); + } + } else if (obj instanceof Integer) { + try { + String str = "" + obj; + stringMap.put(key, str); + } catch (Exception e) { + logger.debug("DANGER WILL ROBINSON: unable to convert value for Integer " + key); } } else { try { - String str = obj.toString(); + String str = obj.toString(); stringMap.put(key, str); } catch (Exception e) { - logger.debug("DANGER WILL ROBINSON: unable to convert value "+ key + " (" + e.getMessage() + ")"); + logger.debug( + "DANGER WILL ROBINSON: unable to convert value " + key + " (" + e.getMessage() + ")"); } } } @@ -505,46 +460,38 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { } /** - * This is the "Create VF Module" web service implementation. - * It will instantiate a new VF Module of the requested type in the specified cloud - * and tenant. The tenant must exist before this service is called. + * This is the "Create VF Module" web service implementation. It will instantiate a new VF Module of the requested + * type in the specified cloud and tenant. The tenant must exist before this service is called. * - * If a VF Module with the same name already exists, this can be considered a - * success or failure, depending on the value of the 'failIfExists' parameter. + * If a VF Module with the same name already exists, this can be considered a success or failure, depending on the + * value of the 'failIfExists' parameter. * - * All VF Modules are defined in the MSO catalog. The caller must request - * one of the pre-defined module types or an error will be returned. Within the - * catalog, each VF Module references (among other things) a cloud template - * which is used to deploy the required artifacts (VMs, networks, etc.) - * to the cloud. In this adapter implementation, that artifact is expected - * to be a Cloudify blueprint. + * All VF Modules are defined in the MSO catalog. The caller must request one of the pre-defined module types or an + * error will be returned. Within the catalog, each VF Module references (among other things) a cloud template which + * is used to deploy the required artifacts (VMs, networks, etc.) to the cloud. In this adapter implementation, that + * artifact is expected to be a Cloudify blueprint. * - * Depending on the blueprint, a variable set of input parameters will - * be defined, some of which are required. The caller is responsible to - * pass the necessary input data for the module or an error will be thrown. + * Depending on the blueprint, a variable set of input parameters will be defined, some of which are required. The + * caller is responsible to pass the necessary input data for the module or an error will be thrown. * - * The method returns the vfModuleId, a Map of output attributes, and a VnfRollback - * object. This last object can be passed as-is to the rollbackVnf operation to - * undo everything that was created for the Module. This is useful if a VF module - * is successfully created but the orchestration fails on a subsequent step. + * The method returns the vfModuleId, a Map of output attributes, and a VnfRollback object. This last object can be + * passed as-is to the rollbackVnf operation to undo everything that was created for the Module. This is useful if a + * VF module is successfully created but the orchestration fails on a subsequent step. * * @param cloudSiteId CLLI code of the cloud site in which to create the VNF * @param cloudOwner cloud owner of the cloud site in which to create the VNF * @param tenantId Openstack tenant identifier - * @param vfModuleType VF Module type key, should match a VNF definition in catalog DB. - * Deprecated - should use modelCustomizationUuid - * @param vnfVersion VNF version key, should match a VNF definition in catalog DB - * Deprecated - VF Module versions also captured by modelCustomizationUuid + * @param vfModuleType VF Module type key, should match a VNF definition in catalog DB. Deprecated - should use + * modelCustomizationUuid + * @param vnfVersion VNF version key, should match a VNF definition in catalog DB Deprecated - VF Module versions + * also captured by modelCustomizationUuid * @param genericVnfId Generic VNF ID * @param vfModuleName Name to be assigned to the new VF Module * @param vfModuleId Id of the new VF Module * @param requestType Indicates if this is a Volume Group or Module request - * @param volumeGroupId Identifier (i.e. deployment ID) for a Volume Group - * to attach to a VF Module - * @param baseVfModuleId Identifier (i.e. deployment ID) of the Base Module if - * this is an Add-on module - * @param modelCustomizationUuid Unique ID for the VF Module's model. Replaces - * the use of vfModuleType. + * @param volumeGroupId Identifier (i.e. deployment ID) for a Volume Group to attach to a VF Module + * @param baseVfModuleId Identifier (i.e. deployment ID) of the Base Module if this is an Add-on module + * @param modelCustomizationUuid Unique ID for the VF Module's model. Replaces the use of vfModuleType. * @param inputs Map of key=value inputs for VNF stack creation * @param failIfExists Flag whether already existing VNF should be considered * @param backout Flag whether to suppress automatic backout (for testing) @@ -554,68 +501,51 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { * @param rollback Holder for returning VnfRollback object */ @Override - public void createVfModule(String cloudSiteId, - String cloudOwner, - String tenantId, - String vfModuleType, - String vnfVersion, - String genericVnfId, - String vfModuleName, - String vfModuleId, - String requestType, - String volumeGroupId, - String baseVfModuleId, - String modelCustomizationUuid, - Map <String, Object> inputs, - Boolean failIfExists, - Boolean backout, - Boolean enableBridge, - MsoRequest msoRequest, - Holder <String> vnfId, - Holder <Map <String, String>> outputs, - Holder <VnfRollback> rollback) - throws VnfException - { + public void createVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vfModuleType, + String vnfVersion, String genericVnfId, String vfModuleName, String vfModuleId, String requestType, + String volumeGroupId, String baseVfModuleId, String modelCustomizationUuid, Map<String, Object> inputs, + Boolean failIfExists, Boolean backout, Boolean enableBridge, MsoRequest msoRequest, Holder<String> vnfId, + Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback) throws VnfException { // Will capture execution time for metrics - long startTime = System.currentTimeMillis (); + long startTime = System.currentTimeMillis(); - // Require a model customization ID. Every VF Module definition must have one. + // Require a model customization ID. Every VF Module definition must have one. if (modelCustomizationUuid == null || modelCustomizationUuid.isEmpty()) { logger.debug("Missing required input: modelCustomizationUuid"); String error = "Create vfModule error: Missing required input: modelCustomizationUuid"; logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), - "VF Module ModelCustomizationUuid", CLOUDIFY, ErrorCode.DataError.getValue(), - "Create VF Module: Missing required input: modelCustomizationUuid"); + "VF Module ModelCustomizationUuid", CLOUDIFY, ErrorCode.DataError.getValue(), + "Create VF Module: Missing required input: modelCustomizationUuid"); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); } // Clean up some inputs to make comparisons easier if (requestType == null) - requestType = ""; + requestType = ""; if ("".equals(volumeGroupId) || "null".equals(volumeGroupId)) - volumeGroupId = null; + volumeGroupId = null; if ("".equals(baseVfModuleId) || "null".equals(baseVfModuleId)) - baseVfModuleId = null; + baseVfModuleId = null; if (inputs == null) { - // Create an empty set of inputs - inputs = new HashMap<>(); - logger.debug("inputs == null - setting to empty"); + // Create an empty set of inputs + inputs = new HashMap<>(); + logger.debug("inputs == null - setting to empty"); } else { - this.sendMapToDebug(inputs); + this.sendMapToDebug(inputs); } // Check if this is for a "Volume" module boolean isVolumeRequest = false; if (requestType.startsWith("VOLUME")) { - isVolumeRequest = true; + isVolumeRequest = true; } - logger.debug("requestType = " + requestType + ", volumeGroupStackId = " + volumeGroupId + ", baseStackId = " + - baseVfModuleId); + logger.debug("requestType = " + requestType + ", volumeGroupStackId = " + volumeGroupId + ", baseStackId = " + + baseVfModuleId); // Build a default rollback object (no actions performed) VnfRollback vfRollback = new VnfRollback(); @@ -624,158 +554,161 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { vfRollback.setTenantId(tenantId); vfRollback.setMsoRequest(msoRequest); vfRollback.setRequestType(requestType); - vfRollback.setIsBase(false); // Until we know better + vfRollback.setIsBase(false); // Until we know better vfRollback.setVolumeGroupHeatStackId(volumeGroupId); vfRollback.setBaseGroupHeatStackId(baseVfModuleId); vfRollback.setModelCustomizationUuid(modelCustomizationUuid); vfRollback.setMode("CFY"); - rollback.value = vfRollback; // Default rollback - no updates performed + rollback.value = vfRollback; // Default rollback - no updates performed // Get the VNF/VF Module definition from the Catalog DB first. - // There are three relevant records: VfModule, VfModuleCustomization, VnfResource + // There are three relevant records: VfModule, VfModuleCustomization, VnfResource VfModule vf = null; - VnfResource vnfResource = null; - VfModuleCustomization vfmc = null; + VnfResource vnfResource = null; + VfModuleCustomization vfmc = null; try { vfmc = vfModuleCustomRepo.findFirstByModelCustomizationUUIDOrderByCreatedDesc(modelCustomizationUuid); if (vfmc == null) { String error = "Create vfModule error: Unable to find vfModuleCust with modelCustomizationUuid=" - + modelCustomizationUuid; + + modelCustomizationUuid; logger.debug(error); - logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "VF Module " - + "ModelCustomizationUuid", - modelCustomizationUuid, "CatalogDb", ErrorCode.DataError.getValue(), error); + logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), + "VF Module " + "ModelCustomizationUuid", modelCustomizationUuid, "CatalogDb", + ErrorCode.DataError.getValue(), error); throw new VnfException(error, MsoExceptionCategory.USERDATA); } else { logger.debug("Found vfModuleCust entry " + vfmc.toString()); } // Get the vfModule and vnfResource records - vf = vfmc.getVfModule(); - vnfResource = vfmc.getVfModule().getVnfResources(); - } - catch (Exception e) { + vf = vfmc.getVfModule(); + vnfResource = vfmc.getVfModule().getVnfResources(); + } catch (Exception e) { - logger.debug("unhandled exception in create VF - [Query]" + e.getMessage()); - throw new VnfException("Exception during create VF " + e.getMessage()); + logger.debug("unhandled exception in create VF - [Query]" + e.getMessage()); + throw new VnfException("Exception during create VF " + e.getMessage()); } - // Perform a version check against cloudSite + // Perform a version check against cloudSite // Obtain the cloud site information where we will create the VF Module - Optional<CloudSite> cloudSiteOp = cloudConfig.getCloudSite (cloudSiteId); + Optional<CloudSite> cloudSiteOp = cloudConfig.getCloudSite(cloudSiteId); if (!cloudSiteOp.isPresent()) { - throw new VnfException (new MsoCloudSiteNotFound (cloudSiteId)); + throw new VnfException(new MsoCloudSiteNotFound(cloudSiteId)); } CloudSite cloudSite = cloudSiteOp.get(); - MavenLikeVersioning aicV = new MavenLikeVersioning(); - aicV.setVersion(cloudSite.getCloudVersion()); - - String vnfMin = vnfResource.getAicVersionMin(); - String vnfMax = vnfResource.getAicVersionMax(); - - if ( (vnfMin != null && !(aicV.isMoreRecentThan(vnfMin) || aicV.isTheSameVersion(vnfMin))) || - (vnfMax != null && aicV.isMoreRecentThan(vnfMax))) - { - // ERROR - String error = "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUUID() - + " VersionMin=" + vnfMin + " VersionMax:" + vnfMax + " NOT supported on Cloud: " + cloudSiteId - + " with AIC_Version:" + cloudSite.getCloudVersion(); - logger.error("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, "OpenStack", - ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion"); - logger.debug(error); - throw new VnfException(error, MsoExceptionCategory.USERDATA); - } - // End Version check + MavenLikeVersioning aicV = new MavenLikeVersioning(); + aicV.setVersion(cloudSite.getCloudVersion()); + + String vnfMin = vnfResource.getAicVersionMin(); + String vnfMax = vnfResource.getAicVersionMax(); + + if ((vnfMin != null && !(aicV.isMoreRecentThan(vnfMin) || aicV.isTheSameVersion(vnfMin))) + || (vnfMax != null && aicV.isMoreRecentThan(vnfMax))) { + // ERROR + String error = "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" + + vnfResource.getModelUUID() + " VersionMin=" + vnfMin + " VersionMax:" + vnfMax + + " NOT supported on Cloud: " + cloudSiteId + " with AIC_Version:" + cloudSite.getCloudVersion(); + logger.error("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, "OpenStack", + ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion"); + logger.debug(error); + throw new VnfException(error, MsoExceptionCategory.USERDATA); + } + // End Version check DeploymentInfo cloudifyDeployment = null; // First, look up to see if the VF already exists. - long subStartTime1 = System.currentTimeMillis (); + long subStartTime1 = System.currentTimeMillis(); try { - cloudifyDeployment = cloudifyUtils.queryDeployment (cloudSiteId, tenantId, vfModuleName); - } - catch (MsoException me) { + cloudifyDeployment = cloudifyUtils.queryDeployment(cloudSiteId, tenantId, vfModuleName); + } catch (MsoException me) { // Failed to query the Deployment due to a cloudify exception. - String error = "Create VF Module: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ; + String error = "Create VF Module: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/" + + tenantId + ": " + me; logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudSiteId, - tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), - "Exception - queryDeployment", me); + tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), + "Exception - queryDeployment", me); logger.debug(error); // Convert to a generic VnfException - me.addContext ("CreateVFModule"); - throw new VnfException (me); + me.addContext("CreateVFModule"); + throw new VnfException(me); } // More precise handling/messaging if the Module already exists - if (cloudifyDeployment != null && !(cloudifyDeployment.getStatus () == DeploymentStatus.NOTFOUND)) { - // CREATED, INSTALLED, INSTALLING, FAILED, UNINSTALLING, UNKNOWN - DeploymentStatus status = cloudifyDeployment.getStatus(); - logger.debug ("Found Existing Deployment, status=" + status); - - if (status == DeploymentStatus.INSTALLED) { - // fail - it exists - if (failIfExists != null && failIfExists) { - String error = "Create VF: Deployment " + vfModuleName + " already exists in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), - "Deployment " + vfModuleName + " already exists"); - logger.debug(error); - throw new VnfAlreadyExists (vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId()); - } else { - // Found existing deployment and client has not requested "failIfExists". - // Populate the outputs from the existing deployment. + if (cloudifyDeployment != null && !(cloudifyDeployment.getStatus() == DeploymentStatus.NOTFOUND)) { + // CREATED, INSTALLED, INSTALLING, FAILED, UNINSTALLING, UNKNOWN + DeploymentStatus status = cloudifyDeployment.getStatus(); + logger.debug("Found Existing Deployment, status=" + status); + + if (status == DeploymentStatus.INSTALLED) { + // fail - it exists + if (failIfExists != null && failIfExists) { + String error = "Create VF: Deployment " + vfModuleName + " already exists in " + cloudOwner + "/" + + cloudSiteId + "/" + tenantId; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), + vfModuleName, cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", + ErrorCode.DataError.getValue(), "Deployment " + vfModuleName + " already exists"); + logger.debug(error); + throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, + cloudifyDeployment.getId()); + } else { + // Found existing deployment and client has not requested "failIfExists". + // Populate the outputs from the existing deployment. - vnfId.value = cloudifyDeployment.getId(); - outputs.value = copyStringOutputs (cloudifyDeployment.getOutputs ()); + vnfId.value = cloudifyDeployment.getId(); + outputs.value = copyStringOutputs(cloudifyDeployment.getOutputs()); return; - } - } - // Check through various detailed error cases - if (status == DeploymentStatus.INSTALLING || status == DeploymentStatus.UNINSTALLING) { - // fail - it's in progress - return meaningful error - String error = "Create VF: Deployment " + vfModuleName + " already exists and has status " + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; please wait for it to complete, or fix manually."; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), - "Deployment " + vfModuleName + " already exists"); - logger.debug(error); - throw new VnfAlreadyExists (vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId()); - } - else if (status == DeploymentStatus.FAILED) { - // fail - it exists and is in a FAILED state - String error = "Create VF: Deployment " + vfModuleName + " already exists and is in FAILED state in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention."; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), - "Deployment " + vfModuleName + " already " + "exists and is in FAILED state"); - logger.debug(error); - throw new VnfAlreadyExists (vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId()); - } - else if (status == DeploymentStatus.UNKNOWN || status == DeploymentStatus.CREATED) { - // fail - it exists and is in a UNKNOWN state - String error = "Create VF: Deployment " + vfModuleName + " already exists and has status " + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention."; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), - "Deployment " + vfModuleName + " already " + "exists and is in " + status.toString() + " state"); - logger.debug(error); - throw new VnfAlreadyExists (vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId()); - } - else { - // Unexpected, since all known status values have been tested for - String error = - "Create VF: Deployment " + vfModuleName + " already exists with unexpected status " + status - .toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention."; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), - "Deployment " + vfModuleName + " already " + "exists and is in an unknown state"); - logger.debug(error); - throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId()); - } + } + } + // Check through various detailed error cases + if (status == DeploymentStatus.INSTALLING || status == DeploymentStatus.UNINSTALLING) { + // fail - it's in progress - return meaningful error + String error = "Create VF: Deployment " + vfModuleName + " already exists and has status " + + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + + "; please wait for it to complete, or fix manually."; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, + cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), + "Deployment " + vfModuleName + " already exists"); + logger.debug(error); + throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId()); + } else if (status == DeploymentStatus.FAILED) { + // fail - it exists and is in a FAILED state + String error = "Create VF: Deployment " + vfModuleName + " already exists and is in FAILED state in " + + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention."; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, + cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), + "Deployment " + vfModuleName + " already " + "exists and is in FAILED state"); + logger.debug(error); + throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId()); + } else if (status == DeploymentStatus.UNKNOWN || status == DeploymentStatus.CREATED) { + // fail - it exists and is in a UNKNOWN state + String error = "Create VF: Deployment " + vfModuleName + " already exists and has status " + + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + + "; requires manual intervention."; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, + cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), + "Deployment " + vfModuleName + " already " + "exists and is in " + status.toString() + + " state"); + logger.debug(error); + throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId()); + } else { + // Unexpected, since all known status values have been tested for + String error = "Create VF: Deployment " + vfModuleName + " already exists with unexpected status " + + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + + "; requires manual intervention."; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, + cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), + "Deployment " + vfModuleName + " already " + "exists and is in an unknown state"); + logger.debug(error); + throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, cloudifyDeployment.getId()); + } } @@ -785,43 +718,42 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { // If a Volume Group was provided, query its outputs for inclusion in Module input parameters if (volumeGroupId != null) { - long subStartTime2 = System.currentTimeMillis (); + long subStartTime2 = System.currentTimeMillis(); DeploymentInfo volumeDeployment = null; try { - volumeDeployment = cloudifyUtils.queryDeployment (cloudSiteId, tenantId, volumeGroupId); - } - catch (MsoException me) { + volumeDeployment = cloudifyUtils.queryDeployment(cloudSiteId, tenantId, volumeGroupId); + } catch (MsoException me) { // Failed to query the Volume GroupDeployment due to a cloudify exception. - String error = "Create VF Module: Query Volume Group " + volumeGroupId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ; + String error = "Create VF Module: Query Volume Group " + volumeGroupId + " in " + cloudOwner + "/" + + cloudSiteId + "/" + tenantId + ": " + me; logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId, - cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment(volume)", - ErrorCode.DataError.getValue(), "Exception - queryDeployment(volume)", me); + cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment(volume)", + ErrorCode.DataError.getValue(), "Exception - queryDeployment(volume)", me); logger.debug(error); // Convert to a generic VnfException - me.addContext ("CreateVFModule(QueryVolume)"); - throw new VnfException (me); + me.addContext("CreateVFModule(QueryVolume)"); + throw new VnfException(me); } - if (volumeDeployment == null || volumeDeployment.getStatus() == DeploymentStatus.NOTFOUND) { - String error = - "Create VFModule: Attached Volume Group DOES NOT EXIST " + volumeGroupId + " in " + cloudSiteId + "/" - + tenantId + " USER ERROR"; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId, - cloudSiteId, tenantId, error, CLOUDIFY, "queryDeployment(volume)", - ErrorCode.BusinessProcesssError.getValue(), - "Create VFModule: Attached Volume Group DOES NOT EXIST"); - logger.debug(error); - throw new VnfException(error, MsoExceptionCategory.USERDATA); - } else { - logger.debug("Found nested volume group"); - volumeGroupOutputs = volumeDeployment.getOutputs(); - this.sendMapToDebug(volumeGroupOutputs, "volumeGroupOutputs"); - } + if (volumeDeployment == null || volumeDeployment.getStatus() == DeploymentStatus.NOTFOUND) { + String error = "Create VFModule: Attached Volume Group DOES NOT EXIST " + volumeGroupId + " in " + + cloudSiteId + "/" + tenantId + " USER ERROR"; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId, + cloudSiteId, tenantId, error, CLOUDIFY, "queryDeployment(volume)", + ErrorCode.BusinessProcesssError.getValue(), + "Create VFModule: Attached Volume Group DOES NOT EXIST"); + logger.debug(error); + throw new VnfException(error, MsoExceptionCategory.USERDATA); + } else { + logger.debug("Found nested volume group"); + volumeGroupOutputs = volumeDeployment.getOutputs(); + this.sendMapToDebug(volumeGroupOutputs, "volumeGroupOutputs"); + } } // If this is an Add-On Module, query the Base Module outputs // Note: This will be performed whether or not the current request is for an - // Add-On Volume Group or Add-On VF Module + // Add-On Volume Group or Add-On VF Module if (vf.getIsBase()) { logger.debug("This is a BASE Module request"); @@ -832,37 +764,34 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { // Add-On Modules should always have a Base, but just treat as a warning if not provided. // Add-on Volume requests may or may not specify a base. if (!isVolumeRequest && baseVfModuleId == null) { - logger.debug ("WARNING: Add-on Module request - no Base Module ID provided"); + logger.debug("WARNING: Add-on Module request - no Base Module ID provided"); } if (baseVfModuleId != null) { - long subStartTime2 = System.currentTimeMillis (); - DeploymentInfo baseDeployment = null; - try { - baseDeployment = cloudifyUtils.queryDeployment (cloudSiteId, tenantId, baseVfModuleId); - } - catch (MsoException me) { - // Failed to query the Volume GroupDeployment due to a cloudify exception. - String error = - "Create VF Module: Query Base " + baseVfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " - + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId, - cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment(Base)", - ErrorCode.DataError.getValue(), "Exception - queryDeployment(Base)", me); - logger.debug(error); - // Convert to a generic VnfException - me.addContext("CreateVFModule(QueryBase)"); - throw new VnfException (me); - } + long subStartTime2 = System.currentTimeMillis(); + DeploymentInfo baseDeployment = null; + try { + baseDeployment = cloudifyUtils.queryDeployment(cloudSiteId, tenantId, baseVfModuleId); + } catch (MsoException me) { + // Failed to query the Volume GroupDeployment due to a cloudify exception. + String error = "Create VF Module: Query Base " + baseVfModuleId + " in " + cloudOwner + "/" + + cloudSiteId + "/" + tenantId + ": " + me; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId, + cloudOwner, cloudSiteId, tenantId, CLOUDIFY, "queryDeployment(Base)", + ErrorCode.DataError.getValue(), "Exception - queryDeployment(Base)", me); + logger.debug(error); + // Convert to a generic VnfException + me.addContext("CreateVFModule(QueryBase)"); + throw new VnfException(me); + } if (baseDeployment == null || baseDeployment.getStatus() == DeploymentStatus.NOTFOUND) { - String error = - "Create VFModule: Base Module DOES NOT EXIST " + baseVfModuleId + " in " + cloudSiteId + "/" - + tenantId + " USER ERROR"; + String error = "Create VFModule: Base Module DOES NOT EXIST " + baseVfModuleId + " in " + + cloudSiteId + "/" + tenantId + " USER ERROR"; logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId, - cloudSiteId, tenantId, error, CLOUDIFY, "queryDeployment(Base)", - ErrorCode.BusinessProcesssError.getValue(), - "Create VFModule: Base " + "Module DOES NOT EXIST"); + cloudSiteId, tenantId, error, CLOUDIFY, "queryDeployment(Base)", + ErrorCode.BusinessProcesssError.getValue(), + "Create VFModule: Base " + "Module DOES NOT EXIST"); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); } else { @@ -876,36 +805,36 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { // Ready to deploy the new VNF - // NOTE: For this section, heatTemplate is used for both HEAT templates and Cloudify blueprints. + // NOTE: For this section, heatTemplate is used for both HEAT templates and Cloudify blueprints. // In final implementation (post-POC), the template object would either be generic or there would // be a separate DB Table/Object for Blueprints. - // NOTE: The template is fixed for the VF Module. The environment is part of the customization. + // NOTE: The template is fixed for the VF Module. The environment is part of the customization. HeatTemplate heatTemplate = null; HeatEnvironment heatEnvironment = null; if (isVolumeRequest) { - heatTemplate = vf.getVolumeHeatTemplate(); - heatEnvironment = vfmc.getVolumeHeatEnv(); - } else { - heatTemplate = vf.getModuleHeatTemplate(); - heatEnvironment = vfmc.getHeatEnvironment(); - } - - if (heatTemplate == null) { - String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType + ", reqType=" - + requestType; - logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", vfModuleType, - "OpenStack", ErrorCode.DataError.getValue(), error); - throw new VnfException(error, MsoExceptionCategory.INTERNAL); - } else { - logger.debug("Got HEAT Template from DB: {}", heatTemplate.getHeatTemplate()); - } + heatTemplate = vf.getVolumeHeatTemplate(); + heatEnvironment = vfmc.getVolumeHeatEnv(); + } else { + heatTemplate = vf.getModuleHeatTemplate(); + heatEnvironment = vfmc.getHeatEnvironment(); + } + + if (heatTemplate == null) { + String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType + + ", reqType=" + requestType; + logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", + vfModuleType, "OpenStack", ErrorCode.DataError.getValue(), error); + throw new VnfException(error, MsoExceptionCategory.INTERNAL); + } else { + logger.debug("Got HEAT Template from DB: {}", heatTemplate.getHeatTemplate()); + } if (heatEnvironment == null) { String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType; logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID", - "OpenStack", ErrorCode.DataError.getValue(), error); + "OpenStack", ErrorCode.DataError.getValue(), error); // Alarm on this error, configuration must be fixed throw new VnfException(error, MsoExceptionCategory.INTERNAL); } else { @@ -915,260 +844,252 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { try { // All variables converted to their native object types - HashMap<String, Object> goldenInputs = new HashMap<String,Object>(); + HashMap<String, Object> goldenInputs = new HashMap<String, Object>(); List<String> extraInputs = new ArrayList<String>(); - // NOTE: SKIP THIS FOR CLOUDIFY for now. Just use what was passed in. - // This whole section needs to be rewritten. - Boolean skipInputChecks = false; - - if (skipInputChecks) { - goldenInputs = new HashMap<String,Object>(); - for (String key : inputs.keySet()) { - goldenInputs.put(key, inputs.get(key)); - } - } - else { - // Build maps for the parameters (including aliases) to simplify checks - HashMap<String, HeatTemplateParam> params = new HashMap<String, HeatTemplateParam>(); - - Set<HeatTemplateParam> paramSet = heatTemplate.getParameters(); - logger.debug("paramSet has {} entries", paramSet.size()); - - for (HeatTemplateParam htp : paramSet) { - params.put(htp.getParamName(), htp); - - // Include aliases. - String alias = htp.getParamAlias(); - if (alias != null && !alias.equals("") && !params.containsKey(alias)) { - params.put(alias, htp); - } - } - - // First, convert all inputs to their "template" type - for (String key : inputs.keySet()) { - if (params.containsKey(key)) { - Object value = cloudifyUtils.convertInputValue(inputs.get(key), params.get(key)); - if (value != null) { - goldenInputs.put(key, value); - } - else { - logger.debug("Failed to convert input " + key + "='" + inputs.get(key) + "' to " + params.get(key) - .getParamType()); - } - } else { - extraInputs.add(key); - } - } - - if (!extraInputs.isEmpty()) { - logger.debug("Ignoring extra inputs: " + extraInputs); - } - - // Next add in Volume Group Outputs if there are any. Copy directly without conversions. - if (volumeGroupOutputs != null && !volumeGroupOutputs.isEmpty()) { - for (String key : volumeGroupOutputs.keySet()) { - if (params.containsKey(key) && !goldenInputs.containsKey(key)) { - goldenInputs.put(key, volumeGroupOutputs.get(key)); - } - } - } - - // Next add in Base Module Outputs if there are any. Copy directly without conversions. - if (baseModuleOutputs != null && !baseModuleOutputs.isEmpty()) { - for (String key : baseModuleOutputs.keySet()) { - if (params.containsKey(key) && !goldenInputs.containsKey(key)) { - goldenInputs.put(key, baseModuleOutputs.get(key)); - } - } - } - - // Last, add in values from the "environment" file. - // These are added to the inputs, since Cloudify doesn't pass an environment file like Heat. - - // TODO: This may take a different form for Cloudify, but for now process it - // with Heat environment file syntax + // NOTE: SKIP THIS FOR CLOUDIFY for now. Just use what was passed in. + // This whole section needs to be rewritten. + Boolean skipInputChecks = false; + + if (skipInputChecks) { + goldenInputs = new HashMap<String, Object>(); + for (String key : inputs.keySet()) { + goldenInputs.put(key, inputs.get(key)); + } + } else { + // Build maps for the parameters (including aliases) to simplify checks + HashMap<String, HeatTemplateParam> params = new HashMap<String, HeatTemplateParam>(); + + Set<HeatTemplateParam> paramSet = heatTemplate.getParameters(); + logger.debug("paramSet has {} entries", paramSet.size()); + + for (HeatTemplateParam htp : paramSet) { + params.put(htp.getParamName(), htp); + + // Include aliases. + String alias = htp.getParamAlias(); + if (alias != null && !alias.equals("") && !params.containsKey(alias)) { + params.put(alias, htp); + } + } + + // First, convert all inputs to their "template" type + for (String key : inputs.keySet()) { + if (params.containsKey(key)) { + Object value = cloudifyUtils.convertInputValue(inputs.get(key), params.get(key)); + if (value != null) { + goldenInputs.put(key, value); + } else { + logger.debug("Failed to convert input " + key + "='" + inputs.get(key) + "' to " + + params.get(key).getParamType()); + } + } else { + extraInputs.add(key); + } + } + + if (!extraInputs.isEmpty()) { + logger.debug("Ignoring extra inputs: " + extraInputs); + } + + // Next add in Volume Group Outputs if there are any. Copy directly without conversions. + if (volumeGroupOutputs != null && !volumeGroupOutputs.isEmpty()) { + for (String key : volumeGroupOutputs.keySet()) { + if (params.containsKey(key) && !goldenInputs.containsKey(key)) { + goldenInputs.put(key, volumeGroupOutputs.get(key)); + } + } + } + + // Next add in Base Module Outputs if there are any. Copy directly without conversions. + if (baseModuleOutputs != null && !baseModuleOutputs.isEmpty()) { + for (String key : baseModuleOutputs.keySet()) { + if (params.containsKey(key) && !goldenInputs.containsKey(key)) { + goldenInputs.put(key, baseModuleOutputs.get(key)); + } + } + } + + // Last, add in values from the "environment" file. + // These are added to the inputs, since Cloudify doesn't pass an environment file like Heat. + + // TODO: This may take a different form for Cloudify, but for now process it + // with Heat environment file syntax StringBuilder sb = new StringBuilder(heatEnvironment.getEnvironment()); - MsoHeatEnvironmentEntry mhee = new MsoHeatEnvironmentEntry (sb); - - if (mhee.getParameters() != null) { - for (MsoHeatEnvironmentParameter envParam : mhee.getParameters()) { - // If this is a template input, copy to golden inputs - String envKey = envParam.getName(); - if (params.containsKey(envKey) && !goldenInputs.containsKey(envKey)) { - Object value = cloudifyUtils.convertInputValue(envParam.getValue(), params.get(envKey)); - if (value != null) { - goldenInputs.put(envKey, value); - } - else { - logger.debug("Failed to convert environment parameter " + envKey + "='" + envParam.getValue() + "' to " + - params.get(envKey).getParamType()); - } - } - } - } - - this.sendMapToDebug(goldenInputs, "Final inputs sent to Cloudify"); - - - // Check that required parameters have been supplied from any of the sources - String missingParams = null; - boolean checkRequiredParameters = true; - try { - String propertyString = this.environment.getProperty(MsoVnfCloudifyAdapterImpl.CHECK_REQD_PARAMS); - if ("false".equalsIgnoreCase (propertyString) || "n".equalsIgnoreCase (propertyString)) { - checkRequiredParameters = false; - logger.debug("CheckRequiredParameters is FALSE. Will still check but then skip blocking... {}", - MsoVnfCloudifyAdapterImpl.CHECK_REQD_PARAMS); - } - } catch (Exception e) { - // No problem - default is true - logger.debug("An exception occured trying to get property {}", - MsoVnfCloudifyAdapterImpl.CHECK_REQD_PARAMS, e); - } - - - for (HeatTemplateParam parm : heatTemplate.getParameters ()) { - if (parm.isRequired () && (!goldenInputs.containsKey (parm.getParamName ()))) { - logger.debug("adding to missing parameters list: {}", parm.getParamName()); - if (missingParams == null) { - missingParams = parm.getParamName(); - } else { - missingParams += "," + parm.getParamName(); - } - } - } - - if (missingParams != null) { - if (checkRequiredParameters) { - // Problem - missing one or more required parameters - String error = "Create VFModule: Missing Required inputs: " + missingParams; - logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, CLOUDIFY, - ErrorCode.DataError.getValue(), "Create VFModule: Missing Required inputs"); - logger.debug(error); - throw new VnfException(error, MsoExceptionCategory.USERDATA); - } else { - logger.debug( - "found missing parameters [" + missingParams + "] - but checkRequiredParameters is false -" - + " will not block"); - } - } else { - logger.debug("No missing parameters found - ok to proceed"); - } - - } // NOTE: END PARAMETER CHECKING - - // Ready to deploy the VF Module. - // *First step - make sure the blueprint is loaded into Cloudify. - String blueprintName = heatTemplate.getTemplateName(); - String blueprint = heatTemplate.getTemplateBody(); - String blueprintId = blueprintName; - - // Use the main blueprint name as the blueprint ID (strip yaml extensions). + MsoHeatEnvironmentEntry mhee = new MsoHeatEnvironmentEntry(sb); + + if (mhee.getParameters() != null) { + for (MsoHeatEnvironmentParameter envParam : mhee.getParameters()) { + // If this is a template input, copy to golden inputs + String envKey = envParam.getName(); + if (params.containsKey(envKey) && !goldenInputs.containsKey(envKey)) { + Object value = cloudifyUtils.convertInputValue(envParam.getValue(), params.get(envKey)); + if (value != null) { + goldenInputs.put(envKey, value); + } else { + logger.debug("Failed to convert environment parameter " + envKey + "='" + + envParam.getValue() + "' to " + params.get(envKey).getParamType()); + } + } + } + } + + this.sendMapToDebug(goldenInputs, "Final inputs sent to Cloudify"); + + + // Check that required parameters have been supplied from any of the sources + String missingParams = null; + boolean checkRequiredParameters = true; + try { + String propertyString = this.environment.getProperty(MsoVnfCloudifyAdapterImpl.CHECK_REQD_PARAMS); + if ("false".equalsIgnoreCase(propertyString) || "n".equalsIgnoreCase(propertyString)) { + checkRequiredParameters = false; + logger.debug("CheckRequiredParameters is FALSE. Will still check but then skip blocking... {}", + MsoVnfCloudifyAdapterImpl.CHECK_REQD_PARAMS); + } + } catch (Exception e) { + // No problem - default is true + logger.debug("An exception occured trying to get property {}", + MsoVnfCloudifyAdapterImpl.CHECK_REQD_PARAMS, e); + } + + + for (HeatTemplateParam parm : heatTemplate.getParameters()) { + if (parm.isRequired() && (!goldenInputs.containsKey(parm.getParamName()))) { + logger.debug("adding to missing parameters list: {}", parm.getParamName()); + if (missingParams == null) { + missingParams = parm.getParamName(); + } else { + missingParams += "," + parm.getParamName(); + } + } + } + + if (missingParams != null) { + if (checkRequiredParameters) { + // Problem - missing one or more required parameters + String error = "Create VFModule: Missing Required inputs: " + missingParams; + logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, CLOUDIFY, + ErrorCode.DataError.getValue(), "Create VFModule: Missing Required inputs"); + logger.debug(error); + throw new VnfException(error, MsoExceptionCategory.USERDATA); + } else { + logger.debug("found missing parameters [" + missingParams + + "] - but checkRequiredParameters is false -" + " will not block"); + } + } else { + logger.debug("No missing parameters found - ok to proceed"); + } + + } // NOTE: END PARAMETER CHECKING + + // Ready to deploy the VF Module. + // *First step - make sure the blueprint is loaded into Cloudify. + String blueprintName = heatTemplate.getTemplateName(); + String blueprint = heatTemplate.getTemplateBody(); + String blueprintId = blueprintName; + + // Use the main blueprint name as the blueprint ID (strip yaml extensions). if (blueprintId.endsWith(".yaml")) - blueprintId = blueprintId.substring(0,blueprintId.lastIndexOf(".yaml")); - - try { - if (! cloudifyUtils.isBlueprintLoaded (cloudSiteId, blueprintId)) { - logger.debug("Blueprint " + blueprintId + " is not loaded. Will upload it now."); - - Map<String,byte[]> blueprintFiles = new HashMap<String,byte[]>(); - - blueprintFiles.put(blueprintName, blueprint.getBytes()); - - // TODO: Implement nested blueprint logic based on Cloudify structures. - // For now, just use the Heat structures. - // The query returns a map of String->Object, where the map keys provide one layer of - // indirection from the Heat template names. For this case, assume the map key matches - // the nested blueprint name. - List<HeatTemplate> nestedBlueprints = heatTemplate.getChildTemplates(); - if (nestedBlueprints != null) { - for (HeatTemplate nestedBlueprint: nestedBlueprints) { - blueprintFiles.put(nestedBlueprint.getTemplateName(), nestedBlueprint.getTemplateBody().getBytes()); - } - } - - // TODO: Implement file artifact logic based on Cloudify structures. - // For now, just use the Heat structures. - List<HeatFiles> heatFiles = vf.getHeatFiles(); - if (heatFiles != null) { - for (HeatFiles heatFile: heatFiles) { - blueprintFiles.put(heatFile.getFileName(), heatFile.getFileBody().getBytes()); - } - } - - // Upload the blueprint package - cloudifyUtils.uploadBlueprint(cloudSiteId, blueprintId, blueprintName, blueprintFiles, false); - - } - } - - catch (MsoException me) { - me.addContext("CreateVFModule"); - String error = "Create VF Module: Upload blueprint failed. Blueprint=" + blueprintName + ": " + me; - logger.error("{} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudSiteId, - tenantId, CLOUDIFY, ErrorCode.DataError.getValue(), "MsoException - uploadBlueprint", me); - logger.debug(error); - throw new VnfException(me); - } + blueprintId = blueprintId.substring(0, blueprintId.lastIndexOf(".yaml")); + + try { + if (!cloudifyUtils.isBlueprintLoaded(cloudSiteId, blueprintId)) { + logger.debug("Blueprint " + blueprintId + " is not loaded. Will upload it now."); + + Map<String, byte[]> blueprintFiles = new HashMap<String, byte[]>(); + + blueprintFiles.put(blueprintName, blueprint.getBytes()); + + // TODO: Implement nested blueprint logic based on Cloudify structures. + // For now, just use the Heat structures. + // The query returns a map of String->Object, where the map keys provide one layer of + // indirection from the Heat template names. For this case, assume the map key matches + // the nested blueprint name. + List<HeatTemplate> nestedBlueprints = heatTemplate.getChildTemplates(); + if (nestedBlueprints != null) { + for (HeatTemplate nestedBlueprint : nestedBlueprints) { + blueprintFiles.put(nestedBlueprint.getTemplateName(), + nestedBlueprint.getTemplateBody().getBytes()); + } + } + + // TODO: Implement file artifact logic based on Cloudify structures. + // For now, just use the Heat structures. + List<HeatFiles> heatFiles = vf.getHeatFiles(); + if (heatFiles != null) { + for (HeatFiles heatFile : heatFiles) { + blueprintFiles.put(heatFile.getFileName(), heatFile.getFileBody().getBytes()); + } + } + + // Upload the blueprint package + cloudifyUtils.uploadBlueprint(cloudSiteId, blueprintId, blueprintName, blueprintFiles, false); + + } + } + + catch (MsoException me) { + me.addContext("CreateVFModule"); + String error = "Create VF Module: Upload blueprint failed. Blueprint=" + blueprintName + ": " + me; + logger.error("{} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, + cloudSiteId, tenantId, CLOUDIFY, ErrorCode.DataError.getValue(), + "MsoException - uploadBlueprint", me); + logger.debug(error); + throw new VnfException(me); + } // Ignore MsoTenantNotFound and MsoStackAlreadyExists exceptions // because we already checked for those. - long createDeploymentStarttime = System.currentTimeMillis (); + long createDeploymentStarttime = System.currentTimeMillis(); try { - // KLUDGE - Cloudify requires Tenant Name for Openstack. We have the ID. - // Go directly to Keystone until APIs could be updated to supply the name. - MsoTenant msoTenant = keystoneUtils.queryTenant(tenantId, cloudSiteId); - String tenantName = (msoTenant != null? msoTenant.getTenantName() : tenantId); - - if (backout == null) { - backout = true; - } - - cloudifyDeployment = cloudifyUtils.createAndInstallDeployment (cloudSiteId, - tenantName, - vfModuleName, - blueprintId, - goldenInputs, - true, - heatTemplate.getTimeoutMinutes (), - backout.booleanValue()); + // KLUDGE - Cloudify requires Tenant Name for Openstack. We have the ID. + // Go directly to Keystone until APIs could be updated to supply the name. + MsoTenant msoTenant = keystoneUtils.queryTenant(tenantId, cloudSiteId); + String tenantName = (msoTenant != null ? msoTenant.getTenantName() : tenantId); + + if (backout == null) { + backout = true; + } + + cloudifyDeployment = cloudifyUtils.createAndInstallDeployment(cloudSiteId, tenantName, vfModuleName, + blueprintId, goldenInputs, true, heatTemplate.getTimeoutMinutes(), backout.booleanValue()); } catch (MsoException me) { - me.addContext ("CreateVFModule"); - String error = "Create VF Module " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger - .error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, cloudSiteId, - tenantId, CLOUDIFY, ErrorCode.DataError.getValue(), "MsoException - createDeployment", - me); + me.addContext("CreateVFModule"); + String error = "Create VF Module " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + + tenantId + ": " + me; + logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, + cloudOwner, cloudSiteId, tenantId, CLOUDIFY, ErrorCode.DataError.getValue(), + "MsoException - createDeployment", me); logger.debug(error); - throw new VnfException (me); + throw new VnfException(me); } catch (NullPointerException npe) { - String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + npe; - logger - .error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, cloudSiteId, - tenantId, CLOUDIFY, ErrorCode.DataError.getValue(), + String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + + tenantId + ": " + npe; + logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, + cloudOwner, cloudSiteId, tenantId, CLOUDIFY, ErrorCode.DataError.getValue(), "NullPointerException - createDeployment", npe); logger.debug(error); logger.debug("NULL POINTER EXCEPTION at cloudify.createAndInstallDeployment"); - //npe.addContext ("CreateVNF"); - throw new VnfException ("NullPointerException during cloudify.createAndInstallDeployment"); + // npe.addContext ("CreateVNF"); + throw new VnfException("NullPointerException during cloudify.createAndInstallDeployment"); } catch (Exception e) { logger.debug("unhandled exception at cloudify.createAndInstallDeployment"); - throw new VnfException("Exception during cloudify.createAndInstallDeployment! " + e.getMessage()); + throw new VnfException("Exception during cloudify.createAndInstallDeployment! " + e.getMessage()); } } catch (Exception e) { - logger.debug("unhandled exception in create VF"); - throw new VnfException("Exception during create VF " + e.getMessage()); + logger.debug("unhandled exception in create VF"); + throw new VnfException("Exception during create VF " + e.getMessage()); } // Reach this point if create is successful. // Populate remaining rollback info and response parameters. - vfRollback.setVnfCreated (true); - vfRollback.setVnfId (cloudifyDeployment.getId()); + vfRollback.setVnfCreated(true); + vfRollback.setVnfId(cloudifyDeployment.getId()); vnfId.value = cloudifyDeployment.getId(); - outputs.value = copyStringOutputs (cloudifyDeployment.getOutputs ()); + outputs.value = copyStringOutputs(cloudifyDeployment.getOutputs()); rollback.value = vfRollback; @@ -1176,48 +1097,47 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { return; } - public void deleteVfModule (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfName, - MsoRequest msoRequest, - Holder <Map <String, String>> outputs) throws VnfException { - logger.debug ("Deleting VF " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId); + public void deleteVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, + MsoRequest msoRequest, Holder<Map<String, String>> outputs) throws VnfException { + logger.debug("Deleting VF " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId); // Will capture execution time for metrics - long startTime = System.currentTimeMillis (); + long startTime = System.currentTimeMillis(); // 1702 capture the output parameters on a delete // so we'll need to query first DeploymentInfo deployment = null; try { - deployment = cloudifyUtils.queryDeployment(cloudSiteId, tenantId, vnfName); + deployment = cloudifyUtils.queryDeployment(cloudSiteId, tenantId, vnfName); } catch (MsoException me) { - // Failed to query the deployment. Convert to a generic VnfException - me.addContext ("DeleteVFModule"); - String error = "Delete VFModule: Query to get outputs: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId, - tenantId, CLOUDIFY, "QueryDeployment", ErrorCode.DataError.getValue(), - "Exception - QueryDeployment", me); + // Failed to query the deployment. Convert to a generic VnfException + me.addContext("DeleteVFModule"); + String error = "Delete VFModule: Query to get outputs: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + + "/" + tenantId + ": " + me; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudOwner, + cloudSiteId, tenantId, CLOUDIFY, "QueryDeployment", ErrorCode.DataError.getValue(), + "Exception - QueryDeployment", me); logger.debug(error); - throw new VnfException (me); + throw new VnfException(me); } - // call method which handles the conversion from Map<String,Object> to Map<String,String> for our expected Object types + // call method which handles the conversion from Map<String,Object> to Map<String,String> for our expected + // Object types outputs.value = convertMapStringObjectToStringString(deployment.getOutputs()); // Use the MsoHeatUtils to delete the stack. Set the polling flag to true. // The possible outcomes of deleteStack are a StackInfo object with status // of NOTFOUND (on success) or FAILED (on error). Also, MsoOpenstackException // could be thrown. - long subStartTime = System.currentTimeMillis (); + long subStartTime = System.currentTimeMillis(); try { cloudifyUtils.uninstallAndDeleteDeployment(cloudSiteId, tenantId, vnfName, 5); } catch (MsoException me) { me.addContext("DeleteVfModule"); // Convert to a generic VnfException - String error = "Delete VF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId, - tenantId, "DeleteDeployment", "DeleteDeployment", ErrorCode.DataError.getValue(), - "Exception - DeleteDeployment: " + me.getMessage()); + String error = + "Delete VF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner, + cloudSiteId, tenantId, "DeleteDeployment", "DeleteDeployment", ErrorCode.DataError.getValue(), + "Exception - DeleteDeployment: " + me.getMessage()); logger.debug(error); throw new VnfException(me); } @@ -1226,27 +1146,16 @@ public class MsoVnfCloudifyAdapterImpl implements MsoVnfAdapter { return; } - // TODO: Should Update be supported for Cloudify? What would this look like? + // TODO: Should Update be supported for Cloudify? What would this look like? @Override - public void updateVfModule (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfType, - String vnfVersion, - String vnfName, - String requestType, - String volumeGroupHeatStackId, - String baseVfHeatStackId, - String vfModuleStackId, - String modelCustomizationUuid, - Map <String, Object> inputs, - MsoRequest msoRequest, - Holder <Map <String, String>> outputs, - Holder <VnfRollback> rollback) throws VnfException - { - // This operation is not currently supported for Cloudify-orchestrated VF Modules. - logger.debug("Update VF Module command attempted but not supported"); - throw new VnfException ("UpdateVfModule: Unsupported command", MsoExceptionCategory.USERDATA); - } + public void updateVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, + String vnfVersion, String vnfName, String requestType, String volumeGroupHeatStackId, + String baseVfHeatStackId, String vfModuleStackId, String modelCustomizationUuid, Map<String, Object> inputs, + MsoRequest msoRequest, Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback) + throws VnfException { + // This operation is not currently supported for Cloudify-orchestrated VF Modules. + logger.debug("Update VF Module command attempted but not supported"); + throw new VnfException("UpdateVfModule: Unsupported command", MsoExceptionCategory.USERDATA); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImpl.java index 82b194a973..7b48d0b07f 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImpl.java @@ -21,21 +21,15 @@ */ /** - * This VNF Adapter implementation is based on the VDU Plugin model. It assumes that each - * VF Module definition in the MSO catalog is expressed via a set of template and/or file - * artifacts that are appropriate for some specific sub-orchestrator that provides an - * implementation of the VduPlugin interface. This adapter handles all of the common - * VF Module logic, including: - * - catalog lookups for artifact retrieval - * - parameter filtering and validation - * - base and volume module queries - * - rollback logic - * - logging and error handling + * This VNF Adapter implementation is based on the VDU Plugin model. It assumes that each VF Module definition in the + * MSO catalog is expressed via a set of template and/or file artifacts that are appropriate for some specific + * sub-orchestrator that provides an implementation of the VduPlugin interface. This adapter handles all of the common + * VF Module logic, including: - catalog lookups for artifact retrieval - parameter filtering and validation - base and + * volume module queries - rollback logic - logging and error handling * - * Then based on the orchestration mode of the VNF, it will invoke different VDU plug-ins - * to perform the low level instantiations, deletions, and queries. At this time, the - * set of available plug-ins is hard-coded, though in the future a dynamic selection - * is expected (e.g. via a service-provider interface). + * Then based on the orchestration mode of the VNF, it will invoke different VDU plug-ins to perform the low level + * instantiations, deletions, and queries. At this time, the set of available plug-ins is hard-coded, though in the + * future a dynamic selection is expected (e.g. via a service-provider interface). */ package org.onap.so.adapters.vnf; @@ -46,10 +40,8 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; - import javax.jws.WebService; import javax.xml.ws.Holder; - import org.onap.so.adapters.vdu.CloudInfo; import org.onap.so.adapters.vdu.VduException; import org.onap.so.adapters.vdu.VduInstance; @@ -74,7 +66,6 @@ import org.onap.so.db.catalog.utils.MavenLikeVersioning; import org.onap.so.entity.MsoRequest; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; - import org.onap.so.openstack.beans.VnfRollback; import org.onap.so.openstack.beans.VnfStatus; import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; @@ -90,12 +81,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; - import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -@WebService(serviceName = "VnfAdapter", endpointInterface = "org.onap.so.adapters.vnf.MsoVnfAdapter", targetNamespace = "http://org.onap.so/vnf") +@WebService(serviceName = "VnfAdapter", endpointInterface = "org.onap.so.adapters.vnf.MsoVnfAdapter", + targetNamespace = "http://org.onap.so/vnf") @Component @Transactional public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { @@ -127,19 +118,20 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { @Autowired protected MsoMulticloudUtils multicloudUtils; - @Autowired - protected VfModuleCustomizationToVduMapper vduMapper; + @Autowired + protected VfModuleCustomizationToVduMapper vduMapper; - /** + /** * Health Check web method. Does nothing but return to show the adapter is deployed. */ @Override - public void healthCheck () { + public void healthCheck() { logger.debug("Health check call in VNF Plugin Adapter"); } /** * DO NOT use that constructor to instantiate this class, the msoPropertiesfactory will be NULL. + * * @see MsoVnfPluginAdapterImpl#MsoVnfAdapterImpl(MsoPropertiesFactory, CloudConfigFactory) */ public MsoVnfPluginAdapterImpl() { @@ -147,57 +139,31 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { } /** - * This is the "Create VNF" web service implementation. - * This function is now unsupported and will return an error. + * This is the "Create VNF" web service implementation. This function is now unsupported and will return an error. * */ @Override - public void createVnf (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfType, - String vnfVersion, - String vnfName, - String requestType, - String volumeGroupHeatStackId, - Map <String, Object> inputs, - Boolean failIfExists, - Boolean backout, - Boolean enableBridge, - MsoRequest msoRequest, - Holder <String> vnfId, - Holder <Map <String, String>> outputs, - Holder <VnfRollback> rollback) - throws VnfException - { - // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules. + public void createVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, String vnfVersion, + String vnfName, String requestType, String volumeGroupHeatStackId, Map<String, Object> inputs, + Boolean failIfExists, Boolean backout, Boolean enableBridge, MsoRequest msoRequest, Holder<String> vnfId, + Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback) throws VnfException { + // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules. logger.debug("CreateVNF command attempted but not supported"); throw new VnfException("CreateVNF: Unsupported command", MsoExceptionCategory.USERDATA); } /** - * This is the "Update VNF" web service implementation. - * This function is now unsupported and will return an error. + * This is the "Update VNF" web service implementation. This function is now unsupported and will return an error. * */ @Override - public void updateVnf (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfType, - String vnfVersion, - String vnfName, - String requestType, - String volumeGroupHeatStackId, - Map <String, Object> inputs, - MsoRequest msoRequest, - Holder <Map <String, String>> outputs, - Holder <VnfRollback> rollback) - throws VnfException - { - // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules. - logger.debug("UpdateVNF command attempted but not supported"); - throw new VnfException ("UpdateVNF: Unsupported command", MsoExceptionCategory.USERDATA); + public void updateVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, String vnfVersion, + String vnfName, String requestType, String volumeGroupHeatStackId, Map<String, Object> inputs, + MsoRequest msoRequest, Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback) + throws VnfException { + // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules. + logger.debug("UpdateVNF command attempted but not supported"); + throw new VnfException("UpdateVNF: Unsupported command", MsoExceptionCategory.USERDATA); } /** @@ -205,8 +171,8 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { * * This really should be QueryVfModule, but nobody ever changed it. * - * The method returns an indicator that the VNF exists, along with its status and outputs. - * The input "vnfName" will also be reflected back as its ID. + * The method returns an indicator that the VNF exists, along with its status and outputs. The input "vnfName" will + * also be reflected back as its ID. * * @param cloudSiteId CLLI code of the cloud site in which to query * @param tenantId Openstack tenant identifier @@ -217,92 +183,78 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { * @param outputs Holder for Map of outputs from the deployed VF Module (assigned IPs, etc) */ @Override - public void queryVnf (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfNameOrId, - MsoRequest msoRequest, - Holder <Boolean> vnfExists, - Holder <String> vnfId, - Holder <VnfStatus> status, - Holder <Map <String, String>> outputs) - throws VnfException - { + public void queryVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfNameOrId, + MsoRequest msoRequest, Holder<Boolean> vnfExists, Holder<String> vnfId, Holder<VnfStatus> status, + Holder<Map<String, String>> outputs) throws VnfException { logger.debug("Querying VNF " + vnfNameOrId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId); // Will capture execution time for metrics - long startTime = System.currentTimeMillis (); - long subStartTime = System.currentTimeMillis (); + long startTime = System.currentTimeMillis(); + long subStartTime = System.currentTimeMillis(); - VduInstance vduInstance = null; - CloudInfo cloudInfo = new CloudInfo(cloudSiteId, cloudOwner, tenantId, null); + VduInstance vduInstance = null; + CloudInfo cloudInfo = new CloudInfo(cloudSiteId, cloudOwner, tenantId, null); VduPlugin vduPlugin = getVduPlugin(cloudSiteId, cloudOwner); - try { - vduInstance = vduPlugin.queryVdu (cloudInfo, vnfNameOrId); - } - catch (VduException e) { - // Failed to query the VDU due to a plugin exception. - // Convert to a generic VnfException - e.addContext("QueryVNF"); - String error = "Query VNF (VDU): " + vnfNameOrId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + e; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfNameOrId, cloudOwner, cloudSiteId, - tenantId, "VDU", "QueryVNF", ErrorCode.DataError.getValue(), "Exception - queryVDU", e); - logger.debug(error); - throw new VnfException(e); - } - - if (vduInstance != null && vduInstance.getStatus().getState() != VduStateType.NOTFOUND) { - vnfExists.value = Boolean.TRUE; - status.value = vduStatusToVnfStatus(vduInstance); - vnfId.value = vduInstance.getVduInstanceId(); - outputs.value = copyStringOutputs(vduInstance.getOutputs()); - - logger.debug("VNF {} found, ID = {}", vnfNameOrId, vnfId.value); + try { + vduInstance = vduPlugin.queryVdu(cloudInfo, vnfNameOrId); + } catch (VduException e) { + // Failed to query the VDU due to a plugin exception. + // Convert to a generic VnfException + e.addContext("QueryVNF"); + String error = "Query VNF (VDU): " + vnfNameOrId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + + ": " + e; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfNameOrId, cloudOwner, + cloudSiteId, tenantId, "VDU", "QueryVNF", ErrorCode.DataError.getValue(), "Exception - queryVDU", + e); + logger.debug(error); + throw new VnfException(e); + } + + if (vduInstance != null && vduInstance.getStatus().getState() != VduStateType.NOTFOUND) { + vnfExists.value = Boolean.TRUE; + status.value = vduStatusToVnfStatus(vduInstance); + vnfId.value = vduInstance.getVduInstanceId(); + outputs.value = copyStringOutputs(vduInstance.getOutputs()); + + logger.debug("VNF {} found, ID = {}", vnfNameOrId, vnfId.value); + } else { + vnfExists.value = Boolean.FALSE; + status.value = VnfStatus.NOTFOUND; + vnfId.value = null; + outputs.value = new HashMap<String, String>(); // Return as an empty map + + logger.debug("VNF {} not found", vnfNameOrId); } - else { - vnfExists.value = Boolean.FALSE; - status.value = VnfStatus.NOTFOUND; - vnfId.value = null; - outputs.value = new HashMap<String, String>(); // Return as an empty map - - logger.debug("VNF {} not found", vnfNameOrId); - } return; } /** - * This is the "Delete VNF" web service implementation. - * This function is now unsupported and will return an error. + * This is the "Delete VNF" web service implementation. This function is now unsupported and will return an error. * */ @Override - public void deleteVnf (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfName, - MsoRequest msoRequest) throws VnfException { - - // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules. - logger.debug("DeleteVNF command attempted but not supported"); - throw new VnfException ("DeleteVNF: Unsupported command", MsoExceptionCategory.USERDATA); + public void deleteVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, MsoRequest msoRequest) + throws VnfException { + + // This operation is no longer supported at the VNF level. The adapter is only called to deploy modules. + logger.debug("DeleteVNF command attempted but not supported"); + throw new VnfException("DeleteVNF: Unsupported command", MsoExceptionCategory.USERDATA); } /** - * This web service endpoint will rollback a previous Create VNF operation. - * A rollback object is returned to the client in a successful creation - * response. The client can pass that object as-is back to the rollbackVnf - * operation to undo the creation. + * This web service endpoint will rollback a previous Create VNF operation. A rollback object is returned to the + * client in a successful creation response. The client can pass that object as-is back to the rollbackVnf operation + * to undo the creation. * - * TODO: This should be rollbackVfModule and/or rollbackVolumeGroup, - * but APIs were apparently never updated. + * TODO: This should be rollbackVfModule and/or rollbackVolumeGroup, but APIs were apparently never updated. */ @Override - public void rollbackVnf (VnfRollback rollback) throws VnfException { - long startTime = System.currentTimeMillis (); - // rollback may be null (e.g. if stack already existed when Create was called) + public void rollbackVnf(VnfRollback rollback) throws VnfException { + long startTime = System.currentTimeMillis(); + // rollback may be null (e.g. if stack already existed when Create was called) if (rollback == null) { logger.info("{} {} {}", MessageEnum.RA_ROLLBACK_NULL.toString(), "OpenStack", "rollbackVnf"); return; @@ -314,131 +266,127 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { } // Get the elements of the VnfRollback object for easier access - String cloudSiteId = rollback.getCloudSiteId (); + String cloudSiteId = rollback.getCloudSiteId(); String cloudOwner = rollback.getCloudOwner(); - String tenantId = rollback.getTenantId (); - CloudInfo cloudInfo = new CloudInfo (cloudSiteId, cloudOwner, tenantId, null); + String tenantId = rollback.getTenantId(); + CloudInfo cloudInfo = new CloudInfo(cloudSiteId, cloudOwner, tenantId, null); - String vfModuleId = rollback.getVfModuleStackId (); + String vfModuleId = rollback.getVfModuleStackId(); logger.debug("Rolling Back VF Module " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId); - VduInstance vduInstance = null; + VduInstance vduInstance = null; // Use the VduPlugin to delete the VF Module. VduPlugin vduPlugin = getVduPlugin(cloudSiteId, cloudOwner); - long subStartTime = System.currentTimeMillis (); + long subStartTime = System.currentTimeMillis(); try { - // TODO: Get a reasonable timeout. Use a global property, or store the creation timeout in rollback object and use that. + // TODO: Get a reasonable timeout. Use a global property, or store the creation timeout in rollback object + // and use that. vduInstance = vduPlugin.deleteVdu(cloudInfo, vfModuleId, 5); logger.debug("Rolled back VDU instantiation: {}", vduInstance.getVduInstanceId()); - } - catch (VduException ve) { + } catch (VduException ve) { // Failed to rollback the VF Module due to a plugin exception. // Convert to a generic VnfException - ve.addContext ("RollbackVFModule"); - String error = "Rollback VF Module: " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + ve; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vfModuleId, cloudOwner, cloudSiteId, - tenantId, "VDU", "DeleteVdu", ErrorCode.DataError.getValue(), "Exception - DeleteVdu", ve); + ve.addContext("RollbackVFModule"); + String error = "Rollback VF Module: " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + + tenantId + ": " + ve; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vfModuleId, cloudOwner, + cloudSiteId, tenantId, "VDU", "DeleteVdu", ErrorCode.DataError.getValue(), "Exception - DeleteVdu", + ve); logger.debug(error); - throw new VnfException (ve); + throw new VnfException(ve); } return; } - private VnfStatus vduStatusToVnfStatus (VduInstance vdu) { - // Determine the status based on last action & status - // DeploymentInfo object should be enhanced to report a better status internally. - VduStatus vduStatus = vdu.getStatus(); - VduStateType status = vduStatus.getState(); - - if (status == null) { - return VnfStatus.UNKNOWN; - } - else if (status == VduStateType.NOTFOUND) { - return VnfStatus.NOTFOUND; - } - else if (status == VduStateType.INSTANTIATED) { - return VnfStatus.ACTIVE; - } - else if (status == VduStateType.FAILED) { - return VnfStatus.FAILED; - } - - return VnfStatus.UNKNOWN; + private VnfStatus vduStatusToVnfStatus(VduInstance vdu) { + // Determine the status based on last action & status + // DeploymentInfo object should be enhanced to report a better status internally. + VduStatus vduStatus = vdu.getStatus(); + VduStateType status = vduStatus.getState(); + + if (status == null) { + return VnfStatus.UNKNOWN; + } else if (status == VduStateType.NOTFOUND) { + return VnfStatus.NOTFOUND; + } else if (status == VduStateType.INSTANTIATED) { + return VnfStatus.ACTIVE; + } else if (status == VduStateType.FAILED) { + return VnfStatus.FAILED; + } + + return VnfStatus.UNKNOWN; + } + + /* + * Normalize an input value to an Object, based on the target parameter type. If the type is not recognized, it will + * just be returned unchanged (as a string). + */ + private Object convertInputValue(Object inputValue, HeatTemplateParam templateParam) { + String type = templateParam.getParamType(); + logger.debug("Parameter: {} is of type ", templateParam.getParamName(), type); + + if (type.equalsIgnoreCase("number")) { + try { + return Integer.valueOf(inputValue.toString()); + } catch (Exception e) { + logger.debug("Unable to convert " + inputValue + " to an integer!", e); + return null; + } + } else if (type.equalsIgnoreCase("json")) { + try { + JsonNode jsonNode = JSON_MAPPER.readTree(JSON_MAPPER.writeValueAsString(inputValue)); + return jsonNode; + } catch (Exception e) { + logger.debug("Unable to convert " + inputValue + " to a JsonNode!", e); + return null; + } + } else if (type.equalsIgnoreCase("boolean")) { + return new Boolean(inputValue.toString()); + } + + // Nothing else matched. Return the original string + return inputValue; } - /* - * Normalize an input value to an Object, based on the target parameter type. - * If the type is not recognized, it will just be returned unchanged (as a string). - */ - private Object convertInputValue (Object inputValue, HeatTemplateParam templateParam) - { - String type = templateParam.getParamType(); - logger.debug("Parameter: {} is of type ", templateParam.getParamName(), type); - - if (type.equalsIgnoreCase("number")) { - try { - return Integer.valueOf(inputValue.toString()); - } - catch (Exception e) { - logger.debug("Unable to convert " + inputValue + " to an integer!" , e); - return null; - } - } else if (type.equalsIgnoreCase("json")) { - try { - JsonNode jsonNode = JSON_MAPPER.readTree(JSON_MAPPER.writeValueAsString(inputValue)); - return jsonNode; - } - catch (Exception e) { - logger.debug("Unable to convert " + inputValue + " to a JsonNode!", e); - return null; - } - } else if (type.equalsIgnoreCase("boolean")) { - return new Boolean(inputValue.toString()); - } - - // Nothing else matched. Return the original string - return inputValue; - } - - private Map <String, String> copyStringOutputs (Map <String, Object> stackOutputs) { - Map <String, String> stringOutputs = new HashMap <String, String> (); - for (String key : stackOutputs.keySet ()) { - if (stackOutputs.get (key) instanceof String) { - stringOutputs.put (key, (String) stackOutputs.get (key)); - } else if (stackOutputs.get(key) instanceof Integer) { - try { - String str = "" + stackOutputs.get(key); - stringOutputs.put(key, str); - } catch (Exception e) { - logger.debug("Unable to add {} to outputs", key, e); - } + private Map<String, String> copyStringOutputs(Map<String, Object> stackOutputs) { + Map<String, String> stringOutputs = new HashMap<String, String>(); + for (String key : stackOutputs.keySet()) { + if (stackOutputs.get(key) instanceof String) { + stringOutputs.put(key, (String) stackOutputs.get(key)); + } else if (stackOutputs.get(key) instanceof Integer) { + try { + String str = "" + stackOutputs.get(key); + stringOutputs.put(key, str); + } catch (Exception e) { + logger.debug("Unable to add {} to outputs", key, e); + } } else if (stackOutputs.get(key) instanceof JsonNode) { - try { - String str = this.convertNode((JsonNode) stackOutputs.get(key)); - stringOutputs.put(key, str); - } catch (Exception e) { - logger.debug("Unable to add {} to outputs - exception converting JsonNode", key, e); - } + try { + String str = this.convertNode((JsonNode) stackOutputs.get(key)); + stringOutputs.put(key, str); + } catch (Exception e) { + logger.debug("Unable to add {} to outputs - exception converting JsonNode", key, e); + } } else if (stackOutputs.get(key) instanceof java.util.LinkedHashMap) { - try { - String str = JSON_MAPPER.writeValueAsString(stackOutputs.get(key)); - stringOutputs.put(key, str); - } catch (Exception e) { - logger.debug("Unable to add {} to outputs - exception converting LinkedHashMap", key, e); - } + try { + String str = JSON_MAPPER.writeValueAsString(stackOutputs.get(key)); + stringOutputs.put(key, str); + } catch (Exception e) { + logger.debug("Unable to add {} to outputs - exception converting LinkedHashMap", key, e); + } } else { - try { - String str = stackOutputs.get(key).toString(); - stringOutputs.put(key, str); - } catch (Exception e) { - logger - .debug("Unable to add " + key + " to outputs - unable to call .toString() " + e.getMessage(), e); - } + try { + String str = stackOutputs.get(key).toString(); + stringOutputs.put(key, str); + } catch (Exception e) { + logger.debug("Unable to add " + key + " to outputs - unable to call .toString() " + e.getMessage(), + e); + } } } return stringOutputs; @@ -446,43 +394,41 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { private void sendMapToDebug(Map<String, Object> inputs, String optionalName) { - int i = 0; - StringBuilder sb = new StringBuilder(optionalName == null ? "\ninputs" : "\n" + optionalName); - if (inputs == null) { - sb.append("\tNULL"); - } - else if (inputs.size() < 1) { - sb.append("\tEMPTY"); - } else { - for (String str : inputs.keySet()) { - String outputString; - try { - outputString = inputs.get(str).toString(); - } catch (Exception e) { - outputString = "Unable to call toString() on the value for " + str; - } - sb.append("\t\nitem " + i++ + ": '" + str + "'='" + outputString + "'"); - } - } - logger.debug(sb.toString()); - return; + int i = 0; + StringBuilder sb = new StringBuilder(optionalName == null ? "\ninputs" : "\n" + optionalName); + if (inputs == null) { + sb.append("\tNULL"); + } else if (inputs.size() < 1) { + sb.append("\tEMPTY"); + } else { + for (String str : inputs.keySet()) { + String outputString; + try { + outputString = inputs.get(str).toString(); + } catch (Exception e) { + outputString = "Unable to call toString() on the value for " + str; + } + sb.append("\t\nitem " + i++ + ": '" + str + "'='" + outputString + "'"); + } + } + logger.debug(sb.toString()); + return; } private void sendMapToDebug(Map<String, Object> inputs) { - int i = 0; - StringBuilder sb = new StringBuilder("inputs:"); - if (inputs == null) { - sb.append("\tNULL"); - } - else if (inputs.size() < 1) { - sb.append("\tEMPTY"); - } else { - for (String str : inputs.keySet()) { - sb.append("\titem " + i++ + ": " + str + "=" + inputs.get(str)); - } - } - logger.debug(sb.toString()); - return; + int i = 0; + StringBuilder sb = new StringBuilder("inputs:"); + if (inputs == null) { + sb.append("\tNULL"); + } else if (inputs.size() < 1) { + sb.append("\tEMPTY"); + } else { + for (String str : inputs.keySet()) { + sb.append("\titem " + i++ + ": " + str + "=" + inputs.get(str)); + } + } + logger.debug(sb.toString()); + return; } private String convertNode(final JsonNode node) { @@ -508,15 +454,15 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { Object obj = objectMap.get(key); if (obj instanceof String) { stringMap.put(key, (String) objectMap.get(key)); - } else if (obj instanceof JsonNode ){ + } else if (obj 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 { String str = this.convertNode((JsonNode) obj); stringMap.put(key, str); } catch (Exception e) { - logger.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode "+ key, e); - //okay in this instance - only string values (fqdn) are expected to be needed + logger.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode " + key, e); + // okay in this instance - only string values (fqdn) are expected to be needed } } else if (obj instanceof java.util.LinkedHashMap) { logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode"); @@ -524,21 +470,23 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { String str = JSON_MAPPER.writeValueAsString(obj); stringMap.put(key, str); } catch (Exception e) { - logger.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap "+ key, e); - } - } else if (obj instanceof Integer) { - try { - String str = "" + obj; - stringMap.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 LinkedHashMap " + key, e); + } + } else if (obj instanceof Integer) { + try { + String str = "" + obj; + stringMap.put(key, str); + } catch (Exception e) { + logger.debug("DANGER WILL ROBINSON: unable to convert value for Integer " + key, e); } } else { try { - String str = obj.toString(); + String str = obj.toString(); stringMap.put(key, str); } catch (Exception e) { - logger.debug("DANGER WILL ROBINSON: unable to convert value "+ key + " (" + e.getMessage() + ")", e); + logger.debug( + "DANGER WILL ROBINSON: unable to convert value " + key + " (" + e.getMessage() + ")", + e); } } } @@ -548,44 +496,37 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { } /** - * This is the "Create VF Module" web service implementation. - * It will instantiate a new VF Module of the requested type in the specified cloud - * and tenant. The tenant must exist before this service is called. + * This is the "Create VF Module" web service implementation. It will instantiate a new VF Module of the requested + * type in the specified cloud and tenant. The tenant must exist before this service is called. * - * If a VF Module with the same name already exists, this can be considered a - * success or failure, depending on the value of the 'failIfExists' parameter. + * If a VF Module with the same name already exists, this can be considered a success or failure, depending on the + * value of the 'failIfExists' parameter. * - * All VF Modules are defined in the MSO catalog. The caller must request one of - * the pre-defined module types or an error will be returned. Within the catalog, - * each VF Module references (among other things) a collection of artifacts that - * are used to deploy the required cloud resources (VMs, networks, etc.). + * All VF Modules are defined in the MSO catalog. The caller must request one of the pre-defined module types or an + * error will be returned. Within the catalog, each VF Module references (among other things) a collection of + * artifacts that are used to deploy the required cloud resources (VMs, networks, etc.). * - * Depending on the module templates, a variable set of input parameters will - * be defined, some of which are required. The caller is responsible to - * pass the necessary input data for the module or an error will be thrown. + * Depending on the module templates, a variable set of input parameters will be defined, some of which are + * required. The caller is responsible to pass the necessary input data for the module or an error will be thrown. * - * The method returns the vfModuleId, a Map of output attributes, and a VnfRollback - * object. This last object can be passed as-is to the rollbackVnf operation to - * undo everything that was created for the Module. This is useful if a VF module - * is successfully created but the orchestration fails on a subsequent step. + * The method returns the vfModuleId, a Map of output attributes, and a VnfRollback object. This last object can be + * passed as-is to the rollbackVnf operation to undo everything that was created for the Module. This is useful if a + * VF module is successfully created but the orchestration fails on a subsequent step. * * @param cloudSiteId CLLI code of the cloud site in which to create the VNF * @param cloudOwner cloud owner of the cloud site in which to create the VNF * @param tenantId Openstack tenant identifier - * @param vfModuleType VF Module type key, should match a VNF definition in catalog DB. - * Deprecated - should use modelCustomizationUuid - * @param vnfVersion VNF version key, should match a VNF definition in catalog DB - * Deprecated - VF Module versions also captured by modelCustomizationUuid + * @param vfModuleType VF Module type key, should match a VNF definition in catalog DB. Deprecated - should use + * modelCustomizationUuid + * @param vnfVersion VNF version key, should match a VNF definition in catalog DB Deprecated - VF Module versions + * also captured by modelCustomizationUuid * @param vnfId - VNF ID * @param vfModuleName Name to be assigned to the new VF Module * @param vfModuleId Id fo the new VF Module * @param requestType Indicates if this is a Volume Group or Module request - * @param volumeGroupId Identifier (i.e. deployment ID) for a Volume Group - * to attach to a VF Module - * @param baseVfModuleId Identifier (i.e. deployment ID) of the Base Module if - * this is an Add-on module - * @param modelCustomizationUuid Unique ID for the VF Module's model. Replaces - * the use of vfModuleType. + * @param volumeGroupId Identifier (i.e. deployment ID) for a Volume Group to attach to a VF Module + * @param baseVfModuleId Identifier (i.e. deployment ID) of the Base Module if this is an Add-on module + * @param modelCustomizationUuid Unique ID for the VF Module's model. Replaces the use of vfModuleType. * @param inputs Map of key=value inputs for VNF stack creation * @param failIfExists Flag whether already existing VNF should be considered * @param backout Flag whether to suppress automatic backout (for testing) @@ -595,68 +536,51 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { * @param rollback Holder for returning VnfRollback object */ @Override - public void createVfModule(String cloudSiteId, - String cloudOwner, - String tenantId, - String vfModuleType, - String vnfVersion, - String genericVnfId, - String vfModuleName, - String vfModuleId, - String requestType, - String volumeGroupId, - String baseVfModuleId, - String modelCustomizationUuid, - Map <String, Object> inputs, - Boolean failIfExists, - Boolean backout, - Boolean enableBridge, - MsoRequest msoRequest, - Holder <String> vnfId, - Holder <Map <String, String>> outputs, - Holder <VnfRollback> rollback) - throws VnfException - { + public void createVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vfModuleType, + String vnfVersion, String genericVnfId, String vfModuleName, String vfModuleId, String requestType, + String volumeGroupId, String baseVfModuleId, String modelCustomizationUuid, Map<String, Object> inputs, + Boolean failIfExists, Boolean backout, Boolean enableBridge, MsoRequest msoRequest, Holder<String> vnfId, + Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback) throws VnfException { // Will capture execution time for metrics - long startTime = System.currentTimeMillis (); + long startTime = System.currentTimeMillis(); - // Require a model customization ID. Every VF Module definition must have one. - if (modelCustomizationUuid == null || modelCustomizationUuid.isEmpty()) { + // Require a model customization ID. Every VF Module definition must have one. + if (modelCustomizationUuid == null || modelCustomizationUuid.isEmpty()) { logger.debug("Missing required input: modelCustomizationUuid"); String error = "Create vfModule error: Missing required input: modelCustomizationUuid"; logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), - "VF Module ModelCustomizationUuid", "VDU", ErrorCode.DataError, - "Create VF Module: " + "Missing required input: modelCustomizationUuid"); + "VF Module ModelCustomizationUuid", "VDU", ErrorCode.DataError, + "Create VF Module: " + "Missing required input: modelCustomizationUuid"); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); } // Clean up some inputs to make comparisons easier if (requestType == null) - requestType = ""; + requestType = ""; if ("".equals(volumeGroupId) || "null".equals(volumeGroupId)) - volumeGroupId = null; + volumeGroupId = null; if ("".equals(baseVfModuleId) || "null".equals(baseVfModuleId)) - baseVfModuleId = null; + baseVfModuleId = null; if (inputs == null) { - // Create an empty set of inputs - inputs = new HashMap<>(); - logger.debug("inputs == null - setting to empty"); + // Create an empty set of inputs + inputs = new HashMap<>(); + logger.debug("inputs == null - setting to empty"); } else { - this.sendMapToDebug(inputs); + this.sendMapToDebug(inputs); } // Check if this is for a "Volume" module boolean isVolumeRequest = false; if (requestType.startsWith("VOLUME")) { - isVolumeRequest = true; + isVolumeRequest = true; } - logger.debug("requestType = " + requestType + ", volumeGroupStackId = " + volumeGroupId + ", baseStackId = " + - baseVfModuleId); + logger.debug("requestType = " + requestType + ", volumeGroupStackId = " + volumeGroupId + ", baseStackId = " + + baseVfModuleId); // Build a default rollback object (no actions performed) VnfRollback vfRollback = new VnfRollback(); @@ -665,69 +589,70 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { vfRollback.setTenantId(tenantId); vfRollback.setMsoRequest(msoRequest); vfRollback.setRequestType(requestType); - vfRollback.setIsBase(false); // Until we know better + vfRollback.setIsBase(false); // Until we know better vfRollback.setVolumeGroupHeatStackId(volumeGroupId); vfRollback.setBaseGroupHeatStackId(baseVfModuleId); vfRollback.setModelCustomizationUuid(modelCustomizationUuid); vfRollback.setMode("CFY"); - rollback.value = vfRollback; // Default rollback - no updates performed + rollback.value = vfRollback; // Default rollback - no updates performed // Get the VNF/VF Module definition from the Catalog DB first. - // There are three relevant records: VfModule, VfModuleCustomization, VnfResource + // There are three relevant records: VfModule, VfModuleCustomization, VnfResource VfModule vfModule = null; - VnfResource vnfResource = null; - VfModuleCustomization vfModuleCust = null; + VnfResource vnfResource = null; + VfModuleCustomization vfModuleCust = null; try { - vfModuleCust = vfModuleCustomRepo.findFirstByModelCustomizationUUIDOrderByCreatedDesc(modelCustomizationUuid); + vfModuleCust = + vfModuleCustomRepo.findFirstByModelCustomizationUUIDOrderByCreatedDesc(modelCustomizationUuid); if (vfModuleCust == null) { String error = "Create vfModule error: Unable to find vfModuleCust with modelCustomizationUuid=" - + modelCustomizationUuid; + + modelCustomizationUuid; logger.debug(error); logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), - "VF Module ModelCustomizationUuid", modelCustomizationUuid, "CatalogDb", - ErrorCode.DataError, error); + "VF Module ModelCustomizationUuid", modelCustomizationUuid, "CatalogDb", ErrorCode.DataError, + error); throw new VnfException(error, MsoExceptionCategory.USERDATA); } else { logger.debug("Found vfModuleCust entry {}", vfModuleCust.toString()); } // Get the vfModule and vnfResource records - vfModule = vfModuleCust.getVfModule(); - vnfResource = vfModuleCust.getVfModule().getVnfResources(); - } - catch (Exception e) { + vfModule = vfModuleCust.getVfModule(); + vnfResource = vfModuleCust.getVfModule().getVnfResources(); + } catch (Exception e) { - logger.debug("unhandled exception in create VF - [Query]" + e.getMessage()); - throw new VnfException("Exception during create VF " + e.getMessage()); + logger.debug("unhandled exception in create VF - [Query]" + e.getMessage()); + throw new VnfException("Exception during create VF " + e.getMessage()); } // Perform a version check against cloudSite // Obtain the cloud site information where we will create the VF Module - Optional<CloudSite> cloudSiteOp = cloudConfig.getCloudSite (cloudSiteId); + Optional<CloudSite> cloudSiteOp = cloudConfig.getCloudSite(cloudSiteId); if (!cloudSiteOp.isPresent()) { // If cloudSiteId is not present in the catalog DB, then default to multicloud - logger.debug("{} is not present in cloud_site catalog DB, defaulting to Multicloud plugin adapter", cloudSiteId); + logger.debug("{} is not present in cloud_site catalog DB, defaulting to Multicloud plugin adapter", + cloudSiteId); } else { CloudSite cloudSite = cloudSiteOp.get(); - MavenLikeVersioning aicV = new MavenLikeVersioning(); - aicV.setVersion(cloudSite.getCloudVersion()); + MavenLikeVersioning aicV = new MavenLikeVersioning(); + aicV.setVersion(cloudSite.getCloudVersion()); - String vnfMin = vnfResource.getAicVersionMin(); - String vnfMax = vnfResource.getAicVersionMax(); + String vnfMin = vnfResource.getAicVersionMin(); + String vnfMax = vnfResource.getAicVersionMax(); - if ((vnfMin != null && !(aicV.isMoreRecentThan(vnfMin) || aicV.isTheSameVersion(vnfMin))) || (vnfMax != null - && aicV.isMoreRecentThan(vnfMax))) { + if ((vnfMin != null && !(aicV.isMoreRecentThan(vnfMin) || aicV.isTheSameVersion(vnfMin))) + || (vnfMax != null && aicV.isMoreRecentThan(vnfMax))) { // ERROR String error = - "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUUID() - + " VersionMin=" + vnfMin + " VersionMax:" + vnfMax + " NOT supported on Cloud: " + cloudSiteId - + " with AIC_Version:" + cloudSite.getCloudVersion(); + "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUUID() + + " VersionMin=" + vnfMin + " VersionMax:" + vnfMax + " NOT supported on Cloud: " + + cloudSiteId + " with AIC_Version:" + cloudSite.getCloudVersion(); logger.error("{} {} {} {} {}", MessageEnum.RA_CONFIG_EXC.toString(), error, "OpenStack", - ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion"); + ErrorCode.BusinessProcesssError.getValue(), "Exception - setVersion"); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); } @@ -736,42 +661,43 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { VduInstance vduInstance = null; - CloudInfo cloudInfo = new CloudInfo (cloudSiteId, cloudOwner, tenantId, null); + CloudInfo cloudInfo = new CloudInfo(cloudSiteId, cloudOwner, tenantId, null); // Use the VduPlugin. VduPlugin vduPlugin = getVduPlugin(cloudSiteId, cloudOwner); - long subStartTime1 = System.currentTimeMillis (); + long subStartTime1 = System.currentTimeMillis(); try { - vduInstance = vduPlugin.queryVdu (cloudInfo, vfModuleName); - } - catch (VduException me) { + vduInstance = vduPlugin.queryVdu(cloudInfo, vfModuleName); + } catch (VduException me) { // Failed to query the VDU due to a plugin exception. - String error = "Create VF Module: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ; + String error = "Create VF Module: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/" + + tenantId + ": " + me; logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), - "Exception - queryVdu", me); + cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), + "Exception - queryVdu", me); logger.debug(error); // Convert to a generic VnfException - me.addContext ("CreateVFModule"); - throw new VnfException (me); + me.addContext("CreateVFModule"); + throw new VnfException(me); } // More precise handling/messaging if the Module already exists if (vduInstance != null && !(vduInstance.getStatus().getState() == VduStateType.NOTFOUND)) { - VduStateType status = vduInstance.getStatus().getState(); + VduStateType status = vduInstance.getStatus().getState(); logger.debug("Found Existing VDU, status=" + status); if (status == VduStateType.INSTANTIATED) { if (failIfExists != null && failIfExists) { // fail - it exists - String error = - "Create VF: Deployment " + vfModuleName + " already exists in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), - "VF Module " + vfModuleName + " already exists"); + String error = "Create VF: Deployment " + vfModuleName + " already exists in " + cloudOwner + "/" + + cloudSiteId + "/" + tenantId; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), + vfModuleName, cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", + ErrorCode.DataError.getValue(), "VF Module " + vfModuleName + " already exists"); logger.debug(error); - throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, vduInstance.getVduInstanceId()); + throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, + vduInstance.getVduInstanceId()); } else { // Found existing deployment and client has not requested "failIfExists". // Populate the outputs from the existing deployment. @@ -783,46 +709,49 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { } // Check through various detailed error cases else if (status == VduStateType.INSTANTIATING || status == VduStateType.DELETING - || status == VduStateType.UPDATING) { + || status == VduStateType.UPDATING) { // fail - it's in progress - return meaningful error - String error = - "Create VF: Deployment " + vfModuleName + " already exists and has status " + status.toString() - + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; please wait for it to complete, or fix manually."; + String error = "Create VF: Deployment " + vfModuleName + " already exists and has status " + + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + + "; please wait for it to complete, or fix manually."; logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), - "VF Module " + vfModuleName + " already exists"); + cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), + "VF Module " + vfModuleName + " already exists"); logger.debug(error); - throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, vduInstance.getVduInstanceId()); + throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, + vduInstance.getVduInstanceId()); } else if (status == VduStateType.FAILED) { // fail - it exists and is in a FAILED state - String error = - "Create VF: Deployment " + vfModuleName + " already exists and is in FAILED state in " + cloudOwner + "/" + cloudSiteId - + "/" + tenantId + "; requires manual intervention."; + String error = "Create VF: Deployment " + vfModuleName + " already exists and is in FAILED state in " + + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention."; logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), - "VF Module " + vfModuleName + " already exists and is in FAILED state"); + cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), + "VF Module " + vfModuleName + " already exists and is in FAILED state"); logger.debug(error); - throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, vduInstance.getVduInstanceId()); + throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, + vduInstance.getVduInstanceId()); } else if (status == VduStateType.UNKNOWN) { // fail - it exists and is in a UNKNOWN state - String error = - "Create VF: Deployment " + vfModuleName + " already exists and has status " + status.toString() - + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention."; + String error = "Create VF: Deployment " + vfModuleName + " already exists and has status " + + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + + "; requires manual intervention."; logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), - "VF Module " + vfModuleName + " already exists and is in " + status.toString() + " state"); + cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), + "VF Module " + vfModuleName + " already exists and is in " + status.toString() + " state"); logger.debug(error); - throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, vduInstance.getVduInstanceId()); + throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, + vduInstance.getVduInstanceId()); } else { // Unexpected, since all known status values have been tested for - String error = - "Create VF: Deployment " + vfModuleName + " already exists with unexpected status " + status - .toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention."; + String error = "Create VF: Deployment " + vfModuleName + " already exists with unexpected status " + + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + + "; requires manual intervention."; logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), - "VF Module " + vfModuleName + " already exists and is in an unknown state"); + cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu", ErrorCode.DataError.getValue(), + "VF Module " + vfModuleName + " already exists and is in an unknown state"); logger.debug(error); - throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, vduInstance.getVduInstanceId()); + throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, + vduInstance.getVduInstanceId()); } } @@ -833,41 +762,42 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { // If a Volume Group was provided, query its outputs for inclusion in Module input parameters if (volumeGroupId != null) { - long subStartTime2 = System.currentTimeMillis (); + long subStartTime2 = System.currentTimeMillis(); VduInstance volumeVdu = null; try { - volumeVdu = vduPlugin.queryVdu (cloudInfo, volumeGroupId); - } - catch (VduException me) { + volumeVdu = vduPlugin.queryVdu(cloudInfo, volumeGroupId); + } catch (VduException me) { // Failed to query the Volume Group VDU due to a plugin exception. - String error = "Create VF Module: Query Volume Group " + volumeGroupId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ; + String error = "Create VF Module: Query Volume Group " + volumeGroupId + " in " + cloudOwner + "/" + + cloudSiteId + "/" + tenantId + ": " + me; logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId, - cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu(volume)", ErrorCode.DataError.getValue(), - "Exception - queryVdu(volume)", me); + cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu(volume)", ErrorCode.DataError.getValue(), + "Exception - queryVdu(volume)", me); logger.debug(error); // Convert to a generic VnfException - me.addContext ("CreateVFModule(QueryVolume)"); - throw new VnfException (me); + me.addContext("CreateVFModule(QueryVolume)"); + throw new VnfException(me); } - if (volumeVdu == null || volumeVdu.getStatus().getState() == VduStateType.NOTFOUND) { - String error = "Create VFModule: Attached Volume Group DOES NOT EXIST " + volumeGroupId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR" ; - logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId, - cloudOwner, cloudSiteId, tenantId, error, "VDU", "queryVdu(volume)", - ErrorCode.BusinessProcesssError.getValue(), - "Create VFModule: Attached Volume Group " + "DOES NOT EXIST"); - logger.debug(error); - throw new VnfException (error, MsoExceptionCategory.USERDATA); - } else { - logger.debug("Found nested volume group"); - volumeGroupOutputs = volumeVdu.getOutputs(); - this.sendMapToDebug(volumeGroupOutputs, "volumeGroupOutputs"); - } + if (volumeVdu == null || volumeVdu.getStatus().getState() == VduStateType.NOTFOUND) { + String error = "Create VFModule: Attached Volume Group DOES NOT EXIST " + volumeGroupId + " in " + + cloudOwner + "/" + cloudSiteId + "/" + tenantId + " USER ERROR"; + logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId, + cloudOwner, cloudSiteId, tenantId, error, "VDU", "queryVdu(volume)", + ErrorCode.BusinessProcesssError.getValue(), + "Create VFModule: Attached Volume Group " + "DOES NOT EXIST"); + logger.debug(error); + throw new VnfException(error, MsoExceptionCategory.USERDATA); + } else { + logger.debug("Found nested volume group"); + volumeGroupOutputs = volumeVdu.getOutputs(); + this.sendMapToDebug(volumeGroupOutputs, "volumeGroupOutputs"); + } } // If this is an Add-On Module, query the Base Module outputs // Note: This will be performed whether or not the current request is for an - // Add-On Volume Group or Add-On VF Module + // Add-On Volume Group or Add-On VF Module if (vfModule.getIsBase()) { logger.debug("This is a BASE Module request"); @@ -882,31 +812,29 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { } if (baseVfModuleId != null) { - long subStartTime2 = System.currentTimeMillis (); - VduInstance baseVdu = null; - try { - baseVdu = vduPlugin.queryVdu (cloudInfo, baseVfModuleId); - } - catch (MsoException me) { - // Failed to query the Base VF Module due to a Vdu Plugin exception. - String error = "Create VF Module: Query Base " + baseVfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me ; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId, - cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu(Base)", ErrorCode.DataError.getValue(), - "Exception - queryVdu(Base)", me); - logger.debug(error); - // Convert to a generic VnfException - me.addContext ("CreateVFModule(QueryBase)"); - throw new VnfException (me); - } + long subStartTime2 = System.currentTimeMillis(); + VduInstance baseVdu = null; + try { + baseVdu = vduPlugin.queryVdu(cloudInfo, baseVfModuleId); + } catch (MsoException me) { + // Failed to query the Base VF Module due to a Vdu Plugin exception. + String error = "Create VF Module: Query Base " + baseVfModuleId + " in " + cloudOwner + "/" + + cloudSiteId + "/" + tenantId + ": " + me; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId, + cloudOwner, cloudSiteId, tenantId, "VDU", "queryVdu(Base)", ErrorCode.DataError.getValue(), + "Exception - queryVdu(Base)", me); + logger.debug(error); + // Convert to a generic VnfException + me.addContext("CreateVFModule(QueryBase)"); + throw new VnfException(me); + } if (baseVdu == null || baseVdu.getStatus().getState() == VduStateType.NOTFOUND) { - String error = - "Create VFModule: Base Module DOES NOT EXIST " + baseVfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" - + tenantId + " USER ERROR"; - logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId, - cloudOwner, cloudSiteId, tenantId, error, "VDU", "queryVdu(Base)", - ErrorCode.BusinessProcesssError.getValue(), - "Create VFModule: Base Module DOES NOT EXIST"); + String error = "Create VFModule: Base Module DOES NOT EXIST " + baseVfModuleId + " in " + cloudOwner + + "/" + cloudSiteId + "/" + tenantId + " USER ERROR"; + logger.error("{} {} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), + baseVfModuleId, cloudOwner, cloudSiteId, tenantId, error, "VDU", "queryVdu(Base)", + ErrorCode.BusinessProcesssError.getValue(), "Create VFModule: Base Module DOES NOT EXIST"); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); } else { @@ -918,27 +846,27 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { } - // NOTE: For this section, heatTemplate is used for all template artifacts. + // NOTE: For this section, heatTemplate is used for all template artifacts. // In final implementation (post-POC), the template object would either be generic or there would // be a separate DB Table/Object for different sub-orchestrators. - // NOTE: The template is fixed for the VF Module. The environment is part of the customization. + // NOTE: The template is fixed for the VF Module. The environment is part of the customization. HeatTemplate heatTemplate = null; HeatEnvironment heatEnvironment = null; if (isVolumeRequest) { - heatTemplate = vfModule.getVolumeHeatTemplate(); - heatEnvironment = vfModuleCust.getVolumeHeatEnv(); - } else { - heatTemplate = vfModule.getModuleHeatTemplate(); - heatEnvironment = vfModuleCust.getHeatEnvironment(); - } - - if (heatTemplate == null) { - String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType + ", reqType=" - + requestType; - logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", vfModuleType, - "VNF", ErrorCode.DataError.getValue(), error); + heatTemplate = vfModule.getVolumeHeatTemplate(); + heatEnvironment = vfModuleCust.getVolumeHeatEnv(); + } else { + heatTemplate = vfModule.getModuleHeatTemplate(); + heatEnvironment = vfModuleCust.getHeatEnvironment(); + } + + if (heatTemplate == null) { + String error = "UpdateVF: No Heat Template ID defined in catalog database for " + vfModuleType + + ", reqType=" + requestType; + logger.error("{} {} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Template ID", + vfModuleType, "VNF", ErrorCode.DataError.getValue(), error); logger.debug(error); throw new VnfException(error, MsoExceptionCategory.INTERNAL); } else { @@ -948,7 +876,7 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { if (heatEnvironment == null) { String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType; logger.error("{} {} {} {} {}", MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID", - "OpenStack", ErrorCode.DataError.getValue(), error); + "OpenStack", ErrorCode.DataError.getValue(), error); throw new VnfException(error, MsoExceptionCategory.INTERNAL); } else { logger.debug("Got Heat Environment from DB: " + heatEnvironment.getEnvironment()); @@ -956,152 +884,150 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { // Create the combined set of parameters from the incoming request, base-module outputs, - // volume-module outputs. Also, convert all variables to their native object types. + // volume-module outputs. Also, convert all variables to their native object types. - HashMap<String, Object> goldenInputs = new HashMap<String,Object>(); + HashMap<String, Object> goldenInputs = new HashMap<String, Object>(); List<String> extraInputs = new ArrayList<String>(); - Boolean skipInputChecks = false; - - if (skipInputChecks) { - goldenInputs = new HashMap<String,Object>(); - for (String key : inputs.keySet()) { - goldenInputs.put(key, inputs.get(key)); - } - } - else { - // Build maps for the parameters (including aliases) to simplify checks - HashMap<String, HeatTemplateParam> params = new HashMap<String, HeatTemplateParam>(); - - Set<HeatTemplateParam> paramSet = heatTemplate.getParameters(); - logger.debug("paramSet has " + paramSet.size() + " entries"); - - for (HeatTemplateParam htp : paramSet) { - params.put(htp.getParamName(), htp); - - // Include aliases. - String alias = htp.getParamAlias(); - if (alias != null && !alias.equals("") && !params.containsKey(alias)) { - params.put(alias, htp); - } - } - - // First, convert all inputs to their "template" type - for (String key : inputs.keySet()) { - if (params.containsKey(key)) { - Object value = convertInputValue(inputs.get(key), params.get(key)); - if (value != null) { - goldenInputs.put(key, value); - } - else { - logger.debug("Failed to convert input " + key + "='" + inputs.get(key) + "' to " + params.get(key) - .getParamType()); - } - } else { - extraInputs.add(key); - } - } - - if (!extraInputs.isEmpty()) { - // Add multicloud inputs - for (String key : MsoMulticloudUtils.MULTICLOUD_INPUTS) { - if (extraInputs.contains(key)) { - goldenInputs.put(key, inputs.get(key)); - extraInputs.remove(key); - if (extraInputs.isEmpty()) { - break; - } - } - } - logger.debug("Ignoring extra inputs: " + extraInputs); - } - - // Next add in Volume Group Outputs if there are any. Copy directly without conversions. - if (volumeGroupOutputs != null && !volumeGroupOutputs.isEmpty()) { - for (String key : volumeGroupOutputs.keySet()) { - if (params.containsKey(key) && !goldenInputs.containsKey(key)) { - goldenInputs.put(key, volumeGroupOutputs.get(key)); - } - } - } - - // Next add in Base Module Outputs if there are any. Copy directly without conversions. - if (baseModuleOutputs != null && !baseModuleOutputs.isEmpty()) { - for (String key : baseModuleOutputs.keySet()) { - if (params.containsKey(key) && !goldenInputs.containsKey(key)) { - goldenInputs.put(key, baseModuleOutputs.get(key)); - } - } - } - - // TODO: The model should support a mechanism to pre-assign default parameter values - // per "customization" (i.e. usage) of a given module. In HEAT, this is specified by - // an Environment file. There is not a general mechanism in the model to handle this. - // For the general case, any such parameter/values can be added dynamically to the - // inputs (only if not already specified). + Boolean skipInputChecks = false; + + if (skipInputChecks) { + goldenInputs = new HashMap<String, Object>(); + for (String key : inputs.keySet()) { + goldenInputs.put(key, inputs.get(key)); + } + } else { + // Build maps for the parameters (including aliases) to simplify checks + HashMap<String, HeatTemplateParam> params = new HashMap<String, HeatTemplateParam>(); + + Set<HeatTemplateParam> paramSet = heatTemplate.getParameters(); + logger.debug("paramSet has " + paramSet.size() + " entries"); + + for (HeatTemplateParam htp : paramSet) { + params.put(htp.getParamName(), htp); + + // Include aliases. + String alias = htp.getParamAlias(); + if (alias != null && !alias.equals("") && !params.containsKey(alias)) { + params.put(alias, htp); + } + } + + // First, convert all inputs to their "template" type + for (String key : inputs.keySet()) { + if (params.containsKey(key)) { + Object value = convertInputValue(inputs.get(key), params.get(key)); + if (value != null) { + goldenInputs.put(key, value); + } else { + logger.debug("Failed to convert input " + key + "='" + inputs.get(key) + "' to " + + params.get(key).getParamType()); + } + } else { + extraInputs.add(key); + } + } + + if (!extraInputs.isEmpty()) { + // Add multicloud inputs + for (String key : MsoMulticloudUtils.MULTICLOUD_INPUTS) { + if (extraInputs.contains(key)) { + goldenInputs.put(key, inputs.get(key)); + extraInputs.remove(key); + if (extraInputs.isEmpty()) { + break; + } + } + } + logger.debug("Ignoring extra inputs: " + extraInputs); + } + + // Next add in Volume Group Outputs if there are any. Copy directly without conversions. + if (volumeGroupOutputs != null && !volumeGroupOutputs.isEmpty()) { + for (String key : volumeGroupOutputs.keySet()) { + if (params.containsKey(key) && !goldenInputs.containsKey(key)) { + goldenInputs.put(key, volumeGroupOutputs.get(key)); + } + } + } + + // Next add in Base Module Outputs if there are any. Copy directly without conversions. + if (baseModuleOutputs != null && !baseModuleOutputs.isEmpty()) { + for (String key : baseModuleOutputs.keySet()) { + if (params.containsKey(key) && !goldenInputs.containsKey(key)) { + goldenInputs.put(key, baseModuleOutputs.get(key)); + } + } + } + + // TODO: The model should support a mechanism to pre-assign default parameter values + // per "customization" (i.e. usage) of a given module. In HEAT, this is specified by + // an Environment file. There is not a general mechanism in the model to handle this. + // For the general case, any such parameter/values can be added dynamically to the + // inputs (only if not already specified). // Check that required parameters have been supplied from any of the sources String missingParams = null; boolean checkRequiredParameters = true; try { String propertyString = this.environment.getProperty(MsoVnfPluginAdapterImpl.CHECK_REQD_PARAMS); - if ("false".equalsIgnoreCase (propertyString) || "n".equalsIgnoreCase (propertyString)) { + if ("false".equalsIgnoreCase(propertyString) || "n".equalsIgnoreCase(propertyString)) { checkRequiredParameters = false; logger.debug("CheckRequiredParameters is FALSE. Will still check but then skip blocking..." - + MsoVnfPluginAdapterImpl.CHECK_REQD_PARAMS); + + MsoVnfPluginAdapterImpl.CHECK_REQD_PARAMS); } } catch (Exception e) { // No problem - default is true - logger.debug ("An exception occured trying to get property " + MsoVnfPluginAdapterImpl.CHECK_REQD_PARAMS, - e); + logger.debug("An exception occured trying to get property " + MsoVnfPluginAdapterImpl.CHECK_REQD_PARAMS, + e); } // Do the actual parameter checking. // Include looking at the ENV file as a valid definition of a parameter value. - // TODO: This handling of ENV applies only to Heat. A general mechanism to + // TODO: This handling of ENV applies only to Heat. A general mechanism to // support pre-set parameter/values does not yet exist in the model. // - StringBuilder sb = new StringBuilder(heatEnvironment.getEnvironment()); - MsoHeatEnvironmentEntry mhee = new MsoHeatEnvironmentEntry (sb); - for (HeatTemplateParam parm : heatTemplate.getParameters ()) { - if (parm.isRequired () && (!goldenInputs.containsKey (parm.getParamName ()))) { + StringBuilder sb = new StringBuilder(heatEnvironment.getEnvironment()); + MsoHeatEnvironmentEntry mhee = new MsoHeatEnvironmentEntry(sb); + for (HeatTemplateParam parm : heatTemplate.getParameters()) { + if (parm.isRequired() && (!goldenInputs.containsKey(parm.getParamName()))) { if (mhee != null && mhee.containsParameter(parm.getParamName())) { - logger.debug ("Required parameter " + parm.getParamName () - + " appears to be in environment - do not count as missing"); + logger.debug("Required parameter " + parm.getParamName() + + " appears to be in environment - do not count as missing"); } else { - logger.debug("adding to missing parameters list: " + parm.getParamName ()); - if (missingParams == null) { - missingParams = parm.getParamName (); - } else { - missingParams += "," + parm.getParamName (); - } + logger.debug("adding to missing parameters list: " + parm.getParamName()); + if (missingParams == null) { + missingParams = parm.getParamName(); + } else { + missingParams += "," + parm.getParamName(); + } } } } - if (missingParams != null) { - if (checkRequiredParameters) { - // Problem - missing one or more required parameters - String error = "Create VFModule: Missing Required inputs: " + missingParams; - logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, "VDU", - ErrorCode.DataError.getValue(), "Create VFModule: Missing Required inputs"); - logger.debug(error); - throw new VnfException(error, MsoExceptionCategory.USERDATA); + if (missingParams != null) { + if (checkRequiredParameters) { + // Problem - missing one or more required parameters + String error = "Create VFModule: Missing Required inputs: " + missingParams; + logger.error("{} {} {} {} {}", MessageEnum.RA_MISSING_PARAM.toString(), missingParams, "VDU", + ErrorCode.DataError.getValue(), "Create VFModule: Missing Required inputs"); + logger.debug(error); + throw new VnfException(error, MsoExceptionCategory.USERDATA); + } else { + logger.debug("found missing parameters [" + missingParams + + "] - but checkRequiredParameters is false - " + "will not block"); + } } else { - logger.debug( - "found missing parameters [" + missingParams + "] - but checkRequiredParameters is false - " - + "will not block"); + logger.debug("No missing parameters found - ok to proceed"); } - } else { - logger.debug("No missing parameters found - ok to proceed"); - } - } // NOTE: END PARAMETER CHECKING + } // NOTE: END PARAMETER CHECKING - // Here we go... ready to deploy the VF Module. - long instantiateVduStartTime = System.currentTimeMillis (); - if (backout == null) backout = true; + // Here we go... ready to deploy the VF Module. + long instantiateVduStartTime = System.currentTimeMillis(); + if (backout == null) + backout = true; try { // Construct the VDU Model structure to pass to the targeted VduPlugin @@ -1118,22 +1044,25 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { } catch (VduException me) { // Failed to instantiate the VDU. me.addContext("CreateVFModule"); - String error = "Create VF Module " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, cloudSiteId, - tenantId, "VDU", ErrorCode.DataError.getValue(), "MsoException - instantiateVdu", me); + String error = "Create VF Module " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + + ": " + me; + logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, + cloudSiteId, tenantId, "VDU", ErrorCode.DataError.getValue(), "MsoException - instantiateVdu", me); logger.debug(error); // Convert to a generic VnfException throw new VnfException(me); } catch (NullPointerException npe) { - String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + npe; - logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, cloudSiteId, - tenantId, "VDU", ErrorCode.DataError.getValue(), "NullPointerException - instantiateVdu", - npe); + String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + + ": " + npe; + logger.error("{} {} {} {} {} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, + cloudSiteId, tenantId, "VDU", ErrorCode.DataError.getValue(), + "NullPointerException - instantiateVdu", npe); logger.debug(error); logger.debug("NULL POINTER EXCEPTION at vduPlugin.instantiateVdu", npe); throw new VnfException("NullPointerException during instantiateVdu"); } catch (Exception e) { - String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + e; + String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + + ": " + e; logger.debug("Unhandled exception at vduPlugin.instantiateVdu", e); logger.debug(error); throw new VnfException("Exception during instantiateVdu: " + e.getMessage()); @@ -1142,10 +1071,10 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { // Reach this point if create is successful. // Populate remaining rollback info and response parameters. - vfRollback.setVnfCreated (true); - vfRollback.setVnfId (vduInstance.getVduInstanceId()); + vfRollback.setVnfCreated(true); + vfRollback.setVnfId(vduInstance.getVduInstanceId()); vnfId.value = vduInstance.getVduInstanceId(); - outputs.value = copyStringOutputs (vduInstance.getOutputs ()); + outputs.value = copyStringOutputs(vduInstance.getOutputs()); rollback.value = vfRollback; @@ -1154,40 +1083,37 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { } - public void deleteVfModule (String cloudSiteId, - String cloudOwner, - String tenantId, - String vfModuleId, - MsoRequest msoRequest, - Holder <Map <String, String>> outputs) throws VnfException - { + public void deleteVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vfModuleId, + MsoRequest msoRequest, Holder<Map<String, String>> outputs) throws VnfException { logger.debug("Deleting VF Module " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId); // Will capture execution time for metrics - long startTime = System.currentTimeMillis (); + long startTime = System.currentTimeMillis(); // Capture the output parameters on a delete, so need to query first - VduInstance vduInstance = null; - CloudInfo cloudInfo = new CloudInfo(cloudSiteId, cloudOwner, tenantId, null); + VduInstance vduInstance = null; + CloudInfo cloudInfo = new CloudInfo(cloudSiteId, cloudOwner, tenantId, null); // Use the VduPlugin. VduPlugin vduPlugin = getVduPlugin(cloudSiteId, cloudOwner); - try { - vduInstance = vduPlugin.queryVdu (cloudInfo, vfModuleId); - } - catch (VduException e) { - // Failed to query the VDU due to a plugin exception. - // Convert to a generic VnfException - e.addContext("QueryVFModule"); - String error = "Query VfModule (VDU): " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + e; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleId, cloudOwner, cloudSiteId, - tenantId, "VDU", "QueryVFModule", ErrorCode.DataError.getValue(), "Exception - queryVDU", e); - logger.debug(error); - throw new VnfException(e); - } - - // call method which handles the conversion from Map<String,Object> to Map<String,String> for our expected Object types + try { + vduInstance = vduPlugin.queryVdu(cloudInfo, vfModuleId); + } catch (VduException e) { + // Failed to query the VDU due to a plugin exception. + // Convert to a generic VnfException + e.addContext("QueryVFModule"); + String error = "Query VfModule (VDU): " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + + tenantId + ": " + e; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleId, cloudOwner, + cloudSiteId, tenantId, "VDU", "QueryVFModule", ErrorCode.DataError.getValue(), + "Exception - queryVDU", e); + logger.debug(error); + throw new VnfException(e); + } + + // call method which handles the conversion from Map<String,Object> to Map<String,String> for our expected + // Object types outputs.value = convertMapStringObjectToStringString(vduInstance.getOutputs()); // Use the VduPlugin to delete the VDU. @@ -1196,19 +1122,20 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { // - a vnfInstance object with status of NOTFOUND (VDU did not exist, treat as success) // - a vnfInstance object with status of FAILED (error) // Also, VduException could be thrown. - long subStartTime = System.currentTimeMillis (); + long subStartTime = System.currentTimeMillis(); try { - // TODO: Get an appropriate timeout value - require access to the model + // TODO: Get an appropriate timeout value - require access to the model vduPlugin.deleteVdu(cloudInfo, vfModuleId, 5); } catch (VduException me) { - me.addContext ("DeleteVfModule"); + me.addContext("DeleteVfModule"); // Convert to a generic VnfException - String error = "Delete VF: " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vfModuleId, cloudOwner, cloudSiteId, - tenantId, "VDU", "DeleteVdu", ErrorCode.DataError.getValue(), - "Exception - DeleteVdu: " + me.getMessage()); + String error = + "Delete VF: " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), vfModuleId, cloudOwner, + cloudSiteId, tenantId, "VDU", "DeleteVdu", ErrorCode.DataError.getValue(), + "Exception - DeleteVdu: " + me.getMessage()); logger.debug(error); - throw new VnfException (me); + throw new VnfException(me); } // On success, nothing is returned. @@ -1217,53 +1144,39 @@ public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { // Update VF Module not yet implemented for generic VDU plug-in model. @Override - public void updateVfModule (String cloudSiteId, - String cloudOwner, - String tenantId, - String vnfType, - String vnfVersion, - String vnfName, - String requestType, - String volumeGroupHeatStackId, - String baseVfHeatStackId, - String vfModuleStackId, - String modelCustomizationUuid, - Map <String, Object> inputs, - MsoRequest msoRequest, - Holder <Map <String, String>> outputs, - Holder <VnfRollback> rollback) throws VnfException - { - // This operation is not currently supported for VduPlugin-orchestrated VF Modules. - logger.debug("Update VF Module command attempted but not supported"); - throw new VnfException ("UpdateVfModule: Unsupported command", MsoExceptionCategory.USERDATA); - } + public void updateVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vnfType, + String vnfVersion, String vnfName, String requestType, String volumeGroupHeatStackId, + String baseVfHeatStackId, String vfModuleStackId, String modelCustomizationUuid, Map<String, Object> inputs, + MsoRequest msoRequest, Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback) + throws VnfException { + // This operation is not currently supported for VduPlugin-orchestrated VF Modules. + logger.debug("Update VF Module command attempted but not supported"); + throw new VnfException("UpdateVfModule: Unsupported command", MsoExceptionCategory.USERDATA); + } /* - * Dynamic selection of a VduPlugin version. For initial tests, base on the "orchestrator" - * defined for the target cloud. Should really be looking at the VNF Model (ochestration_mode) - * but we don't currently have access to that in Query and Delete cases. + * Dynamic selection of a VduPlugin version. For initial tests, base on the "orchestrator" defined for the target + * cloud. Should really be looking at the VNF Model (ochestration_mode) but we don't currently have access to that + * in Query and Delete cases. */ - private VduPlugin getVduPlugin (String cloudSiteId, String cloudOwner) { - Optional<CloudSite> cloudSiteOp = cloudConfig.getCloudSite(cloudSiteId); - if (cloudSiteOp.isPresent()) { - CloudSite cloudSite = cloudSiteOp.get(); - String orchestrator = cloudSite.getOrchestrator(); - - if (orchestrator.equalsIgnoreCase("CLOUDIFY")) { - return cloudifyUtils; - } - else if (orchestrator.equalsIgnoreCase("HEAT")) { - return heatUtils; - } - else if (orchestrator.equalsIgnoreCase("MULTICLOUD")) { + private VduPlugin getVduPlugin(String cloudSiteId, String cloudOwner) { + Optional<CloudSite> cloudSiteOp = cloudConfig.getCloudSite(cloudSiteId); + if (cloudSiteOp.isPresent()) { + CloudSite cloudSite = cloudSiteOp.get(); + String orchestrator = cloudSite.getOrchestrator(); + + if (orchestrator.equalsIgnoreCase("CLOUDIFY")) { + return cloudifyUtils; + } else if (orchestrator.equalsIgnoreCase("HEAT")) { + return heatUtils; + } else if (orchestrator.equalsIgnoreCase("MULTICLOUD")) { return multicloudUtils; - } - else { + } else { // Default if cloudSite record exists - return HEAT plugin - will fail later - return heatUtils; + return heatUtils; } - } + } // Default if no cloudSite record exists - return multicloud plugin - return multicloudUtils; + return multicloudUtils; } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VfRollback.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VfRollback.java index 3736669094..7ba8ca8905 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VfRollback.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VfRollback.java @@ -25,108 +25,129 @@ package org.onap.so.adapters.vnf; import org.onap.so.entity.MsoRequest; public class VfRollback { - private String vnfId; - private String tenantId; - private String cloudSiteId; - private boolean tenantCreated = false; - private boolean vnfCreated = false; - private MsoRequest msoRequest; - private String volumeGroupName; - private String volumeGroupId; - private String requestType; - private String volumeGroupHeatStackId; - private String baseGroupHeatStackId; - private boolean isBase = false; - private String vfModuleStackId; - - - public String getVnfId() { - return vnfId; - } - public void setVnfId(String vnfId) { - this.vnfId = vnfId; - } - public String getTenantId() { - return tenantId; - } - - public void setTenantId(String tenantId) { - this.tenantId = tenantId; - } - public String getCloudSiteId() { - return cloudSiteId; - } - public void setCloudSiteId(String cloudId) { - this.cloudSiteId = cloudId; - } - public boolean getTenantCreated() { - return tenantCreated; - } - public void setTenantCreated(boolean tenantCreated) { - this.tenantCreated = tenantCreated; - } - public boolean getVnfCreated() { - return vnfCreated; - } - public void setVnfCreated(boolean vnfCreated) { - this.vnfCreated = vnfCreated; - } - public MsoRequest getMsoRequest() { - return msoRequest; - } - public void setMsoRequest (MsoRequest msoRequest) { - this.msoRequest = msoRequest; - } - public String getVolumeGroupName() { - return this.volumeGroupName; - } - public void setVolumeGroupName(String volumeGroupName) { - this.volumeGroupName = volumeGroupName; - } - public String getVolumeGroupId() { - return this.volumeGroupId; - } - public void setVolumeGroupId(String volumeGroupId) { - this.volumeGroupId = volumeGroupId; - } - public String getRequestType() { - return this.requestType; - } - public void setRequestType(String requestType) { - this.requestType = requestType; - } - public String getVolumeGroupHeatStackId() { - return this.volumeGroupHeatStackId; - } - public void setVolumeGroupHeatStackId(String volumeGroupHeatStackId) { - this.volumeGroupHeatStackId = volumeGroupHeatStackId; - } - - public String getBaseGroupHeatStackId() { - return this.baseGroupHeatStackId; - } - public void setBaseGroupHeatStackId(String baseGroupHeatStackId) { - this.baseGroupHeatStackId = baseGroupHeatStackId; - } - - public boolean isBase() { - return this.isBase; - } - public void setIsBase(boolean isBase) { - this.isBase = isBase; - } - public String getVfModuleStackId() { - return this.vfModuleStackId; - } - public void setVfModuleStackId(String vfModuleStackId) { - this.vfModuleStackId = vfModuleStackId; - } - - @Override + private String vnfId; + private String tenantId; + private String cloudSiteId; + private boolean tenantCreated = false; + private boolean vnfCreated = false; + private MsoRequest msoRequest; + private String volumeGroupName; + private String volumeGroupId; + private String requestType; + private String volumeGroupHeatStackId; + private String baseGroupHeatStackId; + private boolean isBase = false; + private String vfModuleStackId; + + + public String getVnfId() { + return vnfId; + } + + public void setVnfId(String vnfId) { + this.vnfId = vnfId; + } + + public String getTenantId() { + return tenantId; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + public String getCloudSiteId() { + return cloudSiteId; + } + + public void setCloudSiteId(String cloudId) { + this.cloudSiteId = cloudId; + } + + public boolean getTenantCreated() { + return tenantCreated; + } + + public void setTenantCreated(boolean tenantCreated) { + this.tenantCreated = tenantCreated; + } + + public boolean getVnfCreated() { + return vnfCreated; + } + + public void setVnfCreated(boolean vnfCreated) { + this.vnfCreated = vnfCreated; + } + + public MsoRequest getMsoRequest() { + return msoRequest; + } + + public void setMsoRequest(MsoRequest msoRequest) { + this.msoRequest = msoRequest; + } + + public String getVolumeGroupName() { + return this.volumeGroupName; + } + + public void setVolumeGroupName(String volumeGroupName) { + this.volumeGroupName = volumeGroupName; + } + + public String getVolumeGroupId() { + return this.volumeGroupId; + } + + public void setVolumeGroupId(String volumeGroupId) { + this.volumeGroupId = volumeGroupId; + } + + public String getRequestType() { + return this.requestType; + } + + public void setRequestType(String requestType) { + this.requestType = requestType; + } + + public String getVolumeGroupHeatStackId() { + return this.volumeGroupHeatStackId; + } + + public void setVolumeGroupHeatStackId(String volumeGroupHeatStackId) { + this.volumeGroupHeatStackId = volumeGroupHeatStackId; + } + + public String getBaseGroupHeatStackId() { + return this.baseGroupHeatStackId; + } + + public void setBaseGroupHeatStackId(String baseGroupHeatStackId) { + this.baseGroupHeatStackId = baseGroupHeatStackId; + } + + public boolean isBase() { + return this.isBase; + } + + public void setIsBase(boolean isBase) { + this.isBase = isBase; + } + + public String getVfModuleStackId() { + return this.vfModuleStackId; + } + + public void setVfModuleStackId(String vfModuleStackId) { + this.vfModuleStackId = vfModuleStackId; + } + + @Override public String toString() { - return "VfRollback: cloud=" + cloudSiteId + ", tenant=" + tenantId + - ", vnf=" + vnfId + ", tenantCreated=" + tenantCreated + - ", vnfCreated=" + vnfCreated + ", requestType = " + requestType + - ", volumeGroupHeatStackId = " + this.volumeGroupHeatStackId; - } + return "VfRollback: cloud=" + cloudSiteId + ", tenant=" + tenantId + ", vnf=" + vnfId + ", tenantCreated=" + + tenantCreated + ", vnfCreated=" + vnfCreated + ", requestType = " + requestType + + ", volumeGroupHeatStackId = " + this.volumeGroupHeatStackId; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java index d1a48a7c9b..487b14b942 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java @@ -26,7 +26,6 @@ package org.onap.so.adapters.vnf; import java.util.Map; - import javax.inject.Provider; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -41,7 +40,6 @@ import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.ws.Holder; - import org.apache.http.HttpStatus; import org.onap.so.adapters.vnf.exceptions.VnfException; import org.onap.so.adapters.vnfrest.CreateVfModuleRequest; @@ -66,7 +64,6 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; - import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @@ -74,636 +71,524 @@ import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; /** - * This class services calls to the REST interface for VF Modules (http://host:port/vnfs/rest/v1/vnfs) - * Both XML and JSON can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default. - * For testing, call with cloudSiteId = ___TESTING___ - * To test exceptions, also set tenantId = ___TESTING___ + * This class services calls to the REST interface for VF Modules (http://host:port/vnfs/rest/v1/vnfs) Both XML and JSON + * can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default. For testing, call + * with cloudSiteId = ___TESTING___ To test exceptions, also set tenantId = ___TESTING___ */ @Path("/v1/vnfs") @Api(value = "/v1/vnfs", description = "root of vnf adapters restful web service") @Transactional @Component public class VnfAdapterRest { - private static Logger logger = LoggerFactory.getLogger(VnfAdapterRest.class); - private static final String TESTING_KEYWORD = "___TESTING___"; - private static final String RESP=", resp="; - - @Autowired - private MsoVnfAdapterImpl vnfAdapter; - //TODO Logging, SkipAAI, CREATED flags, Integrate with BPEL, Auth, - - @Autowired - private Provider<BpelRestClient> bpelRestClientProvider; - - - /* - * URL:http://localhost:8080/vnfs/rest/v1/vnfs/<aaivnfid>/vf-modules/<aaimodid> - * REQUEST: - * {"deleteVfModuleRequest": - {"cloudSiteId": "DAN", - "tenantId": "214b428a1f554c02935e66330f6a5409", - "vnfId": "somevnfid", - "vfModuleId": "somemodid", - "vfModuleStackId": "4e567676-e266-4594-a3a6-131c8a2baf73", - "messageId": "ra.1", - "notificationUrl": "http://localhost:8089/vnfmock", - "skipAAI": true, - "msoRequest": { - "requestId": "ra1", - "serviceInstanceId": "sa1" - }} - } - */ - @DELETE - @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "DeleteVfModule", - response = Response.class, - notes = "Delete an existing vnfModule, DeleteVfModuleRequest JSON is required") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfModule has been successfully deleted"), - @ApiResponse(code = 202, message = "delete vnfModule request has been accepted (async only)"), - @ApiResponse(code = 500, message = "delete vnfModule failed, examine entity object for details") }) - public Response deleteVfModule ( - @ApiParam(value = "aaiVnfId", required = true) - @PathParam("aaiVnfId") String aaiVnfId, - @ApiParam(value = "aaiVfModuleId", required = true) - @PathParam("aaiVfModuleId") String aaiVfModuleId, - @ApiParam(value = "DeleteVfModuleRequest", required = true) - final DeleteVfModuleRequest req) - { - logger.debug("Delete VfModule enter: " + req.toJsonString()); - if (aaiVnfId == null || !aaiVnfId.equals(req.getVnfId())) { - logger.debug("Req rejected - aaiVnfId not provided or doesn't match URL"); - return Response - .status(HttpStatus.SC_BAD_REQUEST) - .type(MediaType.TEXT_PLAIN) - .entity("vnfid in URL does not match content") - .build(); - } - if (aaiVfModuleId == null || !aaiVfModuleId.equals(req.getVfModuleId())) { - logger.debug("Req rejected - aaiVfModuleId not provided or doesn't match URL"); - return Response - .status(HttpStatus.SC_BAD_REQUEST) - .type(MediaType.TEXT_PLAIN) - .entity("vfModuleId in URL does not match content") - .build(); - } - DeleteVfModuleTask task = new DeleteVfModuleTask(req); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling delete, send generic failure as sync resp to caller - logger.error("", MessageEnum.RA_DELETE_VNF_ERR.toString(), "deleteVfModule", - ErrorCode.BusinessProcesssError.getValue(), "Exception in deleteVfModule", e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("deleteVNFVolumes exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class DeleteVfModuleTask implements Runnable { - private final DeleteVfModuleRequest req; - private DeleteVfModuleResponse response = null; - private VfModuleExceptionResponse eresp = null; - private boolean sendxml; - - public DeleteVfModuleTask(DeleteVfModuleRequest req) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<DeleteVfModuleResponse>(response) {} - : new GenericEntity<VfModuleExceptionResponse>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - - @Override - public void run() { - try { - String cloudsite = req.getCloudSiteId(); - Holder<Map<String, String>> outputs = new Holder <> (); - if (cloudsite != null && !cloudsite.equals(TESTING_KEYWORD)) { - //vnfAdapter.deleteVnf (req.getCloudSiteId(), req.getTenantId(), req.getVfModuleStackId(), req.getMsoRequest()); - vnfAdapter.deleteVfModule (req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), req.getVfModuleStackId(), req.getMsoRequest(), outputs); - } - response = new DeleteVfModuleResponse(req.getVnfId(), req.getVfModuleId(), Boolean.TRUE, req.getMessageId(), outputs.value); - } catch (VnfException e) { - logger.error("{} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), - ErrorCode.BusinessProcesssError.getValue(), "VnfException - Delete VNF Module", e); - eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, req.getMessageId()); - } - if (!req.isSynchronous()) { - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("Delete vfModule exit: code=" + getStatusCode() + RESP + getResponse()); - } - } - - /* - * URL:http://localhost:8080/vnfs/rest/v1/vnfs/<aaiVnfId>/vf-modules/<aaiVfModuleId>?cloudSiteId=DAN&tenantId=vfModule?&skipAAI=TRUE&msoRequest.requestId=ra1&msoRequest.serviceInstanceId=si1&vfModuleName=T2N2S1 - * RESP: - * {"queryVfModuleResponse": { - "vfModuleId": "AvfmodId", - "vfModuleOutputs": {"entry": { - "key": "server_private_ip_1", - "value": "10.100.1.25" - }}, - "vfModuleStackId": "RaaVnf1/abfa8a6d-feb1-40af-aea3-109403b1cf6b", - "vnfId": "AvnfID", - "vnfStatus": "ACTIVE" - }} - */ - @GET - @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}") - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "QueryVfModule", - response = Response.class, - notes = "Query an existing vnfModule") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfModule has been successfully queried"), - @ApiResponse(code = 500, message = "query vnfModule failed, examine entity object for details") }) - public Response queryVfModule( - @ApiParam(value = "aaiVnfId", required = true) - @PathParam("aaiVnfId") String aaiVnfId, - @ApiParam(value = "aaiVfModuleId", required = true) - @PathParam("aaiVfModuleId") String aaiVfModuleId, - @ApiParam(value = "cloudSiteId", required = true) - @QueryParam("cloudSiteId") String cloudSiteId, - @ApiParam(value = "cloudOwner", required = true) - @QueryParam("cloudOwner") String cloudOwner, - @ApiParam(value = "tenantId", required = true) - @QueryParam("tenantId") String tenantId, - @ApiParam(value = "vfModuleName", required = true) - @QueryParam("vfModuleName") String vfModuleName, //RAA? Id in doc - @ApiParam(value = "skipAAI", required = true) - @QueryParam("skipAAI") Boolean skipAAI, - @ApiParam(value = "msoRequest.requestId", required = true) - @QueryParam("msoRequest.requestId") String requestId, - @ApiParam(value = "msoRequest.serviceInstanceId", required = true) - @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId) - { - //This request responds synchronously only - logger.debug("Query vfModule enter:" + vfModuleName); - MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId); - - try { - int respStatus = HttpStatus.SC_OK; - QueryVfModuleResponse qryResp = new QueryVfModuleResponse(aaiVnfId, aaiVfModuleId, null, null, null); - Holder<Boolean> vnfExists = new Holder<>(); - Holder<String> vfModuleId = new Holder<>(); - Holder<VnfStatus> status = new Holder<>(); - Holder<Map<String, String>> outputs = new Holder <> (); - vnfAdapter.queryVnf (cloudSiteId, cloudOwner, tenantId, vfModuleName, msoRequest, vnfExists, vfModuleId, status, outputs); - if (!vnfExists.value) { - logger.debug("vfModule not found"); - respStatus = HttpStatus.SC_NOT_FOUND; - } else { - logger.debug("vfModule found" + vfModuleId.value + ", status=" + status.value); - qryResp.setVfModuleId(vfModuleId.value); - qryResp.setVnfStatus(status.value); - qryResp.setVfModuleOutputs(outputs.value); - } - logger.debug("Query vfModule exit"); - return Response - .status(respStatus) - .entity(new GenericEntity<QueryVfModuleResponse>(qryResp) {}) - .build(); - } catch (VnfException e) { - logger.error("{} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, "queryVfModule", - ErrorCode.BusinessProcesssError.getValue(), "VnfException - queryVfModule", e); - VfModuleExceptionResponse excResp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.FALSE, null); - return Response - .status(HttpStatus.SC_INTERNAL_SERVER_ERROR) - .entity(new GenericEntity<VfModuleExceptionResponse>(excResp) {}) - .build(); - } - } - - /*URL: http://localhost:8080/vnfs/rest/v1/vnfs/<aaivnfid>/vf-modules - *REQUEST: - * {"createVfModuleRequest": - {"cloudSiteId": "DAN", - "tenantId": "214b428a1f554c02935e66330f6a5409", - "vnfId": "somevnfid", - "vfModuleId": "somemodid", - "vfModuleName": "RaaVnf1", - "vnfType": "ApacheVnf", - "vfModuleParams": {"entry": [ - {"key": "network_id", - "value": "59ed7b41-2983-413f-ba93-e7d437433916"}, - {"key": "subnet_id", - "value": "086c9298-5c57-49b7-bb2b-6fd5730c5d92"}, - {"key": "server_name_0", - "value": "RaaVnf1"} - ]}, - "failIfExists": true, - "messageId": "ra.1", - "notificationUrl": "http://localhost:8089/vnfmock", - "skipAAI": true, - "msoRequest": { - "requestId": "ra1", - "serviceInstanceId": "sa1" - }} - } - */ - @POST - @Path("{aaiVnfId}/vf-modules") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "CreateVfModule", - response = Response.class, - notes = "Create a vnfModule") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfModule has been successfully created"), - @ApiResponse(code = 202, message = "create vnfModule request has been successfully accepted (async only)"), - @ApiResponse(code = 500, message = "create vnfModule failed, examine entity object for details") }) - public Response createVfModule( - @ApiParam(value = "aaiVnfId", required = true) - @PathParam("aaiVnfId") String aaiVnfId, - @ApiParam(value = "CreateVfModuleRequest", required = true) - final CreateVfModuleRequest req) - { - logger.debug("Create VfModule enter inside VnfAdapterRest: " + req.toJsonString()); - if (aaiVnfId == null || !aaiVnfId.equals(req.getVnfId())) { - logger.debug("Req rejected - aaiVnfId not provided or doesn't match URL"); - return Response - .status(HttpStatus.SC_BAD_REQUEST) - .type(MediaType.TEXT_PLAIN) - .entity("vnfid in URL does not match content") - .build(); - } - CreateVfModuleTask task = new CreateVfModuleTask(req); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR, "createVfModule", - ErrorCode.BusinessProcesssError, "Exception - createVfModule", e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("createVfModule exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class CreateVfModuleTask implements Runnable { - private final CreateVfModuleRequest req; - private CreateVfModuleResponse response = null; - private VfModuleExceptionResponse eresp = null; - private boolean sendxml; - - public CreateVfModuleTask(CreateVfModuleRequest req) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<CreateVfModuleResponse>(response) {} - : new GenericEntity<VfModuleExceptionResponse>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - - @Override - public void run() { - logger.debug ("CreateVfModuleTask start"); - try { - // Synchronous Web Service Outputs - Holder <String> vfModuleStackId = new Holder <> (); - Holder <Map <String, String>> outputs = new Holder <> (); - Holder <VnfRollback> vnfRollback = new Holder <> (); - String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); - logger.debug("completeVnfVfModuleType=" + completeVnfVfModuleType); - String cloudsite = req.getCloudSiteId(); - String cloudOwner = req.getCloudOwner(); - if (cloudsite != null && cloudsite.equals(TESTING_KEYWORD)) { - String tenant = req.getTenantId(); - if (tenant != null && tenant.equals(TESTING_KEYWORD)) { - throw new VnfException("testing."); - } - vnfRollback.value = new VnfRollback(req.getVnfId(), tenant, cloudOwner, cloudsite, - true, false, new MsoRequest("reqid", "svcid"), - req.getVolumeGroupId(), req.getVolumeGroupId(), req.getRequestType(), req.getModelCustomizationUuid()); - vfModuleStackId.value = "479D3D8B-6360-47BC-AB75-21CC91981484"; - outputs.value = VolumeAdapterRest.testMap(); - } else { -// vnfAdapter.createVnf (createReq.getCloudSiteId(), -// createReq.getTenantId(), -// createReq.getVnfType(), -// createReq.getVnfVersion(), -// createReq.getVfModuleName(), -// createReq.getRequestType(), -// createReq.getVolumeGroupStackId(), -// createReq.getVfModuleParams(), -// createReq.getFailIfExists(), -// createReq.getBackout(), -// createReq.getMsoRequest(), -// vfModuleStackId, -// outputs, -// vnfRollback); - vnfAdapter.createVfModule(req.getCloudSiteId(), - req.getCloudOwner(), - req.getTenantId(), - //req.getVnfType(), - completeVnfVfModuleType, - req.getVnfVersion(), - req.getVnfId(), - req.getVfModuleName(), - req.getVfModuleId(), - req.getRequestType(), - req.getVolumeGroupStackId(), - req.getBaseVfModuleStackId(), - req.getModelCustomizationUuid(), - req.getVfModuleParams(), - req.getFailIfExists(), - req.getBackout(), - req.getEnableBridge(), - req.getMsoRequest(), - vfModuleStackId, - outputs, - vnfRollback); - } - VfModuleRollback modRollback = new VfModuleRollback(vnfRollback.value, req.getVfModuleId(), vfModuleStackId.value, req.getMessageId()); - response = new CreateVfModuleResponse(req.getVnfId(), req.getVfModuleId(), - vfModuleStackId.value, Boolean.TRUE, outputs.value, modRollback, req.getMessageId()); - } catch (VnfException e) { - logger.debug("Exception :",e); - eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, req.getMessageId()); - } - if (!req.isSynchronous()) { - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("CreateVfModuleTask exit: code=" + getStatusCode() + RESP + getResponse()); - } - } - - @PUT - @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "UpdateVfModule", - response = Response.class, - notes = "Update an existing vnfModule") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfModule has been successfully updated"), - @ApiResponse(code = 202, message = "update vnfModule request has been successfully accepted (async only)"), - @ApiResponse(code = 500, message = "update vnfModule failed, examine entity object for details") }) - public Response updateVfModule( - @ApiParam(value = "aaiVnfId", required = true) - @PathParam("aaiVnfId") String aaiVnfId, - @ApiParam(value = "aaiVfModuleId", required = true) - @PathParam("aaiVfModuleId") String aaiVfModuleId, - @ApiParam(value = "UpdateVfModuleRequest", required = true) - final UpdateVfModuleRequest req) - { - logger.debug("Update VfModule enter: " + req.toJsonString()); - UpdateVfModulesTask task = new UpdateVfModulesTask(req); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} {} {}", MessageEnum.RA_UPDATE_VNF_ERR.toString(), "updateVfModule", - ErrorCode.BusinessProcesssError.getValue(), "Exception - updateVfModule", e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("updateVfModules exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class UpdateVfModulesTask implements Runnable { - private final UpdateVfModuleRequest req; - private UpdateVfModuleResponse response = null; - private VfModuleExceptionResponse eresp = null; - private boolean sendxml; - - public UpdateVfModulesTask(UpdateVfModuleRequest req) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<UpdateVfModuleResponse>(response) {} - : new GenericEntity<VfModuleExceptionResponse>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - @Override - public void run() { - try { - //MsoVnfAdapter vnfAdapter = new MsoVnfAdapterImpl (msoPropertiesFactory, cloudConfigFactory); - - // Synchronous Web Service Outputs - Holder <String> vfModuleStackId = new Holder <> (); - Holder <Map <String, String>> outputs = new Holder <> (); - Holder <VnfRollback> vnfRollback = new Holder <> (); - String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); - logger.debug("in updateVf - completeVnfVfModuleType=" + completeVnfVfModuleType); - - vnfAdapter.updateVfModule (req.getCloudSiteId(), - req.getCloudOwner(), - req.getTenantId(), - //req.getVnfType(), - completeVnfVfModuleType, - req.getVnfVersion(), - req.getVfModuleName(), - req.getRequestType(), - req.getVolumeGroupStackId(), - req.getBaseVfModuleStackId(), - req.getVfModuleStackId(), - req.getModelCustomizationUuid(), - req.getVfModuleParams(), - req.getMsoRequest(), - outputs, - vnfRollback); - - response = new UpdateVfModuleResponse(req.getVnfId(), req.getVfModuleId(), - vfModuleStackId.value, outputs.value, req.getMessageId()); - } catch (VnfException e) { - logger.debug("Exception :",e); - eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, req.getMessageId()); - } - if (!req.isSynchronous()) { - // This is asynch, so POST response back to caller - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost (getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("Update VfModule exit: code=" + getStatusCode() + RESP + getResponse()); - } - } - /* - * URL:http://localhost:8080/vnfs/rest/v1/vnfs/<aaivnfid>/vf-modules/<aaimodid>/rollback - * REQUEST: - * {"deleteVfModuleRequest": - {"cloudSiteId": "DAN", - "tenantId": "214b428a1f554c02935e66330f6a5409", - "vnfId": "somevnfid", - "vfModuleId": "somemodid", - "vfModuleStackId": "4e567676-e266-4594-a3a6-131c8a2baf73", - "messageId": "ra.1", - "notificationUrl": "http://localhost:8089/vnfmock", - "skipAAI": true, - "msoRequest": { - "requestId": "ra1", - "serviceInstanceId": "sa1" - }} - } - */ - @DELETE - @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}/rollback") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "RollbackVfModule", - response = Response.class, - notes = "Rollback an existing vnfModule") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfModule has been successfully rolled back"), - @ApiResponse(code = 202, message = "rollback vnfModule request has been successfully accepted (async only)"), - @ApiResponse(code = 500, message = "rollback vnfModule failed, examine entity object for details") }) - public Response rollbackVfModule ( - @ApiParam(value = "aaiVnfId", required = true) - @PathParam("aaiVnfId") String aaiVnfId, - @ApiParam(value = "aaiVfModuleId", required = true) - @PathParam("aaiVfModuleId") String aaiVfModuleId, - @ApiParam(value = "RollbackVfModuleRequest", required = true) - //@QueryParam("rollback") String rollback, - final RollbackVfModuleRequest req) - { - logger.debug("Rollback VfModule enter: " + req.toJsonString()); - RollbackVfModulesTask task = new RollbackVfModulesTask(req); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR.toString(), "rollbackVfModule", - ErrorCode.BusinessProcesssError.getValue(), "Exception - rollbackVfModule", e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("rollbackVfModule exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class RollbackVfModulesTask implements Runnable { - private final RollbackVfModuleRequest req; - private RollbackVfModuleResponse response = null; - private VfModuleExceptionResponse eresp = null; - private boolean sendxml; - - public RollbackVfModulesTask(RollbackVfModuleRequest req) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<RollbackVfModuleResponse>(response) {} - : new GenericEntity<VfModuleExceptionResponse>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - @Override - public void run() { - try { - VfModuleRollback vmr = req.getVfModuleRollback(); - VnfRollback vrb = new VnfRollback( - vmr.getVfModuleStackId(), vmr.getTenantId(), vmr.getCloudOwner(), vmr.getCloudSiteId(), true, true, - vmr.getMsoRequest(), null, null, null, null); - vnfAdapter.rollbackVnf (vrb); - response = new RollbackVfModuleResponse(Boolean.TRUE, req.getMessageId()); - } catch (VnfException e) { - logger.error("{} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR, ErrorCode.BusinessProcesssError, - "Exception" + " - " + "rollbackVfModule", e); - eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, false, req.getMessageId()); - } - if (!req.isSynchronous()) { - // This is asynch, so POST response back to caller - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost (getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("RollbackVfModulesTask exit: code=" + getStatusCode() + RESP + getResponse()); - } - } + private static Logger logger = LoggerFactory.getLogger(VnfAdapterRest.class); + private static final String TESTING_KEYWORD = "___TESTING___"; + private static final String RESP = ", resp="; + + @Autowired + private MsoVnfAdapterImpl vnfAdapter; + // TODO Logging, SkipAAI, CREATED flags, Integrate with BPEL, Auth, + + @Autowired + private Provider<BpelRestClient> bpelRestClientProvider; + + + /* + * URL:http://localhost:8080/vnfs/rest/v1/vnfs/<aaivnfid>/vf-modules/<aaimodid> REQUEST: {"deleteVfModuleRequest": + * {"cloudSiteId": "DAN", "tenantId": "214b428a1f554c02935e66330f6a5409", "vnfId": "somevnfid", "vfModuleId": + * "somemodid", "vfModuleStackId": "4e567676-e266-4594-a3a6-131c8a2baf73", "messageId": "ra.1", "notificationUrl": + * "http://localhost:8089/vnfmock", "skipAAI": true, "msoRequest": { "requestId": "ra1", "serviceInstanceId": "sa1" + * }} } + */ + @DELETE + @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "DeleteVfModule", response = Response.class, + notes = "Delete an existing vnfModule, DeleteVfModuleRequest JSON is required") + @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully deleted"), + @ApiResponse(code = 202, message = "delete vnfModule request has been accepted (async only)"), + @ApiResponse(code = 500, message = "delete vnfModule failed, examine entity object for details")}) + public Response deleteVfModule( + @ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId, + @ApiParam(value = "aaiVfModuleId", required = true) @PathParam("aaiVfModuleId") String aaiVfModuleId, + @ApiParam(value = "DeleteVfModuleRequest", required = true) final DeleteVfModuleRequest req) { + logger.debug("Delete VfModule enter: " + req.toJsonString()); + if (aaiVnfId == null || !aaiVnfId.equals(req.getVnfId())) { + logger.debug("Req rejected - aaiVnfId not provided or doesn't match URL"); + return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN) + .entity("vnfid in URL does not match content").build(); + } + if (aaiVfModuleId == null || !aaiVfModuleId.equals(req.getVfModuleId())) { + logger.debug("Req rejected - aaiVfModuleId not provided or doesn't match URL"); + return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN) + .entity("vfModuleId in URL does not match content").build(); + } + DeleteVfModuleTask task = new DeleteVfModuleTask(req); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling delete, send generic failure as sync resp to caller + logger.error("", MessageEnum.RA_DELETE_VNF_ERR.toString(), "deleteVfModule", + ErrorCode.BusinessProcesssError.getValue(), "Exception in deleteVfModule", e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("deleteVNFVolumes exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class DeleteVfModuleTask implements Runnable { + private final DeleteVfModuleRequest req; + private DeleteVfModuleResponse response = null; + private VfModuleExceptionResponse eresp = null; + private boolean sendxml; + + public DeleteVfModuleTask(DeleteVfModuleRequest req) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<DeleteVfModuleResponse>(response) {} + : new GenericEntity<VfModuleExceptionResponse>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + try { + String cloudsite = req.getCloudSiteId(); + Holder<Map<String, String>> outputs = new Holder<>(); + if (cloudsite != null && !cloudsite.equals(TESTING_KEYWORD)) { + // vnfAdapter.deleteVnf (req.getCloudSiteId(), req.getTenantId(), req.getVfModuleStackId(), + // req.getMsoRequest()); + vnfAdapter.deleteVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + req.getVfModuleStackId(), req.getMsoRequest(), outputs); + } + response = new DeleteVfModuleResponse(req.getVnfId(), req.getVfModuleId(), Boolean.TRUE, + req.getMessageId(), outputs.value); + } catch (VnfException e) { + logger.error("{} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), + ErrorCode.BusinessProcesssError.getValue(), "VnfException - Delete VNF Module", e); + eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, + req.getMessageId()); + } + if (!req.isSynchronous()) { + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("Delete vfModule exit: code=" + getStatusCode() + RESP + getResponse()); + } + } + + /* + * URL:http://localhost:8080/vnfs/rest/v1/vnfs/<aaiVnfId>/vf-modules/<aaiVfModuleId>?cloudSiteId=DAN&tenantId= + * vfModule?&skipAAI=TRUE&msoRequest.requestId=ra1&msoRequest.serviceInstanceId=si1&vfModuleName=T2N2S1 RESP: + * {"queryVfModuleResponse": { "vfModuleId": "AvfmodId", "vfModuleOutputs": {"entry": { "key": + * "server_private_ip_1", "value": "10.100.1.25" }}, "vfModuleStackId": + * "RaaVnf1/abfa8a6d-feb1-40af-aea3-109403b1cf6b", "vnfId": "AvnfID", "vnfStatus": "ACTIVE" }} + */ + @GET + @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}") + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "QueryVfModule", response = Response.class, notes = "Query an existing vnfModule") + @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully queried"), + @ApiResponse(code = 500, message = "query vnfModule failed, examine entity object for details")}) + public Response queryVfModule(@ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId, + @ApiParam(value = "aaiVfModuleId", required = true) @PathParam("aaiVfModuleId") String aaiVfModuleId, + @ApiParam(value = "cloudSiteId", required = true) @QueryParam("cloudSiteId") String cloudSiteId, + @ApiParam(value = "cloudOwner", required = true) @QueryParam("cloudOwner") String cloudOwner, + @ApiParam(value = "tenantId", required = true) @QueryParam("tenantId") String tenantId, + @ApiParam(value = "vfModuleName", required = true) @QueryParam("vfModuleName") String vfModuleName, // RAA? + // Id in + // doc + @ApiParam(value = "skipAAI", required = true) @QueryParam("skipAAI") Boolean skipAAI, + @ApiParam(value = "msoRequest.requestId", + required = true) @QueryParam("msoRequest.requestId") String requestId, + @ApiParam(value = "msoRequest.serviceInstanceId", + required = true) @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId) { + // This request responds synchronously only + logger.debug("Query vfModule enter:" + vfModuleName); + MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId); + + try { + int respStatus = HttpStatus.SC_OK; + QueryVfModuleResponse qryResp = new QueryVfModuleResponse(aaiVnfId, aaiVfModuleId, null, null, null); + Holder<Boolean> vnfExists = new Holder<>(); + Holder<String> vfModuleId = new Holder<>(); + Holder<VnfStatus> status = new Holder<>(); + Holder<Map<String, String>> outputs = new Holder<>(); + vnfAdapter.queryVnf(cloudSiteId, cloudOwner, tenantId, vfModuleName, msoRequest, vnfExists, vfModuleId, + status, outputs); + if (!vnfExists.value) { + logger.debug("vfModule not found"); + respStatus = HttpStatus.SC_NOT_FOUND; + } else { + logger.debug("vfModule found" + vfModuleId.value + ", status=" + status.value); + qryResp.setVfModuleId(vfModuleId.value); + qryResp.setVnfStatus(status.value); + qryResp.setVfModuleOutputs(outputs.value); + } + logger.debug("Query vfModule exit"); + return Response.status(respStatus).entity(new GenericEntity<QueryVfModuleResponse>(qryResp) {}).build(); + } catch (VnfException e) { + logger.error("{} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, "queryVfModule", + ErrorCode.BusinessProcesssError.getValue(), "VnfException - queryVfModule", e); + VfModuleExceptionResponse excResp = + new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.FALSE, null); + return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR) + .entity(new GenericEntity<VfModuleExceptionResponse>(excResp) {}).build(); + } + } + + /* + * URL: http://localhost:8080/vnfs/rest/v1/vnfs/<aaivnfid>/vf-modules REQUEST: {"createVfModuleRequest": + * {"cloudSiteId": "DAN", "tenantId": "214b428a1f554c02935e66330f6a5409", "vnfId": "somevnfid", "vfModuleId": + * "somemodid", "vfModuleName": "RaaVnf1", "vnfType": "ApacheVnf", "vfModuleParams": {"entry": [ {"key": + * "network_id", "value": "59ed7b41-2983-413f-ba93-e7d437433916"}, {"key": "subnet_id", "value": + * "086c9298-5c57-49b7-bb2b-6fd5730c5d92"}, {"key": "server_name_0", "value": "RaaVnf1"} ]}, "failIfExists": true, + * "messageId": "ra.1", "notificationUrl": "http://localhost:8089/vnfmock", "skipAAI": true, "msoRequest": { + * "requestId": "ra1", "serviceInstanceId": "sa1" }} } + */ + @POST + @Path("{aaiVnfId}/vf-modules") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "CreateVfModule", response = Response.class, notes = "Create a vnfModule") + @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully created"), + @ApiResponse(code = 202, message = "create vnfModule request has been successfully accepted (async only)"), + @ApiResponse(code = 500, message = "create vnfModule failed, examine entity object for details")}) + public Response createVfModule( + @ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId, + @ApiParam(value = "CreateVfModuleRequest", required = true) final CreateVfModuleRequest req) { + logger.debug("Create VfModule enter inside VnfAdapterRest: " + req.toJsonString()); + if (aaiVnfId == null || !aaiVnfId.equals(req.getVnfId())) { + logger.debug("Req rejected - aaiVnfId not provided or doesn't match URL"); + return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN) + .entity("vnfid in URL does not match content").build(); + } + CreateVfModuleTask task = new CreateVfModuleTask(req); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling create, send generic failure as sync resp to caller + logger.error("{} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR, "createVfModule", + ErrorCode.BusinessProcesssError, "Exception - createVfModule", e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("createVfModule exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class CreateVfModuleTask implements Runnable { + private final CreateVfModuleRequest req; + private CreateVfModuleResponse response = null; + private VfModuleExceptionResponse eresp = null; + private boolean sendxml; + + public CreateVfModuleTask(CreateVfModuleRequest req) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<CreateVfModuleResponse>(response) {} + : new GenericEntity<VfModuleExceptionResponse>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + logger.debug("CreateVfModuleTask start"); + try { + // Synchronous Web Service Outputs + Holder<String> vfModuleStackId = new Holder<>(); + Holder<Map<String, String>> outputs = new Holder<>(); + Holder<VnfRollback> vnfRollback = new Holder<>(); + String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); + logger.debug("completeVnfVfModuleType=" + completeVnfVfModuleType); + String cloudsite = req.getCloudSiteId(); + String cloudOwner = req.getCloudOwner(); + if (cloudsite != null && cloudsite.equals(TESTING_KEYWORD)) { + String tenant = req.getTenantId(); + if (tenant != null && tenant.equals(TESTING_KEYWORD)) { + throw new VnfException("testing."); + } + vnfRollback.value = new VnfRollback(req.getVnfId(), tenant, cloudOwner, cloudsite, true, false, + new MsoRequest("reqid", "svcid"), req.getVolumeGroupId(), req.getVolumeGroupId(), + req.getRequestType(), req.getModelCustomizationUuid()); + vfModuleStackId.value = "479D3D8B-6360-47BC-AB75-21CC91981484"; + outputs.value = VolumeAdapterRest.testMap(); + } else { + // vnfAdapter.createVnf (createReq.getCloudSiteId(), + // createReq.getTenantId(), + // createReq.getVnfType(), + // createReq.getVnfVersion(), + // createReq.getVfModuleName(), + // createReq.getRequestType(), + // createReq.getVolumeGroupStackId(), + // createReq.getVfModuleParams(), + // createReq.getFailIfExists(), + // createReq.getBackout(), + // createReq.getMsoRequest(), + // vfModuleStackId, + // outputs, + // vnfRollback); + vnfAdapter.createVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + // req.getVnfType(), + completeVnfVfModuleType, req.getVnfVersion(), req.getVnfId(), req.getVfModuleName(), + req.getVfModuleId(), req.getRequestType(), req.getVolumeGroupStackId(), + req.getBaseVfModuleStackId(), req.getModelCustomizationUuid(), req.getVfModuleParams(), + req.getFailIfExists(), req.getBackout(), req.getEnableBridge(), req.getMsoRequest(), + vfModuleStackId, outputs, vnfRollback); + } + VfModuleRollback modRollback = new VfModuleRollback(vnfRollback.value, req.getVfModuleId(), + vfModuleStackId.value, req.getMessageId()); + response = new CreateVfModuleResponse(req.getVnfId(), req.getVfModuleId(), vfModuleStackId.value, + Boolean.TRUE, outputs.value, modRollback, req.getMessageId()); + } catch (VnfException e) { + logger.debug("Exception :", e); + eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, + req.getMessageId()); + } + if (!req.isSynchronous()) { + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("CreateVfModuleTask exit: code=" + getStatusCode() + RESP + getResponse()); + } + } + + @PUT + @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "UpdateVfModule", response = Response.class, notes = "Update an existing vnfModule") + @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully updated"), + @ApiResponse(code = 202, message = "update vnfModule request has been successfully accepted (async only)"), + @ApiResponse(code = 500, message = "update vnfModule failed, examine entity object for details")}) + public Response updateVfModule( + @ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId, + @ApiParam(value = "aaiVfModuleId", required = true) @PathParam("aaiVfModuleId") String aaiVfModuleId, + @ApiParam(value = "UpdateVfModuleRequest", required = true) final UpdateVfModuleRequest req) { + logger.debug("Update VfModule enter: " + req.toJsonString()); + UpdateVfModulesTask task = new UpdateVfModulesTask(req); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling create, send generic failure as sync resp to caller + logger.error("{} {} {} {}", MessageEnum.RA_UPDATE_VNF_ERR.toString(), "updateVfModule", + ErrorCode.BusinessProcesssError.getValue(), "Exception - updateVfModule", e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("updateVfModules exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class UpdateVfModulesTask implements Runnable { + private final UpdateVfModuleRequest req; + private UpdateVfModuleResponse response = null; + private VfModuleExceptionResponse eresp = null; + private boolean sendxml; + + public UpdateVfModulesTask(UpdateVfModuleRequest req) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<UpdateVfModuleResponse>(response) {} + : new GenericEntity<VfModuleExceptionResponse>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + try { + // MsoVnfAdapter vnfAdapter = new MsoVnfAdapterImpl (msoPropertiesFactory, cloudConfigFactory); + + // Synchronous Web Service Outputs + Holder<String> vfModuleStackId = new Holder<>(); + Holder<Map<String, String>> outputs = new Holder<>(); + Holder<VnfRollback> vnfRollback = new Holder<>(); + String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); + logger.debug("in updateVf - completeVnfVfModuleType=" + completeVnfVfModuleType); + + vnfAdapter.updateVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + // req.getVnfType(), + completeVnfVfModuleType, req.getVnfVersion(), req.getVfModuleName(), req.getRequestType(), + req.getVolumeGroupStackId(), req.getBaseVfModuleStackId(), req.getVfModuleStackId(), + req.getModelCustomizationUuid(), req.getVfModuleParams(), req.getMsoRequest(), outputs, + vnfRollback); + + response = new UpdateVfModuleResponse(req.getVnfId(), req.getVfModuleId(), vfModuleStackId.value, + outputs.value, req.getMessageId()); + } catch (VnfException e) { + logger.debug("Exception :", e); + eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, + req.getMessageId()); + } + if (!req.isSynchronous()) { + // This is asynch, so POST response back to caller + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("Update VfModule exit: code=" + getStatusCode() + RESP + getResponse()); + } + } + + /* + * URL:http://localhost:8080/vnfs/rest/v1/vnfs/<aaivnfid>/vf-modules/<aaimodid>/rollback REQUEST: + * {"deleteVfModuleRequest": {"cloudSiteId": "DAN", "tenantId": "214b428a1f554c02935e66330f6a5409", "vnfId": + * "somevnfid", "vfModuleId": "somemodid", "vfModuleStackId": "4e567676-e266-4594-a3a6-131c8a2baf73", "messageId": + * "ra.1", "notificationUrl": "http://localhost:8089/vnfmock", "skipAAI": true, "msoRequest": { "requestId": "ra1", + * "serviceInstanceId": "sa1" }} } + */ + @DELETE + @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}/rollback") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "RollbackVfModule", response = Response.class, notes = "Rollback an existing vnfModule") + @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully rolled back"), + @ApiResponse(code = 202, + message = "rollback vnfModule request has been successfully accepted (async only)"), + @ApiResponse(code = 500, message = "rollback vnfModule failed, examine entity object for details")}) + public Response rollbackVfModule( + @ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId, + @ApiParam(value = "aaiVfModuleId", required = true) @PathParam("aaiVfModuleId") String aaiVfModuleId, + @ApiParam(value = "RollbackVfModuleRequest", required = true) + // @QueryParam("rollback") String rollback, + final RollbackVfModuleRequest req) { + logger.debug("Rollback VfModule enter: " + req.toJsonString()); + RollbackVfModulesTask task = new RollbackVfModulesTask(req); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling create, send generic failure as sync resp to caller + logger.error("{} {} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR.toString(), "rollbackVfModule", + ErrorCode.BusinessProcesssError.getValue(), "Exception - rollbackVfModule", e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("rollbackVfModule exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class RollbackVfModulesTask implements Runnable { + private final RollbackVfModuleRequest req; + private RollbackVfModuleResponse response = null; + private VfModuleExceptionResponse eresp = null; + private boolean sendxml; + + public RollbackVfModulesTask(RollbackVfModuleRequest req) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<RollbackVfModuleResponse>(response) {} + : new GenericEntity<VfModuleExceptionResponse>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + try { + VfModuleRollback vmr = req.getVfModuleRollback(); + VnfRollback vrb = new VnfRollback(vmr.getVfModuleStackId(), vmr.getTenantId(), vmr.getCloudOwner(), + vmr.getCloudSiteId(), true, true, vmr.getMsoRequest(), null, null, null, null); + vnfAdapter.rollbackVnf(vrb); + response = new RollbackVfModuleResponse(Boolean.TRUE, req.getMessageId()); + } catch (VnfException e) { + logger.error("{} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR, ErrorCode.BusinessProcesssError, + "Exception" + " - " + "rollbackVfModule", e); + eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, false, + req.getMessageId()); + } + if (!req.isSynchronous()) { + // This is asynch, so POST response back to caller + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("RollbackVfModulesTask exit: code=" + getStatusCode() + RESP + getResponse()); + } + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestUtils.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestUtils.java index 8c96acc361..b53ac0f899 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestUtils.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestUtils.java @@ -23,7 +23,6 @@ package org.onap.so.adapters.vnf; import java.util.Optional; - import org.onap.so.cloud.CloudConfig; import org.onap.so.db.catalog.beans.CloudSite; import org.slf4j.Logger; @@ -32,80 +31,74 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component -public class VnfAdapterRestUtils -{ - private static Logger logger = LoggerFactory.getLogger(VnfAdapterRestUtils.class); - - private static final String HEAT_MODE = "HEAT"; - private static final String CLOUDIFY_MODE = "CLOUDIFY"; - private static final String MULTICLOUD_MODE = "MULTICLOUD"; - - @Autowired - private CloudConfig cloudConfig; - - @Autowired - private MsoVnfCloudifyAdapterImpl cloudifyImpl; - - @Autowired - private MsoVnfAdapterImpl vnfImpl; - - @Autowired - private MsoVnfPluginAdapterImpl vnfPluginImpl; - - /* - * Choose which implementation of VNF Adapter to use, based on the orchestration mode. - * Currently, the two supported orchestrators are HEAT and CLOUDIFY. - */ - public MsoVnfAdapter getVnfAdapterImpl (String mode, String cloudSiteId) - { - // First, determine the orchestration mode to use. - // If was explicitly provided as a parameter, use that. Else if specified for the - // cloudsite, use that. Otherwise, the default is the (original) HEAT-based impl. - - logger.debug("Entered GetVnfAdapterImpl: mode=" + mode + ", cloudSite=" + cloudSiteId); - - if (mode == null) { - // Didn't get an explicit mode type requested. - // Use the CloudSite to determine which Impl to use, based on whether the target cloutSite - // has a CloudifyManager assigned to it - Optional<CloudSite> cloudSite = cloudConfig.getCloudSite(cloudSiteId); - if (cloudSite.isPresent()) { - logger.debug("Got CloudSite: " + cloudSite.toString()); - if (cloudConfig.getCloudifyManager(cloudSite.get().getCloudifyId()) != null) { - mode = CLOUDIFY_MODE; - } else if (MULTICLOUD_MODE.equalsIgnoreCase(cloudSite.get().getOrchestrator())) { - mode = MULTICLOUD_MODE; - } - else { - mode = HEAT_MODE; - } - } - } - - logger.debug ("GetVnfAdapterImpl: mode=" + mode); - - MsoVnfAdapter vnfAdapter = null; - - // TODO: Make this more dynamic (e.g. Service Loader) - if (CLOUDIFY_MODE.equalsIgnoreCase(mode)) { - logger.debug("GetVnfAdapterImpl: Return Cloudify Adapter"); - vnfAdapter = cloudifyImpl; - } - else if (HEAT_MODE.equalsIgnoreCase(mode)) { - logger.debug("GetVnfAdapterImpl: Return Heat Adapter"); - vnfAdapter = vnfImpl; - } - else if (MULTICLOUD_MODE.equalsIgnoreCase(mode)) { - logger.debug("GetVnfAdapterImpl: Return Plugin (multicloud) Adapter"); - vnfAdapter = vnfPluginImpl; - } - else { - // Don't expect this, but default is the HEAT adapter - logger.debug("GetVnfAdapterImpl: Return Default (Heat) Adapter"); - vnfAdapter = vnfImpl; - } - - return vnfAdapter; - } +public class VnfAdapterRestUtils { + private static Logger logger = LoggerFactory.getLogger(VnfAdapterRestUtils.class); + + private static final String HEAT_MODE = "HEAT"; + private static final String CLOUDIFY_MODE = "CLOUDIFY"; + private static final String MULTICLOUD_MODE = "MULTICLOUD"; + + @Autowired + private CloudConfig cloudConfig; + + @Autowired + private MsoVnfCloudifyAdapterImpl cloudifyImpl; + + @Autowired + private MsoVnfAdapterImpl vnfImpl; + + @Autowired + private MsoVnfPluginAdapterImpl vnfPluginImpl; + + /* + * Choose which implementation of VNF Adapter to use, based on the orchestration mode. Currently, the two supported + * orchestrators are HEAT and CLOUDIFY. + */ + public MsoVnfAdapter getVnfAdapterImpl(String mode, String cloudSiteId) { + // First, determine the orchestration mode to use. + // If was explicitly provided as a parameter, use that. Else if specified for the + // cloudsite, use that. Otherwise, the default is the (original) HEAT-based impl. + + logger.debug("Entered GetVnfAdapterImpl: mode=" + mode + ", cloudSite=" + cloudSiteId); + + if (mode == null) { + // Didn't get an explicit mode type requested. + // Use the CloudSite to determine which Impl to use, based on whether the target cloutSite + // has a CloudifyManager assigned to it + Optional<CloudSite> cloudSite = cloudConfig.getCloudSite(cloudSiteId); + if (cloudSite.isPresent()) { + logger.debug("Got CloudSite: " + cloudSite.toString()); + if (cloudConfig.getCloudifyManager(cloudSite.get().getCloudifyId()) != null) { + mode = CLOUDIFY_MODE; + } else if (MULTICLOUD_MODE.equalsIgnoreCase(cloudSite.get().getOrchestrator())) { + mode = MULTICLOUD_MODE; + } else { + mode = HEAT_MODE; + } + } + } + + logger.debug("GetVnfAdapterImpl: mode=" + mode); + + MsoVnfAdapter vnfAdapter = null; + + // TODO: Make this more dynamic (e.g. Service Loader) + if (CLOUDIFY_MODE.equalsIgnoreCase(mode)) { + logger.debug("GetVnfAdapterImpl: Return Cloudify Adapter"); + vnfAdapter = cloudifyImpl; + } else if (HEAT_MODE.equalsIgnoreCase(mode)) { + logger.debug("GetVnfAdapterImpl: Return Heat Adapter"); + vnfAdapter = vnfImpl; + } else if (MULTICLOUD_MODE.equalsIgnoreCase(mode)) { + logger.debug("GetVnfAdapterImpl: Return Plugin (multicloud) Adapter"); + vnfAdapter = vnfPluginImpl; + } else { + // Don't expect this, but default is the HEAT adapter + logger.debug("GetVnfAdapterImpl: Return Default (Heat) Adapter"); + vnfAdapter = vnfImpl; + } + + return vnfAdapter; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java index 41d350d765..440b0dae0a 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java @@ -25,7 +25,6 @@ package org.onap.so.adapters.vnf; import java.util.Map; - import javax.inject.Provider; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -40,7 +39,6 @@ import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.ws.Holder; - import org.apache.http.HttpStatus; import org.onap.so.adapters.vnf.exceptions.VnfException; import org.onap.so.adapters.vnfrest.CreateVfModuleRequest; @@ -64,7 +62,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; - import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @@ -72,651 +69,535 @@ import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; /** - * This class services calls to the REST interface for VF Modules (http://host:port/vnfs/rest/v2/vnfs) - * Both XML and JSON can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default. - * For testing, call with cloudSiteId = ___TESTING___ - * To test exceptions, also set tenantId = ___TESTING___ + * This class services calls to the REST interface for VF Modules (http://host:port/vnfs/rest/v2/vnfs) Both XML and JSON + * can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default. For testing, call + * with cloudSiteId = ___TESTING___ To test exceptions, also set tenantId = ___TESTING___ * - * V2 incorporates run-time selection of sub-orchestrator implementation (Heat or Cloudify) - * based on the target cloud. + * V2 incorporates run-time selection of sub-orchestrator implementation (Heat or Cloudify) based on the target cloud. */ @Path("/v2/vnfs") @Api(value = "/v2/vnfs", description = "root of vnf adapters restful web service v2") @Component public class VnfAdapterRestV2 { - private static Logger logger = LoggerFactory.getLogger(VnfAdapterRestV2.class); - private static final String TESTING_KEYWORD = "___TESTING___"; - private static final String RESP=", resp="; - - @Autowired - private VnfAdapterRestUtils vnfAdapterRestUtils; - - @Autowired - private Provider<BpelRestClient> bpelRestClientProvider; - - /* - * URL:http://localhost:8080/vnfs/rest/v2/vnfs/<aaivnfid>/vf-modules/<aaimodid> - * REQUEST: - * {"deleteVfModuleRequest": - {"cloudSiteId": "DAN", - "tenantId": "214b428a1f554c02935e66330f6a5409", - "vnfId": "somevnfid", - "vfModuleId": "somemodid", - "vfModuleStackId": "4e567676-e266-4594-a3a6-131c8a2baf73", - "messageId": "ra.1", - "notificationUrl": "http://localhost:8089/vnfmock", - "skipAAI": true, - "msoRequest": { - "requestId": "ra1", - "serviceInstanceId": "sa1" - }} - } - */ - @DELETE - @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "DeleteVfModule", - response = Response.class, - notes = "Delete an existing vnfModule, DeleteVfModuleRequest JSON is required") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfModule has been successfully deleted"), - @ApiResponse(code = 202, message = "delete vnfModule request has been accepted (async only)"), - @ApiResponse(code = 500, message = "delete vnfModule failed, examine entity object for details") }) - public Response deleteVfModule ( - @ApiParam(value = "aaiVnfId", required = true) - @PathParam("aaiVnfId") String aaiVnfId, - @ApiParam(value = "aaiVfModuleId", required = true) - @PathParam("aaiVfModuleId") String aaiVfModuleId, - @ApiParam(value = "mode", required = true) - @QueryParam("mode") String mode, - @ApiParam(value = "DeleteVfModuleRequest", required = true) - final DeleteVfModuleRequest req) - { - logger.debug("Delete VfModule enter: " + req.toJsonString()); - if (aaiVnfId == null || !aaiVnfId.equals(req.getVnfId())) { - logger.debug("Req rejected - aaiVnfId not provided or doesn't match URL"); - return Response - .status(HttpStatus.SC_BAD_REQUEST) - .type(MediaType.TEXT_PLAIN) - .entity("vnfid in URL does not match content") - .build(); - } - if (aaiVfModuleId == null || !aaiVfModuleId.equals(req.getVfModuleId())) { - logger.debug("Req rejected - aaiVfModuleId not provided or doesn't match URL"); - return Response - .status(HttpStatus.SC_BAD_REQUEST) - .type(MediaType.TEXT_PLAIN) - .entity("vfModuleId in URL does not match content") - .build(); - } - - DeleteVfModuleTask task = new DeleteVfModuleTask(req, mode); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling delete, send generic failure as sync resp to caller - logger.error("{} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), "deleteVfModule", - ErrorCode.BusinessProcesssError.getValue(), "Exception in deleteVfModule", e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("deleteVNFVolumes exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class DeleteVfModuleTask implements Runnable { - private final DeleteVfModuleRequest req; - private DeleteVfModuleResponse response = null; - private VfModuleExceptionResponse eresp = null; - private boolean sendxml; - private String mode; - - public DeleteVfModuleTask(DeleteVfModuleRequest req, String mode) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - this.mode = mode; - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<DeleteVfModuleResponse>(response) {} - : new GenericEntity<VfModuleExceptionResponse>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - - @Override - public void run() { - try { - String cloudsite = req.getCloudSiteId(); - Holder<Map<String, String>> outputs = new Holder <Map <String, String>> (); - if (cloudsite != null && !cloudsite.equals(TESTING_KEYWORD)) { - //vnfAdapter.deleteVnf (req.getCloudSiteId(), req.getTenantId(), req.getVfModuleStackId(), req.getMsoRequest()); - // Support different Adapter Implementations - MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsite); - adapter.deleteVfModule (req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), req.getVfModuleStackId(), req.getMsoRequest(), outputs); - } - response = new DeleteVfModuleResponse(req.getVnfId(), req.getVfModuleId(), Boolean.TRUE, req.getMessageId(), outputs.value); - } catch (VnfException e) { - logger.error("{} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), - ErrorCode.BusinessProcesssError.getValue(), "VnfException - " + "Delete VNF Module", e); - eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, req.getMessageId()); - } - if (!req.isSynchronous()) { - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("Delete vfModule exit: code=" + getStatusCode() + RESP + getResponse()); - } - } - - /* - * URL:http://localhost:8080/vnfs/rest/v2/vnfs/<aaiVnfId>/vf-modules/<aaiVfModuleId>?cloudSiteId=DAN&tenantId=vfModule?&skipAAI=TRUE&msoRequest.requestId=ra1&msoRequest.serviceInstanceId=si1&vfModuleName=T2N2S1 - * RESP: - * {"queryVfModuleResponse": { - "vfModuleId": "AvfmodId", - "vfModuleOutputs": {"entry": { - "key": "server_private_ip_1", - "value": "10.100.1.25" - }}, - "vfModuleStackId": "RaaVnf1/abfa8a6d-feb1-40af-aea3-109403b1cf6b", - "vnfId": "AvnfID", - "vnfStatus": "ACTIVE" - }} - */ - @GET - @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}") - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "QueryVfModule", - response = Response.class, - notes = "Query an existing vnfModule") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfModule has been successfully queried"), - @ApiResponse(code = 500, message = "query vnfModule failed, examine entity object for details") }) - public Response queryVfModule( - @ApiParam(value = "aaiVnfId", required = true) - @PathParam("aaiVnfId") String aaiVnfId, - @ApiParam(value = "aaiVfModuleId", required = true) - @PathParam("aaiVfModuleId") String aaiVfModuleId, - @ApiParam(value = "cloudSiteId", required = true) - @QueryParam("cloudSiteId") String cloudSiteId, - @ApiParam(value = "cloudOwner", required = true) - @QueryParam("cloudOwner") String cloudOwner, - @ApiParam(value = "tenantId", required = true) - @QueryParam("tenantId") String tenantId, - @ApiParam(value = "vfModuleName", required = true) - @QueryParam("vfModuleName") String vfModuleName, //RAA? Id in doc - @ApiParam(value = "skipAAI", required = true) - @QueryParam("skipAAI") Boolean skipAAI, - @ApiParam(value = "msoRequest.requestId", required = true) - @QueryParam("msoRequest.requestId") String requestId, - @ApiParam(value = "msoRequest.serviceInstanceId", required = true) - @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId, - @ApiParam(value = "mode", required = true) - @QueryParam("mode") String mode) - { - //This request responds synchronously only - logger.debug("Query vfModule enter:" + vfModuleName); - MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId); - - try { - int respStatus = HttpStatus.SC_OK; - QueryVfModuleResponse qryResp = new QueryVfModuleResponse(aaiVnfId, aaiVfModuleId, null, null, null); - Holder<Boolean> vnfExists = new Holder<Boolean>(); - Holder<String> vfModuleId = new Holder<String>(); - Holder<VnfStatus> status = new Holder<VnfStatus>(); - Holder<Map<String, String>> outputs = new Holder <Map <String, String>> (); - - // Support different Adapter Implementations - MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudSiteId); - adapter.queryVnf (cloudSiteId, cloudOwner, tenantId, vfModuleName, msoRequest, vnfExists, vfModuleId, status, outputs); - - if (!vnfExists.value) { - logger.debug("vfModule not found"); - respStatus = HttpStatus.SC_NOT_FOUND; - } else { - logger.debug("vfModule found" + vfModuleId.value + ", status=" + status.value); - qryResp.setVfModuleId(vfModuleId.value); - qryResp.setVnfStatus(status.value); - qryResp.setVfModuleOutputs(outputs.value); - } - logger.debug ("Query vfModule exit"); - return Response - .status(respStatus) - .entity(new GenericEntity<QueryVfModuleResponse>(qryResp) {}) - .build(); - } catch (VnfException e) { - logger.error("{} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, "queryVfModule", - ErrorCode.BusinessProcesssError.getValue(), "VnfException - queryVfModule", e); - VfModuleExceptionResponse excResp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.FALSE, null); - return Response - .status(HttpStatus.SC_INTERNAL_SERVER_ERROR) - .entity(new GenericEntity<VfModuleExceptionResponse>(excResp) {}) - .build(); - } - } - - /*URL: http://localhost:8080/vnfs/rest/v2/vnfs/<aaivnfid>/vf-modules - *REQUEST: - * {"createVfModuleRequest": - {"cloudSiteId": "DAN", - "tenantId": "214b428a1f554c02935e66330f6a5409", - "vnfId": "somevnfid", - "vfModuleId": "somemodid", - "vfModuleName": "RaaVnf1", - "vnfType": "ApacheVnf", - "vfModuleParams": {"entry": [ - {"key": "network_id", - "value": "59ed7b41-2983-413f-ba93-e7d437433916"}, - {"key": "subnet_id", - "value": "086c9298-5c57-49b7-bb2b-6fd5730c5d92"}, - {"key": "server_name_0", - "value": "RaaVnf1"} - ]}, - "failIfExists": true, - "messageId": "ra.1", - "notificationUrl": "http://localhost:8089/vnfmock", - "skipAAI": true, - "msoRequest": { - "requestId": "ra1", - "serviceInstanceId": "sa1" - }} - } - */ - @POST - @Path("{aaiVnfId}/vf-modules") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "CreateVfModule", - response = Response.class, - notes = "Create a vnfModule") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfModule has been successfully created"), - @ApiResponse(code = 202, message = "create vnfModule request has been successfully accepted (async only)"), - @ApiResponse(code = 500, message = "create vnfModule failed, examine entity object for details") }) - public Response createVfModule( - @ApiParam(value = "aaiVnfId", required = true) - @PathParam("aaiVnfId") String aaiVnfId, - @ApiParam(value = "mode", required = true) - @QueryParam("mode") String mode, - @ApiParam(value = "CreateVfModuleRequest", required = true) - final CreateVfModuleRequest req) - { - logger.debug("Create VfModule enter inside VnfAdapterRest: " + req.toJsonString()); - if (aaiVnfId == null || !aaiVnfId.equals(req.getVnfId())) { - logger.debug("Req rejected - aaiVnfId not provided or doesn't match URL"); - return Response - .status(HttpStatus.SC_BAD_REQUEST) - .type(MediaType.TEXT_PLAIN) - .entity("vnfid in URL does not match content") - .build(); - } - - CreateVfModuleTask task = new CreateVfModuleTask(req, mode); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), "createVfModule", - ErrorCode.BusinessProcesssError.getValue(), "Exception - createVfModule", e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("createVfModule exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class CreateVfModuleTask implements Runnable { - private final CreateVfModuleRequest req; - private CreateVfModuleResponse response = null; - private VfModuleExceptionResponse eresp = null; - private boolean sendxml; - private String mode; - - public CreateVfModuleTask(CreateVfModuleRequest req, String mode) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - this.mode = mode; - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<CreateVfModuleResponse>(response) {} - : new GenericEntity<VfModuleExceptionResponse>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - - @Override - public void run() { - logger.debug("CreateVfModuleTask start"); - try { - // Synchronous Web Service Outputs - Holder <String> vfModuleStackId = new Holder <String> (); - Holder <Map <String, String>> outputs = new Holder <Map <String, String>> (); - Holder <VnfRollback> vnfRollback = new Holder <VnfRollback> (); - String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); - logger.debug("completeVnfVfModuleType=" + completeVnfVfModuleType); - - String cloudsiteId = req.getCloudSiteId(); - String cloudOwner = req.getCloudOwner(); - if (cloudsiteId != null && cloudsiteId.equals(TESTING_KEYWORD)) { - String tenant = req.getTenantId(); - if (tenant != null && tenant.equals(TESTING_KEYWORD)) { - throw new VnfException("testing."); - } - vnfRollback.value = new VnfRollback(req.getVnfId(), tenant, cloudOwner, cloudsiteId, - true, false, new MsoRequest("reqid", "svcid"), - req.getVolumeGroupId(), req.getVolumeGroupId(), req.getRequestType(), req.getModelCustomizationUuid()); - vfModuleStackId.value = "479D3D8B-6360-47BC-AB75-21CC91981484"; - outputs.value = VolumeAdapterRest.testMap(); - } else { - // Support different Adapter Implementations - MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsiteId); - adapter.createVfModule(req.getCloudSiteId(), - req.getCloudOwner(), - req.getTenantId(), - completeVnfVfModuleType, - req.getVnfVersion(), - req.getVnfId(), - req.getVfModuleName(), - req.getVfModuleId(), - req.getRequestType(), - req.getVolumeGroupStackId(), - req.getBaseVfModuleStackId(), - req.getModelCustomizationUuid(), - req.getVfModuleParams(), - req.getFailIfExists(), - req.getBackout(), - req.getEnableBridge(), - req.getMsoRequest(), - vfModuleStackId, - outputs, - vnfRollback); - } - VfModuleRollback modRollback = new VfModuleRollback(vnfRollback.value, req.getVfModuleId(), vfModuleStackId.value, req.getMessageId()); - response = new CreateVfModuleResponse(req.getVnfId(), req.getVfModuleId(), - vfModuleStackId.value, Boolean.TRUE, outputs.value, modRollback, req.getMessageId()); - } catch (VnfException e) { - eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, req.getMessageId()); - } - if (!req.isSynchronous()) { - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("CreateVfModuleTask exit: code=" + getStatusCode() + RESP + getResponse()); - } - } - - @PUT - @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "UpdateVfModule", - response = Response.class, - notes = "Update an existing vnfModule") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfModule has been successfully updated"), - @ApiResponse(code = 202, message = "update vnfModule request has been successfully accepted (async only)"), - @ApiResponse(code = 500, message = "update vnfModule failed, examine entity object for details") }) - public Response updateVfModule( - @ApiParam(value = "aaiVnfId", required = true) - @PathParam("aaiVnfId") String aaiVnfId, - @ApiParam(value = "aaiVfModuleId", required = true) - @PathParam("aaiVfModuleId") String aaiVfModuleId, - @ApiParam(value = "mode", required = true) - @QueryParam("mode") String mode, - @ApiParam(value = "UpdateVfModuleRequest", required = true) - final UpdateVfModuleRequest req) - { - logger.debug("Update VfModule enter: " + req.toJsonString()); - UpdateVfModulesTask task = new UpdateVfModulesTask(req, mode); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} {} {}", MessageEnum.RA_UPDATE_VNF_ERR.toString(), "updateVfModule", - ErrorCode.BusinessProcesssError.getValue(), "Exception - updateVfModule", e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("updateVfModules exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class UpdateVfModulesTask implements Runnable { - private final UpdateVfModuleRequest req; - private UpdateVfModuleResponse response = null; - private VfModuleExceptionResponse eresp = null; - private boolean sendxml; - private String mode; - - public UpdateVfModulesTask(UpdateVfModuleRequest req, String mode) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - this.mode = mode; - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<UpdateVfModuleResponse>(response) {} - : new GenericEntity<VfModuleExceptionResponse>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - @Override - public void run() { - try { - //MsoVnfAdapter vnfAdapter = new MsoVnfAdapterImpl (msoPropertiesFactory, cloudConfigFactory); - - // Synchronous Web Service Outputs - Holder <String> vfModuleStackId = new Holder <String> (); - Holder <Map <String, String>> outputs = new Holder <Map <String, String>> (); - Holder <VnfRollback> vnfRollback = new Holder <VnfRollback> (); - String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); - logger.debug("in updateVf - completeVnfVfModuleType=" + completeVnfVfModuleType); - - String cloudsiteId = req.getCloudSiteId(); - - // Support different Adapter Implementations - MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsiteId); - adapter.updateVfModule (req.getCloudSiteId(), - req.getCloudOwner(), - req.getTenantId(), - completeVnfVfModuleType, - req.getVnfVersion(), - req.getVfModuleName(), - req.getRequestType(), - req.getVolumeGroupStackId(), - req.getBaseVfModuleId(), - req.getVfModuleStackId(), - req.getModelCustomizationUuid(), - req.getVfModuleParams(), - req.getMsoRequest(), - outputs, - vnfRollback); - - response = new UpdateVfModuleResponse(req.getVnfId(), req.getVfModuleId(), - vfModuleStackId.value, outputs.value, req.getMessageId()); - } catch (VnfException e) { - eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, req.getMessageId()); - } - if (!req.isSynchronous()) { - // This is asynch, so POST response back to caller - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost (getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("Update VfModule exit: code=" + getStatusCode() + RESP + getResponse()); - } - } - /* - * URL:http://localhost:8080/vnfs/rest/v2/vnfs/<aaivnfid>/vf-modules/<aaimodid>/rollback - * REQUEST: - * {"deleteVfModuleRequest": - {"cloudSiteId": "DAN", - "tenantId": "214b428a1f554c02935e66330f6a5409", - "vnfId": "somevnfid", - "vfModuleId": "somemodid", - "vfModuleStackId": "4e567676-e266-4594-a3a6-131c8a2baf73", - "messageId": "ra.1", - "notificationUrl": "http://localhost:8089/vnfmock", - "skipAAI": true, - "msoRequest": { - "requestId": "ra1", - "serviceInstanceId": "sa1" - }} - } - */ - @DELETE - @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}/rollback") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "RollbackVfModule", - response = Response.class, - notes = "Rollback an existing vnfModule") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfModule has been successfully rolled back"), - @ApiResponse(code = 202, message = "rollback vnfModule request has been successfully accepted (async only)"), - @ApiResponse(code = 500, message = "rollback vnfModule failed, examine entity object for details") }) - public Response rollbackVfModule ( - @ApiParam(value = "aaiVnfId", required = true) - @PathParam("aaiVnfId") String aaiVnfId, - @ApiParam(value = "aaiVfModuleId", required = true) - @PathParam("aaiVfModuleId") String aaiVfModuleId, - @ApiParam(value = "RollbackVfModuleRequest", required = true) - //@QueryParam("rollback") String rollback, - final RollbackVfModuleRequest req) - { - logger.debug("Rollback VfModule enter: " + req.toJsonString()); - RollbackVfModulesTask task = new RollbackVfModulesTask(req); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR.toString(), "rollbackVfModule", - ErrorCode.BusinessProcesssError.getValue(), "Exception - rollbackVfModule", e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("rollbackVfModule exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class RollbackVfModulesTask implements Runnable { - private final RollbackVfModuleRequest req; - private RollbackVfModuleResponse response = null; - private VfModuleExceptionResponse eresp = null; - private boolean sendxml; - - public RollbackVfModulesTask(RollbackVfModuleRequest req) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<RollbackVfModuleResponse>(response) {} - : new GenericEntity<VfModuleExceptionResponse>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - @Override - public void run() { - try { - VfModuleRollback vmr = req.getVfModuleRollback(); - VnfRollback vrb = new VnfRollback( - vmr.getVfModuleStackId(), vmr.getTenantId(), vmr.getCloudOwner(), vmr.getCloudSiteId(), true, vmr.isVfModuleCreated(), - vmr.getMsoRequest(), null, null, null, null); - - // Support multiple adapter implementations - MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl (vmr.getMode(), vmr.getCloudSiteId()); - adapter.rollbackVnf (vrb); - - response = new RollbackVfModuleResponse(Boolean.TRUE, req.getMessageId()); - } catch (VnfException e) { - logger.error("{} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR.toString(), - ErrorCode.BusinessProcesssError.getValue(), "Exception - rollbackVfModule", e); - eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, false, req.getMessageId()); - } - if (!req.isSynchronous()) { - // This is asynch, so POST response back to caller - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost (getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("RollbackVfModulesTask exit: code=" + getStatusCode() + RESP + getResponse()); - } - } + private static Logger logger = LoggerFactory.getLogger(VnfAdapterRestV2.class); + private static final String TESTING_KEYWORD = "___TESTING___"; + private static final String RESP = ", resp="; + + @Autowired + private VnfAdapterRestUtils vnfAdapterRestUtils; + + @Autowired + private Provider<BpelRestClient> bpelRestClientProvider; + + /* + * URL:http://localhost:8080/vnfs/rest/v2/vnfs/<aaivnfid>/vf-modules/<aaimodid> REQUEST: {"deleteVfModuleRequest": + * {"cloudSiteId": "DAN", "tenantId": "214b428a1f554c02935e66330f6a5409", "vnfId": "somevnfid", "vfModuleId": + * "somemodid", "vfModuleStackId": "4e567676-e266-4594-a3a6-131c8a2baf73", "messageId": "ra.1", "notificationUrl": + * "http://localhost:8089/vnfmock", "skipAAI": true, "msoRequest": { "requestId": "ra1", "serviceInstanceId": "sa1" + * }} } + */ + @DELETE + @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "DeleteVfModule", response = Response.class, + notes = "Delete an existing vnfModule, DeleteVfModuleRequest JSON is required") + @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully deleted"), + @ApiResponse(code = 202, message = "delete vnfModule request has been accepted (async only)"), + @ApiResponse(code = 500, message = "delete vnfModule failed, examine entity object for details")}) + public Response deleteVfModule( + @ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId, + @ApiParam(value = "aaiVfModuleId", required = true) @PathParam("aaiVfModuleId") String aaiVfModuleId, + @ApiParam(value = "mode", required = true) @QueryParam("mode") String mode, + @ApiParam(value = "DeleteVfModuleRequest", required = true) final DeleteVfModuleRequest req) { + logger.debug("Delete VfModule enter: " + req.toJsonString()); + if (aaiVnfId == null || !aaiVnfId.equals(req.getVnfId())) { + logger.debug("Req rejected - aaiVnfId not provided or doesn't match URL"); + return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN) + .entity("vnfid in URL does not match content").build(); + } + if (aaiVfModuleId == null || !aaiVfModuleId.equals(req.getVfModuleId())) { + logger.debug("Req rejected - aaiVfModuleId not provided or doesn't match URL"); + return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN) + .entity("vfModuleId in URL does not match content").build(); + } + + DeleteVfModuleTask task = new DeleteVfModuleTask(req, mode); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling delete, send generic failure as sync resp to caller + logger.error("{} {} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), "deleteVfModule", + ErrorCode.BusinessProcesssError.getValue(), "Exception in deleteVfModule", e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("deleteVNFVolumes exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class DeleteVfModuleTask implements Runnable { + private final DeleteVfModuleRequest req; + private DeleteVfModuleResponse response = null; + private VfModuleExceptionResponse eresp = null; + private boolean sendxml; + private String mode; + + public DeleteVfModuleTask(DeleteVfModuleRequest req, String mode) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + this.mode = mode; + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<DeleteVfModuleResponse>(response) {} + : new GenericEntity<VfModuleExceptionResponse>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + try { + String cloudsite = req.getCloudSiteId(); + Holder<Map<String, String>> outputs = new Holder<Map<String, String>>(); + if (cloudsite != null && !cloudsite.equals(TESTING_KEYWORD)) { + // vnfAdapter.deleteVnf (req.getCloudSiteId(), req.getTenantId(), req.getVfModuleStackId(), + // req.getMsoRequest()); + // Support different Adapter Implementations + MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsite); + adapter.deleteVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + req.getVfModuleStackId(), req.getMsoRequest(), outputs); + } + response = new DeleteVfModuleResponse(req.getVnfId(), req.getVfModuleId(), Boolean.TRUE, + req.getMessageId(), outputs.value); + } catch (VnfException e) { + logger.error("{} {} {}", MessageEnum.RA_DELETE_VNF_ERR.toString(), + ErrorCode.BusinessProcesssError.getValue(), "VnfException - " + "Delete VNF Module", e); + eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, + req.getMessageId()); + } + if (!req.isSynchronous()) { + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("Delete vfModule exit: code=" + getStatusCode() + RESP + getResponse()); + } + } + + /* + * URL:http://localhost:8080/vnfs/rest/v2/vnfs/<aaiVnfId>/vf-modules/<aaiVfModuleId>?cloudSiteId=DAN&tenantId= + * vfModule?&skipAAI=TRUE&msoRequest.requestId=ra1&msoRequest.serviceInstanceId=si1&vfModuleName=T2N2S1 RESP: + * {"queryVfModuleResponse": { "vfModuleId": "AvfmodId", "vfModuleOutputs": {"entry": { "key": + * "server_private_ip_1", "value": "10.100.1.25" }}, "vfModuleStackId": + * "RaaVnf1/abfa8a6d-feb1-40af-aea3-109403b1cf6b", "vnfId": "AvnfID", "vnfStatus": "ACTIVE" }} + */ + @GET + @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}") + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "QueryVfModule", response = Response.class, notes = "Query an existing vnfModule") + @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully queried"), + @ApiResponse(code = 500, message = "query vnfModule failed, examine entity object for details")}) + public Response queryVfModule(@ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId, + @ApiParam(value = "aaiVfModuleId", required = true) @PathParam("aaiVfModuleId") String aaiVfModuleId, + @ApiParam(value = "cloudSiteId", required = true) @QueryParam("cloudSiteId") String cloudSiteId, + @ApiParam(value = "cloudOwner", required = true) @QueryParam("cloudOwner") String cloudOwner, + @ApiParam(value = "tenantId", required = true) @QueryParam("tenantId") String tenantId, + @ApiParam(value = "vfModuleName", required = true) @QueryParam("vfModuleName") String vfModuleName, // RAA? + // Id in + // doc + @ApiParam(value = "skipAAI", required = true) @QueryParam("skipAAI") Boolean skipAAI, + @ApiParam(value = "msoRequest.requestId", + required = true) @QueryParam("msoRequest.requestId") String requestId, + @ApiParam(value = "msoRequest.serviceInstanceId", + required = true) @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId, + @ApiParam(value = "mode", required = true) @QueryParam("mode") String mode) { + // This request responds synchronously only + logger.debug("Query vfModule enter:" + vfModuleName); + MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId); + + try { + int respStatus = HttpStatus.SC_OK; + QueryVfModuleResponse qryResp = new QueryVfModuleResponse(aaiVnfId, aaiVfModuleId, null, null, null); + Holder<Boolean> vnfExists = new Holder<Boolean>(); + Holder<String> vfModuleId = new Holder<String>(); + Holder<VnfStatus> status = new Holder<VnfStatus>(); + Holder<Map<String, String>> outputs = new Holder<Map<String, String>>(); + + // Support different Adapter Implementations + MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudSiteId); + adapter.queryVnf(cloudSiteId, cloudOwner, tenantId, vfModuleName, msoRequest, vnfExists, vfModuleId, status, + outputs); + + if (!vnfExists.value) { + logger.debug("vfModule not found"); + respStatus = HttpStatus.SC_NOT_FOUND; + } else { + logger.debug("vfModule found" + vfModuleId.value + ", status=" + status.value); + qryResp.setVfModuleId(vfModuleId.value); + qryResp.setVnfStatus(status.value); + qryResp.setVfModuleOutputs(outputs.value); + } + logger.debug("Query vfModule exit"); + return Response.status(respStatus).entity(new GenericEntity<QueryVfModuleResponse>(qryResp) {}).build(); + } catch (VnfException e) { + logger.error("{} {} {} {} {}", MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, "queryVfModule", + ErrorCode.BusinessProcesssError.getValue(), "VnfException - queryVfModule", e); + VfModuleExceptionResponse excResp = + new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.FALSE, null); + return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR) + .entity(new GenericEntity<VfModuleExceptionResponse>(excResp) {}).build(); + } + } + + /* + * URL: http://localhost:8080/vnfs/rest/v2/vnfs/<aaivnfid>/vf-modules REQUEST: {"createVfModuleRequest": + * {"cloudSiteId": "DAN", "tenantId": "214b428a1f554c02935e66330f6a5409", "vnfId": "somevnfid", "vfModuleId": + * "somemodid", "vfModuleName": "RaaVnf1", "vnfType": "ApacheVnf", "vfModuleParams": {"entry": [ {"key": + * "network_id", "value": "59ed7b41-2983-413f-ba93-e7d437433916"}, {"key": "subnet_id", "value": + * "086c9298-5c57-49b7-bb2b-6fd5730c5d92"}, {"key": "server_name_0", "value": "RaaVnf1"} ]}, "failIfExists": true, + * "messageId": "ra.1", "notificationUrl": "http://localhost:8089/vnfmock", "skipAAI": true, "msoRequest": { + * "requestId": "ra1", "serviceInstanceId": "sa1" }} } + */ + @POST + @Path("{aaiVnfId}/vf-modules") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "CreateVfModule", response = Response.class, notes = "Create a vnfModule") + @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully created"), + @ApiResponse(code = 202, message = "create vnfModule request has been successfully accepted (async only)"), + @ApiResponse(code = 500, message = "create vnfModule failed, examine entity object for details")}) + public Response createVfModule( + @ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId, + @ApiParam(value = "mode", required = true) @QueryParam("mode") String mode, + @ApiParam(value = "CreateVfModuleRequest", required = true) final CreateVfModuleRequest req) { + logger.debug("Create VfModule enter inside VnfAdapterRest: " + req.toJsonString()); + if (aaiVnfId == null || !aaiVnfId.equals(req.getVnfId())) { + logger.debug("Req rejected - aaiVnfId not provided or doesn't match URL"); + return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN) + .entity("vnfid in URL does not match content").build(); + } + + CreateVfModuleTask task = new CreateVfModuleTask(req, mode); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling create, send generic failure as sync resp to caller + logger.error("{} {} {} {}", MessageEnum.RA_CREATE_VNF_ERR.toString(), "createVfModule", + ErrorCode.BusinessProcesssError.getValue(), "Exception - createVfModule", e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("createVfModule exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class CreateVfModuleTask implements Runnable { + private final CreateVfModuleRequest req; + private CreateVfModuleResponse response = null; + private VfModuleExceptionResponse eresp = null; + private boolean sendxml; + private String mode; + + public CreateVfModuleTask(CreateVfModuleRequest req, String mode) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + this.mode = mode; + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<CreateVfModuleResponse>(response) {} + : new GenericEntity<VfModuleExceptionResponse>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + logger.debug("CreateVfModuleTask start"); + try { + // Synchronous Web Service Outputs + Holder<String> vfModuleStackId = new Holder<String>(); + Holder<Map<String, String>> outputs = new Holder<Map<String, String>>(); + Holder<VnfRollback> vnfRollback = new Holder<VnfRollback>(); + String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); + logger.debug("completeVnfVfModuleType=" + completeVnfVfModuleType); + + String cloudsiteId = req.getCloudSiteId(); + String cloudOwner = req.getCloudOwner(); + if (cloudsiteId != null && cloudsiteId.equals(TESTING_KEYWORD)) { + String tenant = req.getTenantId(); + if (tenant != null && tenant.equals(TESTING_KEYWORD)) { + throw new VnfException("testing."); + } + vnfRollback.value = new VnfRollback(req.getVnfId(), tenant, cloudOwner, cloudsiteId, true, false, + new MsoRequest("reqid", "svcid"), req.getVolumeGroupId(), req.getVolumeGroupId(), + req.getRequestType(), req.getModelCustomizationUuid()); + vfModuleStackId.value = "479D3D8B-6360-47BC-AB75-21CC91981484"; + outputs.value = VolumeAdapterRest.testMap(); + } else { + // Support different Adapter Implementations + MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsiteId); + adapter.createVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + completeVnfVfModuleType, req.getVnfVersion(), req.getVnfId(), req.getVfModuleName(), + req.getVfModuleId(), req.getRequestType(), req.getVolumeGroupStackId(), + req.getBaseVfModuleStackId(), req.getModelCustomizationUuid(), req.getVfModuleParams(), + req.getFailIfExists(), req.getBackout(), req.getEnableBridge(), req.getMsoRequest(), + vfModuleStackId, outputs, vnfRollback); + } + VfModuleRollback modRollback = new VfModuleRollback(vnfRollback.value, req.getVfModuleId(), + vfModuleStackId.value, req.getMessageId()); + response = new CreateVfModuleResponse(req.getVnfId(), req.getVfModuleId(), vfModuleStackId.value, + Boolean.TRUE, outputs.value, modRollback, req.getMessageId()); + } catch (VnfException e) { + eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, + req.getMessageId()); + } + if (!req.isSynchronous()) { + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("CreateVfModuleTask exit: code=" + getStatusCode() + RESP + getResponse()); + } + } + + @PUT + @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "UpdateVfModule", response = Response.class, notes = "Update an existing vnfModule") + @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully updated"), + @ApiResponse(code = 202, message = "update vnfModule request has been successfully accepted (async only)"), + @ApiResponse(code = 500, message = "update vnfModule failed, examine entity object for details")}) + public Response updateVfModule( + @ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId, + @ApiParam(value = "aaiVfModuleId", required = true) @PathParam("aaiVfModuleId") String aaiVfModuleId, + @ApiParam(value = "mode", required = true) @QueryParam("mode") String mode, + @ApiParam(value = "UpdateVfModuleRequest", required = true) final UpdateVfModuleRequest req) { + logger.debug("Update VfModule enter: " + req.toJsonString()); + UpdateVfModulesTask task = new UpdateVfModulesTask(req, mode); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling create, send generic failure as sync resp to caller + logger.error("{} {} {} {}", MessageEnum.RA_UPDATE_VNF_ERR.toString(), "updateVfModule", + ErrorCode.BusinessProcesssError.getValue(), "Exception - updateVfModule", e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("updateVfModules exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class UpdateVfModulesTask implements Runnable { + private final UpdateVfModuleRequest req; + private UpdateVfModuleResponse response = null; + private VfModuleExceptionResponse eresp = null; + private boolean sendxml; + private String mode; + + public UpdateVfModulesTask(UpdateVfModuleRequest req, String mode) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + this.mode = mode; + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<UpdateVfModuleResponse>(response) {} + : new GenericEntity<VfModuleExceptionResponse>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + try { + // MsoVnfAdapter vnfAdapter = new MsoVnfAdapterImpl (msoPropertiesFactory, cloudConfigFactory); + + // Synchronous Web Service Outputs + Holder<String> vfModuleStackId = new Holder<String>(); + Holder<Map<String, String>> outputs = new Holder<Map<String, String>>(); + Holder<VnfRollback> vnfRollback = new Holder<VnfRollback>(); + String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); + logger.debug("in updateVf - completeVnfVfModuleType=" + completeVnfVfModuleType); + + String cloudsiteId = req.getCloudSiteId(); + + // Support different Adapter Implementations + MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsiteId); + adapter.updateVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + completeVnfVfModuleType, req.getVnfVersion(), req.getVfModuleName(), req.getRequestType(), + req.getVolumeGroupStackId(), req.getBaseVfModuleId(), req.getVfModuleStackId(), + req.getModelCustomizationUuid(), req.getVfModuleParams(), req.getMsoRequest(), outputs, + vnfRollback); + + response = new UpdateVfModuleResponse(req.getVnfId(), req.getVfModuleId(), vfModuleStackId.value, + outputs.value, req.getMessageId()); + } catch (VnfException e) { + eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.TRUE, + req.getMessageId()); + } + if (!req.isSynchronous()) { + // This is asynch, so POST response back to caller + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("Update VfModule exit: code=" + getStatusCode() + RESP + getResponse()); + } + } + + /* + * URL:http://localhost:8080/vnfs/rest/v2/vnfs/<aaivnfid>/vf-modules/<aaimodid>/rollback REQUEST: + * {"deleteVfModuleRequest": {"cloudSiteId": "DAN", "tenantId": "214b428a1f554c02935e66330f6a5409", "vnfId": + * "somevnfid", "vfModuleId": "somemodid", "vfModuleStackId": "4e567676-e266-4594-a3a6-131c8a2baf73", "messageId": + * "ra.1", "notificationUrl": "http://localhost:8089/vnfmock", "skipAAI": true, "msoRequest": { "requestId": "ra1", + * "serviceInstanceId": "sa1" }} } + */ + @DELETE + @Path("{aaiVnfId}/vf-modules/{aaiVfModuleId}/rollback") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "RollbackVfModule", response = Response.class, notes = "Rollback an existing vnfModule") + @ApiResponses({@ApiResponse(code = 200, message = "vnfModule has been successfully rolled back"), + @ApiResponse(code = 202, + message = "rollback vnfModule request has been successfully accepted (async only)"), + @ApiResponse(code = 500, message = "rollback vnfModule failed, examine entity object for details")}) + public Response rollbackVfModule( + @ApiParam(value = "aaiVnfId", required = true) @PathParam("aaiVnfId") String aaiVnfId, + @ApiParam(value = "aaiVfModuleId", required = true) @PathParam("aaiVfModuleId") String aaiVfModuleId, + @ApiParam(value = "RollbackVfModuleRequest", required = true) + // @QueryParam("rollback") String rollback, + final RollbackVfModuleRequest req) { + logger.debug("Rollback VfModule enter: " + req.toJsonString()); + RollbackVfModulesTask task = new RollbackVfModulesTask(req); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling create, send generic failure as sync resp to caller + logger.error("{} {} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR.toString(), "rollbackVfModule", + ErrorCode.BusinessProcesssError.getValue(), "Exception - rollbackVfModule", e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("rollbackVfModule exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class RollbackVfModulesTask implements Runnable { + private final RollbackVfModuleRequest req; + private RollbackVfModuleResponse response = null; + private VfModuleExceptionResponse eresp = null; + private boolean sendxml; + + public RollbackVfModulesTask(RollbackVfModuleRequest req) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<RollbackVfModuleResponse>(response) {} + : new GenericEntity<VfModuleExceptionResponse>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + try { + VfModuleRollback vmr = req.getVfModuleRollback(); + VnfRollback vrb = new VnfRollback(vmr.getVfModuleStackId(), vmr.getTenantId(), vmr.getCloudOwner(), + vmr.getCloudSiteId(), true, vmr.isVfModuleCreated(), vmr.getMsoRequest(), null, null, null, + null); + + // Support multiple adapter implementations + MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(vmr.getMode(), vmr.getCloudSiteId()); + adapter.rollbackVnf(vrb); + + response = new RollbackVfModuleResponse(Boolean.TRUE, req.getMessageId()); + } catch (VnfException e) { + logger.error("{} {} {}", MessageEnum.RA_ROLLBACK_VNF_ERR.toString(), + ErrorCode.BusinessProcesssError.getValue(), "Exception - rollbackVfModule", e); + eresp = new VfModuleExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, false, + req.getMessageId()); + } + if (!req.isSynchronous()) { + // This is asynch, so POST response back to caller + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("RollbackVfModulesTask exit: code=" + getStatusCode() + RESP + getResponse()); + } + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRest.java index e7d7b56624..c02a872a85 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRest.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRest.java @@ -71,10 +71,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** - * This class services calls to the REST interface for VNF Volumes (http://host:port/vnfs/rest/v1/volume-groups) - * Both XML and JSON can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default. - * For testing, call with cloudSiteId = ___TESTING___ - * To test exceptions, also set tenantId = ___TESTING___ + * This class services calls to the REST interface for VNF Volumes (http://host:port/vnfs/rest/v1/volume-groups) Both + * XML and JSON can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default. For + * testing, call with cloudSiteId = ___TESTING___ To test exceptions, also set tenantId = ___TESTING___ */ @Path("/v1/volume-groups") @Api(value = "/v1/volume-groups", description = "root of volume-groups adapters restful web service") @@ -82,580 +81,524 @@ import org.springframework.stereotype.Component; public class VolumeAdapterRest { private static final Logger logger = LoggerFactory.getLogger(VolumeAdapterRest.class); - private static final String TESTING_KEYWORD = "___TESTING___"; - private static final String EXCEPTION="Exception :"; - private static final String RESP=", resp="; - private static final String VOLUME_GROUPID_IN_URL_DOESNT_MATCH_CONTENT="VolumeGroupId in URL does not match content"; - @Autowired - private MsoVnfAdapterImpl vnfAdapter; - - @Autowired - private Provider<BpelRestClient> bpelRestClientProvider; - - @POST - @Path("") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "CreateVNFVolumes", - response = Response.class, - notes = "Create a new vnfVolume") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfVolume has been successfully created"), - @ApiResponse(code = 202, message = "create vnfVolume request has been successfully accepted (async only)"), - @ApiResponse(code = 500, message = "create vnfVolume failed, examine entity object for details") }) - public Response createVNFVolumes( - @ApiParam(value = "CreateVolumeGroupRequest", required = true) - final CreateVolumeGroupRequest req - ) { - logger.debug("createVNFVolumes enter: {}", req.toJsonString()); - CreateVNFVolumesTask task = new CreateVNFVolumesTask(req); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} Exception - createVNFVolumes: ", MessageEnum.RA_CREATE_VNF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("createVNFVolumes exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class CreateVNFVolumesTask implements Runnable { - private final CreateVolumeGroupRequest req; - private CreateVolumeGroupResponse response = null; - private VolumeGroupExceptionResponse eresp = null; - private boolean sendxml; - - public CreateVNFVolumesTask(CreateVolumeGroupRequest req) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<CreateVolumeGroupResponse>(response) {} - : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - @Override - public void run() { - logger.debug("CreateVFModule VolumesTask start"); - try { - // Synchronous Web Service Outputs - Holder<String> stackId = new Holder<>(); - Holder<Map<String, String>> outputs = new Holder<>(); - Holder<VnfRollback> vnfRollback = new Holder<>(); - String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); - logger.debug("in createVfModuleVolumes - completeVnfVfModuleType={}", completeVnfVfModuleType); - - String cloudsite = req.getCloudSiteId(); - if (cloudsite != null && cloudsite.equals(TESTING_KEYWORD)) { - String tenant = req.getTenantId(); - if (tenant != null && tenant.equals(TESTING_KEYWORD)) { - throw new VnfException("testing."); - } - stackId.value = "479D3D8B-6360-47BC-AB75-21CC91981484"; - outputs.value = testMap(); - } else { -// vnfAdapter.createVnf( -// req.getCloudSiteId(), -// req.getTenantId(), -// req.getVnfType(), -// req.getVnfVersion(), -// req.getVolumeGroupName(), -// "VOLUME", // request type is VOLUME -// null, // not sure about this -// req.getVolumeGroupParams(), -// req.getFailIfExists(), -// req.getSuppressBackout(), -// req.getMsoRequest(), -// stackId, -// outputs, -// vnfRollback); - vnfAdapter.createVfModule( - req.getCloudSiteId(), //cloudSiteId, - req.getCloudOwner(), //cloudOwner, - req.getTenantId(), //tenantId, - //req.getVnfType(), //vnfType, - completeVnfVfModuleType, - req.getVnfVersion(), //vnfVersion, - "", // genericVnfId - req.getVolumeGroupName(), //vnfName, - "", // vfModuleid - "VOLUME", //requestType, - null, //volumeGroupHeatStackId, - null, //baseVfHeatStackId, - req.getModelCustomizationUuid(), - req.getVolumeGroupParams(), //inputs, - req.getFailIfExists(), //failIfExists, - req.getSuppressBackout(), //backout, - req.getEnableBridge(), - req.getMsoRequest(), // msoRequest, - stackId, - outputs, - vnfRollback); - } - VolumeGroupRollback rb = new VolumeGroupRollback( - req.getVolumeGroupId(), - stackId.value, - true, // TODO boolean volumeGroupCreated, when would it be false? - req.getTenantId(), - req.getCloudOwner(), - req.getCloudSiteId(), - req.getMsoRequest(), - req.getMessageId()); - response = new CreateVolumeGroupResponse( - req.getVolumeGroupId(), - stackId.value, - true, // TODO boolean volumeGroupCreated, when would it be false? - outputs.value, - rb, - req.getMessageId()); - } catch (VnfException e) { - logger.debug(EXCEPTION, e); - eresp = new VolumeGroupExceptionResponse( - e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); - } - if (!req.isSynchronous()) { - // This is asynch, so POST response back to caller - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("CreateVFModule VolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse()); - } - } - - @DELETE - @Path("{aaiVolumeGroupId}") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "DeleteVNFVolumes", - response = Response.class, - notes = "Delete an existing vnfVolume") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfVolume has been successfully deleted"), - @ApiResponse(code = 202, message = "delete vnfVolume request has been successfully accepted (async only)"), - @ApiResponse(code = 500, message = "delete vnfVolume failed, examine entity object for details") }) - public Response deleteVNFVolumes( - @ApiParam(value = "aaiVolumeGroupId", required = true) - @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId, - @ApiParam(value = "DeleteVolumeGroupRequest", required = true) - final DeleteVolumeGroupRequest req - ) - { - logger.debug("deleteVNFVolumes enter: {}", req.toJsonString()); - if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) { - return Response - .status(HttpStatus.SC_BAD_REQUEST) - .type(MediaType.TEXT_PLAIN) - .entity(VOLUME_GROUPID_IN_URL_DOESNT_MATCH_CONTENT) - .build(); - } - DeleteVNFVolumesTask task = new DeleteVNFVolumesTask(req); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} Exception - deleteVNFVolumes: ", MessageEnum.RA_DELETE_VNF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("deleteVNFVolumes exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class DeleteVNFVolumesTask implements Runnable { - private final DeleteVolumeGroupRequest req; - private DeleteVolumeGroupResponse response = null; - private VolumeGroupExceptionResponse eresp = null; - private boolean sendxml; - - public DeleteVNFVolumesTask(DeleteVolumeGroupRequest req) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<DeleteVolumeGroupResponse>(response) {} - : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - @Override - public void run() { - logger.debug("DeleteVNFVolumesTask start"); - try { - if (!req.getCloudSiteId().equals(TESTING_KEYWORD)) { - vnfAdapter.deleteVnf(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), req.getVolumeGroupStackId(), req.getMsoRequest()); - } - response = new DeleteVolumeGroupResponse(true, req.getMessageId()); - } catch (VnfException e) { - logger.debug(EXCEPTION, e); - eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); - } - if (!req.isSynchronous()) { - // This is asynch, so POST response back to caller - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("DeleteVNFVolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse()); - } - } - - @DELETE - @Path("{aaiVolumeGroupId}/rollback") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "RollbackVNFVolumes", - response = Response.class, - notes = "Delete an existing vnfVolume") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfVolume has been successfully rolled back"), - @ApiResponse(code = 202, message = "rollback vnfVolume request has been successfully accepted (async only)"), - @ApiResponse(code = 500, message = "rollback vnfVolume failed, examine entity object for details") }) - public Response rollbackVNFVolumes( - @ApiParam(value = "aaiVolumeGroupId", required = true) - @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId, - @ApiParam(value = "RollbackVolumeGroupRequest", required = true) - final RollbackVolumeGroupRequest req - ) - { - logger.debug("rollbackVNFVolumes enter: {}", req.toJsonString()); - if (aaiVolumeGroupId == null || req.getVolumeGroupRollback() == null || !aaiVolumeGroupId.equals(req.getVolumeGroupRollback().getVolumeGroupId())) { - return Response - .status(HttpStatus.SC_BAD_REQUEST) - .type(MediaType.TEXT_PLAIN) - .entity(VOLUME_GROUPID_IN_URL_DOESNT_MATCH_CONTENT) - .build(); - } - RollbackVNFVolumesTask task = new RollbackVNFVolumesTask(req); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} Exception - rollbackVNFVolumes: ", MessageEnum.RA_ROLLBACK_VNF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("rollbackVNFVolumes exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class RollbackVNFVolumesTask implements Runnable { - private final RollbackVolumeGroupRequest req; - private RollbackVolumeGroupResponse response = null; - private VolumeGroupExceptionResponse eresp = null; - private boolean sendxml; - - public RollbackVNFVolumesTask(RollbackVolumeGroupRequest req) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<RollbackVolumeGroupResponse>(response) {} - : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - @Override - public void run() { - logger.debug("DeleteVNFVolumesTask start"); - try { - VolumeGroupRollback vgr = req.getVolumeGroupRollback(); - VnfRollback vrb = new VnfRollback( - vgr.getVolumeGroupStackId(), vgr.getTenantId(), vgr.getCloudOwnerId(), vgr.getCloudSiteId(), true, true, - vgr.getMsoRequest(), null, null, null, null); - vnfAdapter.rollbackVnf(vrb); - response = new RollbackVolumeGroupResponse(true, req.getMessageId()); - } catch (VnfException e) { - logger.debug(EXCEPTION, e); - eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); - } - if (!req.isSynchronous()) { - // This is asynch, so POST response back to caller - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("DeleteVNFVolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse()); - } - - } - - @PUT - @Path("{aaiVolumeGroupId}") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "UpdateVNFVolumes", - response = Response.class, - notes = "Update an existing vnfVolume") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfVolume has been successfully updated"), - @ApiResponse(code = 202, message = "update vnfVolume request has been successfully accepted (async only)"), - @ApiResponse(code = 500, message = "update vnfVolume failed, examine entity object for details") }) - public Response updateVNFVolumes( - @ApiParam(value = "aaiVolumeGroupId", required = true) - @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId, - @ApiParam(value = "UpdateVolumeGroupRequest", required = true) - final UpdateVolumeGroupRequest req - ) - { - logger.debug("updateVNFVolumes enter: {}", req.toJsonString()); - if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) { - return Response - .status(HttpStatus.SC_BAD_REQUEST) - .type(MediaType.TEXT_PLAIN) - .entity(VOLUME_GROUPID_IN_URL_DOESNT_MATCH_CONTENT) - .build(); - } - UpdateVNFVolumesTask task = new UpdateVNFVolumesTask(req); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} Exception - updateVNFVolumes: ", MessageEnum.RA_UPDATE_VNF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("updateVNFVolumes exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class UpdateVNFVolumesTask implements Runnable { - private final UpdateVolumeGroupRequest req; - private UpdateVolumeGroupResponse response = null; - private VolumeGroupExceptionResponse eresp = null; - private boolean sendxml; - - public UpdateVNFVolumesTask(UpdateVolumeGroupRequest req) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<UpdateVolumeGroupResponse>(response) {} - : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - @Override - public void run() { - logger.debug("UpdateVNFVolumesTask start"); - try { - Holder<Map<String, String>> outputs = new Holder<> (); - Holder<VnfRollback> vnfRollback = new Holder<> (); - String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); - logger.debug("in updateVfModuleVolume - completeVnfVfModuleType={}", completeVnfVfModuleType); - - if (req.getCloudSiteId().equals(TESTING_KEYWORD)) { - outputs.value = testMap(); - } else { - //vnfAdapter.updateVnf( - // req.getCloudSiteId(), - // req.getTenantId(), - // req.getVnfType(), - // req.getVnfVersion(), - // req.getVfModuleType(), - // "VOLUME", // request type is VOLUME - // req.getVolumeGroupStackId(), - // req.getVolumeGroupParams(), - // req.getMsoRequest(), - // outputs, - // vnfRollback); - vnfAdapter.updateVfModule (req.getCloudSiteId(), - req.getCloudOwner(), - req.getTenantId(), - //req.getVnfType(), - completeVnfVfModuleType, - req.getVnfVersion(), - req.getVolumeGroupStackId(), - "VOLUME", - null, - null, - req.getVolumeGroupStackId(), - req.getModelCustomizationUuid(), - req.getVolumeGroupParams(), - req.getMsoRequest(), - outputs, - vnfRollback); - } - response = new UpdateVolumeGroupResponse( - req.getVolumeGroupId(), req.getVolumeGroupStackId(), - outputs.value, req.getMessageId()); - } catch (VnfException e) { - logger.debug(EXCEPTION, e); - eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); - } - if (!req.isSynchronous()) { - // This is asynch, so POST response back to caller - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("UpdateVNFVolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse()); - } - } - - @GET - @Path("{aaiVolumeGroupId}") - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "QueryVNFVolumes", - response = Response.class, - notes = "Query an existing vnfVolume") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfVolume has been successfully queried"), - @ApiResponse(code = 500, message = "query vnfVolume failed, examine entity object for details") }) - public Response queryVNFVolumes( - @ApiParam(value = "aaiVolumeGroupId", required = true) - @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId, - @ApiParam(value = "cloudSiteId", required = true) - @QueryParam("cloudSiteId") String cloudSiteId, - @ApiParam(value = "cloudOwner", required = true) - @QueryParam("cloudOwner") String cloudOwner, - @ApiParam(value = "tenantId", required = true) - @QueryParam("tenantId") String tenantId, - @ApiParam(value = "volumeGroupStackId", required = true) - @QueryParam("volumeGroupStackId") String volumeGroupStackId, - @ApiParam(value = "skipAAI", required = true) - @QueryParam("skipAAI") Boolean skipAAI, - @ApiParam(value = "msoRequest.requestId", required = true) - @QueryParam("msoRequest.requestId") String requestId, - @ApiParam(value = "msoRequest.serviceInstanceId", required = true) - @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId - ) - { - //This request responds synchronously only - logger.debug("queryVNFVolumes enter: {} {}", aaiVolumeGroupId, volumeGroupStackId); - MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId); - - try { - int respStatus = HttpStatus.SC_OK; - QueryVolumeGroupResponse qryResp = new QueryVolumeGroupResponse(aaiVolumeGroupId, volumeGroupStackId, null, null); - Holder<Boolean> vnfExists = new Holder<>(); - Holder<String> vfModuleId = new Holder<>(); - Holder<VnfStatus> status = new Holder<>(); - Holder<Map<String, String>> outputs = new Holder<>(); - if (cloudSiteId != null && cloudSiteId.equals(TESTING_KEYWORD)) { - if (tenantId != null && tenantId.equals(TESTING_KEYWORD)) { - throw new VnfException("testing."); - } - vnfExists.value = true; - vfModuleId.value = TESTING_KEYWORD; - status.value = VnfStatus.ACTIVE; - outputs.value = testMap(); - } else { - vnfAdapter.queryVnf(cloudSiteId, cloudOwner, tenantId, volumeGroupStackId, msoRequest, vnfExists, vfModuleId, status, outputs); - } - if (!vnfExists.value) { - logger.debug("VNFVolumes not found"); - qryResp.setVolumeGroupStatus(status.value); - respStatus = HttpStatus.SC_NOT_FOUND; - } else { - logger.debug("VNFVolumes found {}, status={}", vfModuleId.value, status.value); - qryResp.setVolumeGroupStatus(status.value); - qryResp.setVolumeGroupOutputs(outputs.value); - } - logger.debug("Query queryVNFVolumes exit"); - return Response - .status(respStatus) - .entity(new GenericEntity<QueryVolumeGroupResponse>(qryResp) {}) - .build(); - } catch (VnfException e) { - logger.error("{} {} AaiVolumeGroupId: {} VnfException - queryVNFVolumes", MessageEnum.RA_QUERY_VNF_ERR, - ErrorCode.BusinessProcesssError.getValue(), aaiVolumeGroupId, e); - VolumeGroupExceptionResponse excResp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.FALSE, null); - logger.debug("Query queryVNFVolumes exit"); - return Response - .status(HttpStatus.SC_INTERNAL_SERVER_ERROR) - .entity(new GenericEntity<VolumeGroupExceptionResponse>(excResp) {}) - .build(); - } - } + private static final String TESTING_KEYWORD = "___TESTING___"; + private static final String EXCEPTION = "Exception :"; + private static final String RESP = ", resp="; + private static final String VOLUME_GROUPID_IN_URL_DOESNT_MATCH_CONTENT = + "VolumeGroupId in URL does not match content"; + @Autowired + private MsoVnfAdapterImpl vnfAdapter; + + @Autowired + private Provider<BpelRestClient> bpelRestClientProvider; + + @POST + @Path("") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "CreateVNFVolumes", response = Response.class, notes = "Create a new vnfVolume") + @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully created"), + @ApiResponse(code = 202, message = "create vnfVolume request has been successfully accepted (async only)"), + @ApiResponse(code = 500, message = "create vnfVolume failed, examine entity object for details")}) + public Response createVNFVolumes( + @ApiParam(value = "CreateVolumeGroupRequest", required = true) final CreateVolumeGroupRequest req) { + logger.debug("createVNFVolumes enter: {}", req.toJsonString()); + CreateVNFVolumesTask task = new CreateVNFVolumesTask(req); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling create, send generic failure as sync resp to caller + logger.error("{} {} Exception - createVNFVolumes: ", MessageEnum.RA_CREATE_VNF_ERR, + ErrorCode.BusinessProcesssError.getValue(), e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("createVNFVolumes exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class CreateVNFVolumesTask implements Runnable { + private final CreateVolumeGroupRequest req; + private CreateVolumeGroupResponse response = null; + private VolumeGroupExceptionResponse eresp = null; + private boolean sendxml; + + public CreateVNFVolumesTask(CreateVolumeGroupRequest req) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<CreateVolumeGroupResponse>(response) {} + : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + logger.debug("CreateVFModule VolumesTask start"); + try { + // Synchronous Web Service Outputs + Holder<String> stackId = new Holder<>(); + Holder<Map<String, String>> outputs = new Holder<>(); + Holder<VnfRollback> vnfRollback = new Holder<>(); + String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); + logger.debug("in createVfModuleVolumes - completeVnfVfModuleType={}", completeVnfVfModuleType); + + String cloudsite = req.getCloudSiteId(); + if (cloudsite != null && cloudsite.equals(TESTING_KEYWORD)) { + String tenant = req.getTenantId(); + if (tenant != null && tenant.equals(TESTING_KEYWORD)) { + throw new VnfException("testing."); + } + stackId.value = "479D3D8B-6360-47BC-AB75-21CC91981484"; + outputs.value = testMap(); + } else { + // vnfAdapter.createVnf( + // req.getCloudSiteId(), + // req.getTenantId(), + // req.getVnfType(), + // req.getVnfVersion(), + // req.getVolumeGroupName(), + // "VOLUME", // request type is VOLUME + // null, // not sure about this + // req.getVolumeGroupParams(), + // req.getFailIfExists(), + // req.getSuppressBackout(), + // req.getMsoRequest(), + // stackId, + // outputs, + // vnfRollback); + vnfAdapter.createVfModule(req.getCloudSiteId(), // cloudSiteId, + req.getCloudOwner(), // cloudOwner, + req.getTenantId(), // tenantId, + // req.getVnfType(), //vnfType, + completeVnfVfModuleType, req.getVnfVersion(), // vnfVersion, + "", // genericVnfId + req.getVolumeGroupName(), // vnfName, + "", // vfModuleid + "VOLUME", // requestType, + null, // volumeGroupHeatStackId, + null, // baseVfHeatStackId, + req.getModelCustomizationUuid(), req.getVolumeGroupParams(), // inputs, + req.getFailIfExists(), // failIfExists, + req.getSuppressBackout(), // backout, + req.getEnableBridge(), req.getMsoRequest(), // msoRequest, + stackId, outputs, vnfRollback); + } + VolumeGroupRollback rb = new VolumeGroupRollback(req.getVolumeGroupId(), stackId.value, true, // TODO + // boolean + // volumeGroupCreated, + // when + // would + // it be + // false? + req.getTenantId(), req.getCloudOwner(), req.getCloudSiteId(), req.getMsoRequest(), + req.getMessageId()); + response = new CreateVolumeGroupResponse(req.getVolumeGroupId(), stackId.value, true, // TODO boolean + // volumeGroupCreated, + // when would it + // be false? + outputs.value, rb, req.getMessageId()); + } catch (VnfException e) { + logger.debug(EXCEPTION, e); + eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, + req.getMessageId()); + } + if (!req.isSynchronous()) { + // This is asynch, so POST response back to caller + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("CreateVFModule VolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse()); + } + } + + @DELETE + @Path("{aaiVolumeGroupId}") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "DeleteVNFVolumes", response = Response.class, notes = "Delete an existing vnfVolume") + @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully deleted"), + @ApiResponse(code = 202, message = "delete vnfVolume request has been successfully accepted (async only)"), + @ApiResponse(code = 500, message = "delete vnfVolume failed, examine entity object for details")}) + public Response deleteVNFVolumes( + @ApiParam(value = "aaiVolumeGroupId", + required = true) @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId, + @ApiParam(value = "DeleteVolumeGroupRequest", required = true) final DeleteVolumeGroupRequest req) { + logger.debug("deleteVNFVolumes enter: {}", req.toJsonString()); + if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) { + return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN) + .entity(VOLUME_GROUPID_IN_URL_DOESNT_MATCH_CONTENT).build(); + } + DeleteVNFVolumesTask task = new DeleteVNFVolumesTask(req); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling create, send generic failure as sync resp to caller + logger.error("{} {} Exception - deleteVNFVolumes: ", MessageEnum.RA_DELETE_VNF_ERR, + ErrorCode.BusinessProcesssError.getValue(), e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("deleteVNFVolumes exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class DeleteVNFVolumesTask implements Runnable { + private final DeleteVolumeGroupRequest req; + private DeleteVolumeGroupResponse response = null; + private VolumeGroupExceptionResponse eresp = null; + private boolean sendxml; + + public DeleteVNFVolumesTask(DeleteVolumeGroupRequest req) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<DeleteVolumeGroupResponse>(response) {} + : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + logger.debug("DeleteVNFVolumesTask start"); + try { + if (!req.getCloudSiteId().equals(TESTING_KEYWORD)) { + vnfAdapter.deleteVnf(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + req.getVolumeGroupStackId(), req.getMsoRequest()); + } + response = new DeleteVolumeGroupResponse(true, req.getMessageId()); + } catch (VnfException e) { + logger.debug(EXCEPTION, e); + eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, + req.getMessageId()); + } + if (!req.isSynchronous()) { + // This is asynch, so POST response back to caller + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("DeleteVNFVolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse()); + } + } + + @DELETE + @Path("{aaiVolumeGroupId}/rollback") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "RollbackVNFVolumes", response = Response.class, notes = "Delete an existing vnfVolume") + @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully rolled back"), + @ApiResponse(code = 202, + message = "rollback vnfVolume request has been successfully accepted (async only)"), + @ApiResponse(code = 500, message = "rollback vnfVolume failed, examine entity object for details")}) + public Response rollbackVNFVolumes( + @ApiParam(value = "aaiVolumeGroupId", + required = true) @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId, + @ApiParam(value = "RollbackVolumeGroupRequest", required = true) final RollbackVolumeGroupRequest req) { + logger.debug("rollbackVNFVolumes enter: {}", req.toJsonString()); + if (aaiVolumeGroupId == null || req.getVolumeGroupRollback() == null + || !aaiVolumeGroupId.equals(req.getVolumeGroupRollback().getVolumeGroupId())) { + return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN) + .entity(VOLUME_GROUPID_IN_URL_DOESNT_MATCH_CONTENT).build(); + } + RollbackVNFVolumesTask task = new RollbackVNFVolumesTask(req); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling create, send generic failure as sync resp to caller + logger.error("{} {} Exception - rollbackVNFVolumes: ", MessageEnum.RA_ROLLBACK_VNF_ERR, + ErrorCode.BusinessProcesssError.getValue(), e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("rollbackVNFVolumes exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class RollbackVNFVolumesTask implements Runnable { + private final RollbackVolumeGroupRequest req; + private RollbackVolumeGroupResponse response = null; + private VolumeGroupExceptionResponse eresp = null; + private boolean sendxml; + + public RollbackVNFVolumesTask(RollbackVolumeGroupRequest req) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<RollbackVolumeGroupResponse>(response) {} + : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + logger.debug("DeleteVNFVolumesTask start"); + try { + VolumeGroupRollback vgr = req.getVolumeGroupRollback(); + VnfRollback vrb = new VnfRollback(vgr.getVolumeGroupStackId(), vgr.getTenantId(), vgr.getCloudOwnerId(), + vgr.getCloudSiteId(), true, true, vgr.getMsoRequest(), null, null, null, null); + vnfAdapter.rollbackVnf(vrb); + response = new RollbackVolumeGroupResponse(true, req.getMessageId()); + } catch (VnfException e) { + logger.debug(EXCEPTION, e); + eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, + req.getMessageId()); + } + if (!req.isSynchronous()) { + // This is asynch, so POST response back to caller + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("DeleteVNFVolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse()); + } + + } + + @PUT + @Path("{aaiVolumeGroupId}") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "UpdateVNFVolumes", response = Response.class, notes = "Update an existing vnfVolume") + @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully updated"), + @ApiResponse(code = 202, message = "update vnfVolume request has been successfully accepted (async only)"), + @ApiResponse(code = 500, message = "update vnfVolume failed, examine entity object for details")}) + public Response updateVNFVolumes( + @ApiParam(value = "aaiVolumeGroupId", + required = true) @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId, + @ApiParam(value = "UpdateVolumeGroupRequest", required = true) final UpdateVolumeGroupRequest req) { + logger.debug("updateVNFVolumes enter: {}", req.toJsonString()); + if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) { + return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN) + .entity(VOLUME_GROUPID_IN_URL_DOESNT_MATCH_CONTENT).build(); + } + UpdateVNFVolumesTask task = new UpdateVNFVolumesTask(req); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling create, send generic failure as sync resp to caller + logger.error("{} {} Exception - updateVNFVolumes: ", MessageEnum.RA_UPDATE_VNF_ERR, + ErrorCode.BusinessProcesssError.getValue(), e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("updateVNFVolumes exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class UpdateVNFVolumesTask implements Runnable { + private final UpdateVolumeGroupRequest req; + private UpdateVolumeGroupResponse response = null; + private VolumeGroupExceptionResponse eresp = null; + private boolean sendxml; + + public UpdateVNFVolumesTask(UpdateVolumeGroupRequest req) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<UpdateVolumeGroupResponse>(response) {} + : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + logger.debug("UpdateVNFVolumesTask start"); + try { + Holder<Map<String, String>> outputs = new Holder<>(); + Holder<VnfRollback> vnfRollback = new Holder<>(); + String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); + logger.debug("in updateVfModuleVolume - completeVnfVfModuleType={}", completeVnfVfModuleType); + + if (req.getCloudSiteId().equals(TESTING_KEYWORD)) { + outputs.value = testMap(); + } else { + // vnfAdapter.updateVnf( + // req.getCloudSiteId(), + // req.getTenantId(), + // req.getVnfType(), + // req.getVnfVersion(), + // req.getVfModuleType(), + // "VOLUME", // request type is VOLUME + // req.getVolumeGroupStackId(), + // req.getVolumeGroupParams(), + // req.getMsoRequest(), + // outputs, + // vnfRollback); + vnfAdapter.updateVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + // req.getVnfType(), + completeVnfVfModuleType, req.getVnfVersion(), req.getVolumeGroupStackId(), "VOLUME", null, + null, req.getVolumeGroupStackId(), req.getModelCustomizationUuid(), + req.getVolumeGroupParams(), req.getMsoRequest(), outputs, vnfRollback); + } + response = new UpdateVolumeGroupResponse(req.getVolumeGroupId(), req.getVolumeGroupStackId(), + outputs.value, req.getMessageId()); + } catch (VnfException e) { + logger.debug(EXCEPTION, e); + eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, + req.getMessageId()); + } + if (!req.isSynchronous()) { + // This is asynch, so POST response back to caller + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("UpdateVNFVolumesTask exit: code={} {} {}", getStatusCode(), RESP, getResponse()); + } + } + + @GET + @Path("{aaiVolumeGroupId}") + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "QueryVNFVolumes", response = Response.class, notes = "Query an existing vnfVolume") + @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully queried"), + @ApiResponse(code = 500, message = "query vnfVolume failed, examine entity object for details")}) + public Response queryVNFVolumes( + @ApiParam(value = "aaiVolumeGroupId", + required = true) @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId, + @ApiParam(value = "cloudSiteId", required = true) @QueryParam("cloudSiteId") String cloudSiteId, + @ApiParam(value = "cloudOwner", required = true) @QueryParam("cloudOwner") String cloudOwner, + @ApiParam(value = "tenantId", required = true) @QueryParam("tenantId") String tenantId, + @ApiParam(value = "volumeGroupStackId", + required = true) @QueryParam("volumeGroupStackId") String volumeGroupStackId, + @ApiParam(value = "skipAAI", required = true) @QueryParam("skipAAI") Boolean skipAAI, + @ApiParam(value = "msoRequest.requestId", + required = true) @QueryParam("msoRequest.requestId") String requestId, + @ApiParam(value = "msoRequest.serviceInstanceId", + required = true) @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId) { + // This request responds synchronously only + logger.debug("queryVNFVolumes enter: {} {}", aaiVolumeGroupId, volumeGroupStackId); + MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId); + + try { + int respStatus = HttpStatus.SC_OK; + QueryVolumeGroupResponse qryResp = + new QueryVolumeGroupResponse(aaiVolumeGroupId, volumeGroupStackId, null, null); + Holder<Boolean> vnfExists = new Holder<>(); + Holder<String> vfModuleId = new Holder<>(); + Holder<VnfStatus> status = new Holder<>(); + Holder<Map<String, String>> outputs = new Holder<>(); + if (cloudSiteId != null && cloudSiteId.equals(TESTING_KEYWORD)) { + if (tenantId != null && tenantId.equals(TESTING_KEYWORD)) { + throw new VnfException("testing."); + } + vnfExists.value = true; + vfModuleId.value = TESTING_KEYWORD; + status.value = VnfStatus.ACTIVE; + outputs.value = testMap(); + } else { + vnfAdapter.queryVnf(cloudSiteId, cloudOwner, tenantId, volumeGroupStackId, msoRequest, vnfExists, + vfModuleId, status, outputs); + } + if (!vnfExists.value) { + logger.debug("VNFVolumes not found"); + qryResp.setVolumeGroupStatus(status.value); + respStatus = HttpStatus.SC_NOT_FOUND; + } else { + logger.debug("VNFVolumes found {}, status={}", vfModuleId.value, status.value); + qryResp.setVolumeGroupStatus(status.value); + qryResp.setVolumeGroupOutputs(outputs.value); + } + logger.debug("Query queryVNFVolumes exit"); + return Response.status(respStatus).entity(new GenericEntity<QueryVolumeGroupResponse>(qryResp) {}).build(); + } catch (VnfException e) { + logger.error("{} {} AaiVolumeGroupId: {} VnfException - queryVNFVolumes", MessageEnum.RA_QUERY_VNF_ERR, + ErrorCode.BusinessProcesssError.getValue(), aaiVolumeGroupId, e); + VolumeGroupExceptionResponse excResp = new VolumeGroupExceptionResponse(e.getMessage(), + MsoExceptionCategory.INTERNAL, Boolean.FALSE, null); + logger.debug("Query queryVNFVolumes exit"); + return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR) + .entity(new GenericEntity<VolumeGroupExceptionResponse>(excResp) {}).build(); + } + } + public static Map<String, String> testMap() { - Map<String, String> m = new HashMap<>(); - m.put("mickey", "7"); - m.put("clyde", "10"); - m.put("wayne", "99"); - return m; + Map<String, String> m = new HashMap<>(); + m.put("mickey", "7"); + m.put("clyde", "10"); + m.put("wayne", "99"); + return m; } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java index cbbfdf359a..0ceba20051 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java @@ -70,13 +70,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** - * This class services calls to the REST interface for VNF Volumes (http://host:port/vnfs/rest/v1/volume-groups) - * Both XML and JSON can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default. - * For testing, call with cloudSiteId = ___TESTING___ - * To test exceptions, also set tenantId = ___TESTING___ + * This class services calls to the REST interface for VNF Volumes (http://host:port/vnfs/rest/v1/volume-groups) Both + * XML and JSON can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default. For + * testing, call with cloudSiteId = ___TESTING___ To test exceptions, also set tenantId = ___TESTING___ * - * V2 incorporates run-time selection of sub-orchestrator implementation (Heat or Cloudify) - * based on the target cloud. + * V2 incorporates run-time selection of sub-orchestrator implementation (Heat or Cloudify) based on the target cloud. */ @Path("/v2/volume-groups") @Api(value = "/v2/volume-groups", description = "root of volume-groups adapters restful web service v2") @@ -84,581 +82,511 @@ import org.springframework.stereotype.Component; public class VolumeAdapterRestV2 { private static final Logger logger = LoggerFactory.getLogger(VolumeAdapterRestV2.class); - private static final String TESTING_KEYWORD = "___TESTING___"; - private static final String RESP=", resp="; - private static final String EXCEPTION="Exception :"; - private static final String VOLUME_GROUPID_MISSING="VolumeGroupId in URL does not match content"; - - @Autowired - private VnfAdapterRestUtils vnfAdapterRestUtils; - - @Autowired - private Provider<BpelRestClient> bpelRestClientProvider; - - @POST - @Path("") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "CreateVNFVolumes", - response = Response.class, - notes = "Create a new vnfVolume") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfVolume has been successfully created"), - @ApiResponse(code = 202, message = "create vnfVolume request has been successfully accepted (async only)"), - @ApiResponse(code = 500, message = "create vnfVolume failed, examine entity object for details") }) - public Response createVNFVolumes( - @ApiParam(value = "mode", required = true) - @QueryParam("mode") String mode, - @ApiParam(value = "CreateVolumeGroupRequest", required = true) - final CreateVolumeGroupRequest req) - { - logger.debug("createVNFVolumes enter: {}", req.toJsonString()); - CreateVNFVolumesTask task = new CreateVNFVolumesTask(req, mode); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} Exception - createVNFVolumes: ", MessageEnum.RA_CREATE_VNF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("createVNFVolumes exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class CreateVNFVolumesTask implements Runnable { - private final CreateVolumeGroupRequest req; - private CreateVolumeGroupResponse response = null; - private VolumeGroupExceptionResponse eresp = null; - private boolean sendxml; - private String mode; - - public CreateVNFVolumesTask(CreateVolumeGroupRequest req, String mode) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - this.mode = mode; - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<CreateVolumeGroupResponse>(response) {} - : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - @Override - public void run() { - logger.debug("CreateVFModule VolumesTask start"); - try { - // Synchronous Web Service Outputs - Holder<String> stackId = new Holder<>(); - Holder<Map<String, String>> outputs = new Holder<>(); - Holder<VnfRollback> vnfRollback = new Holder<>(); - String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); - logger.debug("in createVfModuleVolumes - completeVnfVfModuleType={}", completeVnfVfModuleType); - - String cloudsiteId = req.getCloudSiteId(); - if (cloudsiteId != null && cloudsiteId.equals(TESTING_KEYWORD)) { - String tenant = req.getTenantId(); - if (tenant != null && tenant.equals(TESTING_KEYWORD)) { - throw new VnfException("testing."); - } - stackId.value = "479D3D8B-6360-47BC-AB75-21CC91981484"; - outputs.value = testMap(); - } else { - // Support different Adapter Implementations - MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsiteId); - vnfAdapter.createVfModule( - req.getCloudSiteId(), //cloudSiteId, - req.getCloudOwner(), //cloudOwner, - req.getTenantId(), //tenantId, - completeVnfVfModuleType, //vnfType, - req.getVnfVersion(), //vnfVersion, - "", // genericVnfId - req.getVolumeGroupName(), //vnfName, - "", // vfModuleId - "VOLUME", //requestType, - null, //volumeGroupHeatStackId, - null, //baseVfHeatStackId, - req.getModelCustomizationUuid(), - req.getVolumeGroupParams(), //inputs, - req.getFailIfExists(), //failIfExists, - req.getSuppressBackout(), //backout, - req.getEnableBridge(), - req.getMsoRequest(), // msoRequest, - stackId, - outputs, - vnfRollback); - } - - VolumeGroupRollback rb = new VolumeGroupRollback( - req.getVolumeGroupId(), - stackId.value, - vnfRollback.value.getVnfCreated(), - req.getTenantId(), - req.getCloudOwner(), - req.getCloudSiteId(), - req.getMsoRequest(), - req.getMessageId()); - - response = new CreateVolumeGroupResponse( - req.getVolumeGroupId(), - stackId.value, - vnfRollback.value.getVnfCreated(), - outputs.value, - rb, - req.getMessageId()); - } catch (VnfException e) { - logger.debug(EXCEPTION, e); - eresp = new VolumeGroupExceptionResponse( - e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); - } - if (!req.isSynchronous()) { - // This is asynch, so POST response back to caller - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("CreateVFModule VolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse()); - } - } - - @DELETE - @Path("{aaiVolumeGroupId}") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "DeleteVNFVolumes", - response = Response.class, - notes = "Delete an existing vnfVolume") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfVolume has been successfully deleted"), - @ApiResponse(code = 202, message = "delete vnfVolume request has been successfully accepted (async only)"), - @ApiResponse(code = 500, message = "delete vnfVolume failed, examine entity object for details") }) - public Response deleteVNFVolumes( - @ApiParam(value = "aaiVolumeGroupId", required = true) - @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId, - @ApiParam(value = "mode", required = true) - @QueryParam("mode") String mode, - @ApiParam(value = "DeleteVolumeGroupRequest", required = true) - final DeleteVolumeGroupRequest req - ) - { - logger.debug("deleteVNFVolumes enter: {}", req.toJsonString()); - if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) { - return Response - .status(HttpStatus.SC_BAD_REQUEST) - .type(MediaType.TEXT_PLAIN) - .entity(VOLUME_GROUPID_MISSING) - .build(); - } - DeleteVNFVolumesTask task = new DeleteVNFVolumesTask(req, mode); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} Exception - deleteVNFVolumes: ", MessageEnum.RA_DELETE_VNF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("deleteVNFVolumes exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class DeleteVNFVolumesTask implements Runnable { - private final DeleteVolumeGroupRequest req; - private DeleteVolumeGroupResponse response = null; - private VolumeGroupExceptionResponse eresp = null; - private boolean sendxml; - private String mode; - - public DeleteVNFVolumesTask(DeleteVolumeGroupRequest req, String mode) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - this.mode = mode; - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<DeleteVolumeGroupResponse>(response) {} - : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - @Override - public void run() { - logger.debug("DeleteVNFVolumesTask start"); - String cloudSiteId = req.getCloudSiteId(); - try { - if (! cloudSiteId.equals(TESTING_KEYWORD)) { - // Support different Adapter Implementations - MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudSiteId); - vnfAdapter.deleteVnf(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), req.getVolumeGroupStackId(), req.getMsoRequest()); - } - response = new DeleteVolumeGroupResponse(true, req.getMessageId()); - } catch (VnfException e) { - logger.debug(EXCEPTION, e); - eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); - } - if (!req.isSynchronous()) { - // This is asynch, so POST response back to caller - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("DeleteVNFVolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse()); - } - } - - @DELETE - @Path("{aaiVolumeGroupId}/rollback") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "RollbackVNFVolumes", - response = Response.class, - notes = "Delete an existing vnfVolume") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfVolume has been successfully rolled back"), - @ApiResponse(code = 202, message = "rollback vnfVolume request has been successfully accepted (async only)"), - @ApiResponse(code = 500, message = "rollback vnfVolume failed, examine entity object for details") }) - public Response rollbackVNFVolumes( - @ApiParam(value = "aaiVolumeGroupId", required = true) - @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId, - @ApiParam(value = "RollbackVolumeGroupRequest", required = true) - final RollbackVolumeGroupRequest req - ) - { - logger.debug("rollbackVNFVolumes enter: {}", req.toJsonString()); - if (aaiVolumeGroupId == null || req.getVolumeGroupRollback() == null || !aaiVolumeGroupId.equals(req.getVolumeGroupRollback().getVolumeGroupId())) { - return Response - .status(HttpStatus.SC_BAD_REQUEST) - .type(MediaType.TEXT_PLAIN) - .entity(VOLUME_GROUPID_MISSING) - .build(); - } - RollbackVNFVolumesTask task = new RollbackVNFVolumesTask(req); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} Exception - rollbackVNFVolumes: ", MessageEnum.RA_ROLLBACK_VNF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("rollbackVNFVolumes exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class RollbackVNFVolumesTask implements Runnable { - private final RollbackVolumeGroupRequest req; - private RollbackVolumeGroupResponse response = null; - private VolumeGroupExceptionResponse eresp = null; - private boolean sendxml; - - public RollbackVNFVolumesTask(RollbackVolumeGroupRequest req) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<RollbackVolumeGroupResponse>(response) {} - : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - @Override - public void run() { - logger.debug("RollbackVNFVolumesTask start"); - try { - VolumeGroupRollback vgr = req.getVolumeGroupRollback(); - VnfRollback vrb = new VnfRollback( - vgr.getVolumeGroupStackId(), vgr.getTenantId(), vgr.getCloudOwnerId(), vgr.getCloudSiteId(), true, true, - vgr.getMsoRequest(), null, null, null, null); - - // Support different Adapter Implementations - MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(vrb.getMode(), vrb.getCloudSiteId()); - vnfAdapter.rollbackVnf(vrb); - response = new RollbackVolumeGroupResponse(true, req.getMessageId()); - } catch (VnfException e) { - logger.debug(EXCEPTION, e); - eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); - } - if (!req.isSynchronous()) { - // This is asynch, so POST response back to caller - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("RollbackVNFVolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse()); - } - - } - - @PUT - @Path("{aaiVolumeGroupId}") - @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "UpdateVNFVolumes", - response = Response.class, - notes = "Update an existing vnfVolume") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfVolume has been successfully updated"), - @ApiResponse(code = 202, message = "update vnfVolume request has been successfully accepted (async only)"), - @ApiResponse(code = 500, message = "update vnfVolume failed, examine entity object for details") }) - public Response updateVNFVolumes( - @ApiParam(value = "aaiVolumeGroupId", required = true) - @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId, - @ApiParam(value = "mode", required = true) - @QueryParam("mode") String mode, - @ApiParam(value = "UpdateVolumeGroupRequest", required = true) - final UpdateVolumeGroupRequest req - ) - { - logger.debug("updateVNFVolumes enter: {}", req.toJsonString()); - if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) { - return Response - .status(HttpStatus.SC_BAD_REQUEST) - .type(MediaType.TEXT_PLAIN) - .entity(VOLUME_GROUPID_MISSING) - .build(); - } - UpdateVNFVolumesTask task = new UpdateVNFVolumesTask(req, mode); - if (req.isSynchronous()) { - // This is a synchronous request - task.run(); - return Response - .status(task.getStatusCode()) - .entity(task.getGenericEntityResponse()) - .build(); - } else { - // This is an asynchronous request - try { - Thread t1 = new Thread(task); - t1.start(); - } catch (Exception e) { - // problem handling create, send generic failure as sync resp to caller - logger.error("{} {} Exception - updateVNFVolumes: ", MessageEnum.RA_UPDATE_VNF_ERR, - ErrorCode.BusinessProcesssError.getValue(), e); - return Response.serverError().build(); - } - // send sync response (ACK) to caller - logger.debug("updateVNFVolumes exit"); - return Response.status(HttpStatus.SC_ACCEPTED).build(); - } - } - - public class UpdateVNFVolumesTask implements Runnable { - private final UpdateVolumeGroupRequest req; - private UpdateVolumeGroupResponse response = null; - private VolumeGroupExceptionResponse eresp = null; - private boolean sendxml; - private String mode; - - public UpdateVNFVolumesTask(UpdateVolumeGroupRequest req, String mode) { - this.req = req; - this.sendxml = true; // can be set with a field or header later - this.mode = mode; - } - public int getStatusCode() { - return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; - } - public Object getGenericEntityResponse() { - return (response != null) - ? new GenericEntity<UpdateVolumeGroupResponse>(response) {} - : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {}; - } - private String getResponse() { - if (response != null) { - return sendxml ? response.toXmlString() : response.toJsonString(); - } else { - return sendxml ? eresp.toXmlString() : eresp.toJsonString(); - } - } - @Override - public void run() { - logger.debug("UpdateVNFVolumesTask start"); - try { - Holder<Map<String, String>> outputs = new Holder<> (); - Holder<VnfRollback> vnfRollback = new Holder<> (); - String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); - logger.debug("in updateVfModuleVolume - completeVnfVfModuleType={}", completeVnfVfModuleType); - - if (req.getCloudSiteId().equals(TESTING_KEYWORD)) { - outputs.value = testMap(); - } else { - // Support different Adapter Implementations - MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, req.getCloudSiteId()); - vnfAdapter.updateVfModule (req.getCloudSiteId(), - req.getCloudOwner(), - req.getTenantId(), - //req.getVnfType(), - completeVnfVfModuleType, - req.getVnfVersion(), - req.getVolumeGroupStackId(), - "VOLUME", - null, - null, - req.getVolumeGroupStackId(), - req.getModelCustomizationUuid(), - req.getVolumeGroupParams(), - req.getMsoRequest(), - outputs, - vnfRollback); - } - response = new UpdateVolumeGroupResponse( - req.getVolumeGroupId(), req.getVolumeGroupStackId(), - outputs.value, req.getMessageId()); - } catch (VnfException e) { - logger.debug(EXCEPTION, e); - eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, req.getMessageId()); - } - if (!req.isSynchronous()) { - // This is asynch, so POST response back to caller - BpelRestClient bpelClient = bpelRestClientProvider.get(); - bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); - } - logger.debug("UpdateVNFVolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse()); - } - } - - @GET - @Path("{aaiVolumeGroupId}") - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) - @ApiOperation(value = "QueryVNFVolumes", - response = Response.class, - notes = "Query an existing vnfVolume") - @ApiResponses({ - @ApiResponse(code = 200, message = "vnfVolume has been successfully queried"), - @ApiResponse(code = 500, message = "query vnfVolume failed, examine entity object for details") }) - public Response queryVNFVolumes( - @ApiParam(value = "aaiVolumeGroupId", required = true) - @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId, - @ApiParam(value = "cloudSiteId", required = true) - @QueryParam("cloudSiteId") String cloudSiteId, - @ApiParam(value = "cloudOwner", required = true) - @QueryParam("cloudOwner") String cloudOwner, - @ApiParam(value = "tenantId", required = true) - @QueryParam("tenantId") String tenantId, - @ApiParam(value = "volumeGroupStackId", required = true) - @QueryParam("volumeGroupStackId") String volumeGroupStackId, - @ApiParam(value = "skipAAI", required = true) - @QueryParam("skipAAI") Boolean skipAAI, - @ApiParam(value = "msoRequest.requestId", required = true) - @QueryParam("msoRequest.requestId") String requestId, - @ApiParam(value = "msoRequest.serviceInstanceId", required = true) - @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId, - @ApiParam(value = "mode", required = true) - @QueryParam("mode") String mode - ) - { - //This request responds synchronously only - logger.debug("queryVNFVolumes enter: {} {}", aaiVolumeGroupId, volumeGroupStackId); - MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId); - - try { - int respStatus = HttpStatus.SC_OK; - QueryVolumeGroupResponse qryResp = new QueryVolumeGroupResponse(aaiVolumeGroupId, volumeGroupStackId, null, null); - Holder<Boolean> vnfExists = new Holder<>(); - Holder<String> vfModuleId = new Holder<>(); - Holder<VnfStatus> status = new Holder<>(); - Holder<Map<String, String>> outputs = new Holder<>(); - if (cloudSiteId != null && cloudSiteId.equals(TESTING_KEYWORD)) { - if (tenantId != null && tenantId.equals(TESTING_KEYWORD)) { - throw new VnfException("testing."); - } - vnfExists.value = true; - vfModuleId.value = TESTING_KEYWORD; - status.value = VnfStatus.ACTIVE; - outputs.value = testMap(); - } else { - // Support different Adapter Implementations - MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudSiteId); - vnfAdapter.queryVnf(cloudSiteId, cloudOwner, tenantId, volumeGroupStackId, msoRequest, vnfExists, vfModuleId, status, outputs); - } - if (!vnfExists.value) { - logger.debug("VNFVolumes not found"); - qryResp.setVolumeGroupStatus(status.value); - respStatus = HttpStatus.SC_NOT_FOUND; - } else { - logger.debug("VNFVolumes found {}, status={}", vfModuleId.value, status.value); - qryResp.setVolumeGroupStatus(status.value); - qryResp.setVolumeGroupOutputs(outputs.value); - } - logger.debug("Query queryVNFVolumes exit"); - return Response - .status(respStatus) - .entity(new GenericEntity<QueryVolumeGroupResponse>(qryResp) {}) - .build(); - } catch (VnfException e) { - logger.error("{} {} AaiVolumeGroupId: {} VnfException - queryVNFVolumes: ", MessageEnum.RA_QUERY_VNF_ERR, - ErrorCode.BusinessProcesssError.getValue(), aaiVolumeGroupId, e); - VolumeGroupExceptionResponse excResp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, Boolean.FALSE, null); - logger.debug("Query queryVNFVolumes exit"); - return Response - .status(HttpStatus.SC_INTERNAL_SERVER_ERROR) - .entity(new GenericEntity<VolumeGroupExceptionResponse>(excResp) {}) - .build(); - } - } + private static final String TESTING_KEYWORD = "___TESTING___"; + private static final String RESP = ", resp="; + private static final String EXCEPTION = "Exception :"; + private static final String VOLUME_GROUPID_MISSING = "VolumeGroupId in URL does not match content"; + + @Autowired + private VnfAdapterRestUtils vnfAdapterRestUtils; + + @Autowired + private Provider<BpelRestClient> bpelRestClientProvider; + + @POST + @Path("") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "CreateVNFVolumes", response = Response.class, notes = "Create a new vnfVolume") + @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully created"), + @ApiResponse(code = 202, message = "create vnfVolume request has been successfully accepted (async only)"), + @ApiResponse(code = 500, message = "create vnfVolume failed, examine entity object for details")}) + public Response createVNFVolumes(@ApiParam(value = "mode", required = true) @QueryParam("mode") String mode, + @ApiParam(value = "CreateVolumeGroupRequest", required = true) final CreateVolumeGroupRequest req) { + logger.debug("createVNFVolumes enter: {}", req.toJsonString()); + CreateVNFVolumesTask task = new CreateVNFVolumesTask(req, mode); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling create, send generic failure as sync resp to caller + logger.error("{} {} Exception - createVNFVolumes: ", MessageEnum.RA_CREATE_VNF_ERR, + ErrorCode.BusinessProcesssError.getValue(), e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("createVNFVolumes exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class CreateVNFVolumesTask implements Runnable { + private final CreateVolumeGroupRequest req; + private CreateVolumeGroupResponse response = null; + private VolumeGroupExceptionResponse eresp = null; + private boolean sendxml; + private String mode; + + public CreateVNFVolumesTask(CreateVolumeGroupRequest req, String mode) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + this.mode = mode; + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<CreateVolumeGroupResponse>(response) {} + : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + logger.debug("CreateVFModule VolumesTask start"); + try { + // Synchronous Web Service Outputs + Holder<String> stackId = new Holder<>(); + Holder<Map<String, String>> outputs = new Holder<>(); + Holder<VnfRollback> vnfRollback = new Holder<>(); + String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); + logger.debug("in createVfModuleVolumes - completeVnfVfModuleType={}", completeVnfVfModuleType); + + String cloudsiteId = req.getCloudSiteId(); + if (cloudsiteId != null && cloudsiteId.equals(TESTING_KEYWORD)) { + String tenant = req.getTenantId(); + if (tenant != null && tenant.equals(TESTING_KEYWORD)) { + throw new VnfException("testing."); + } + stackId.value = "479D3D8B-6360-47BC-AB75-21CC91981484"; + outputs.value = testMap(); + } else { + // Support different Adapter Implementations + MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsiteId); + vnfAdapter.createVfModule(req.getCloudSiteId(), // cloudSiteId, + req.getCloudOwner(), // cloudOwner, + req.getTenantId(), // tenantId, + completeVnfVfModuleType, // vnfType, + req.getVnfVersion(), // vnfVersion, + "", // genericVnfId + req.getVolumeGroupName(), // vnfName, + "", // vfModuleId + "VOLUME", // requestType, + null, // volumeGroupHeatStackId, + null, // baseVfHeatStackId, + req.getModelCustomizationUuid(), req.getVolumeGroupParams(), // inputs, + req.getFailIfExists(), // failIfExists, + req.getSuppressBackout(), // backout, + req.getEnableBridge(), req.getMsoRequest(), // msoRequest, + stackId, outputs, vnfRollback); + } + + VolumeGroupRollback rb = new VolumeGroupRollback(req.getVolumeGroupId(), stackId.value, + vnfRollback.value.getVnfCreated(), req.getTenantId(), req.getCloudOwner(), req.getCloudSiteId(), + req.getMsoRequest(), req.getMessageId()); + + response = new CreateVolumeGroupResponse(req.getVolumeGroupId(), stackId.value, + vnfRollback.value.getVnfCreated(), outputs.value, rb, req.getMessageId()); + } catch (VnfException e) { + logger.debug(EXCEPTION, e); + eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, + req.getMessageId()); + } + if (!req.isSynchronous()) { + // This is asynch, so POST response back to caller + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("CreateVFModule VolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse()); + } + } + + @DELETE + @Path("{aaiVolumeGroupId}") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "DeleteVNFVolumes", response = Response.class, notes = "Delete an existing vnfVolume") + @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully deleted"), + @ApiResponse(code = 202, message = "delete vnfVolume request has been successfully accepted (async only)"), + @ApiResponse(code = 500, message = "delete vnfVolume failed, examine entity object for details")}) + public Response deleteVNFVolumes( + @ApiParam(value = "aaiVolumeGroupId", + required = true) @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId, + @ApiParam(value = "mode", required = true) @QueryParam("mode") String mode, + @ApiParam(value = "DeleteVolumeGroupRequest", required = true) final DeleteVolumeGroupRequest req) { + logger.debug("deleteVNFVolumes enter: {}", req.toJsonString()); + if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) { + return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity(VOLUME_GROUPID_MISSING) + .build(); + } + DeleteVNFVolumesTask task = new DeleteVNFVolumesTask(req, mode); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling create, send generic failure as sync resp to caller + logger.error("{} {} Exception - deleteVNFVolumes: ", MessageEnum.RA_DELETE_VNF_ERR, + ErrorCode.BusinessProcesssError.getValue(), e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("deleteVNFVolumes exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class DeleteVNFVolumesTask implements Runnable { + private final DeleteVolumeGroupRequest req; + private DeleteVolumeGroupResponse response = null; + private VolumeGroupExceptionResponse eresp = null; + private boolean sendxml; + private String mode; + + public DeleteVNFVolumesTask(DeleteVolumeGroupRequest req, String mode) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + this.mode = mode; + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<DeleteVolumeGroupResponse>(response) {} + : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + logger.debug("DeleteVNFVolumesTask start"); + String cloudSiteId = req.getCloudSiteId(); + try { + if (!cloudSiteId.equals(TESTING_KEYWORD)) { + // Support different Adapter Implementations + MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudSiteId); + vnfAdapter.deleteVnf(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + req.getVolumeGroupStackId(), req.getMsoRequest()); + } + response = new DeleteVolumeGroupResponse(true, req.getMessageId()); + } catch (VnfException e) { + logger.debug(EXCEPTION, e); + eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, + req.getMessageId()); + } + if (!req.isSynchronous()) { + // This is asynch, so POST response back to caller + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("DeleteVNFVolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse()); + } + } + + @DELETE + @Path("{aaiVolumeGroupId}/rollback") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "RollbackVNFVolumes", response = Response.class, notes = "Delete an existing vnfVolume") + @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully rolled back"), + @ApiResponse(code = 202, + message = "rollback vnfVolume request has been successfully accepted (async only)"), + @ApiResponse(code = 500, message = "rollback vnfVolume failed, examine entity object for details")}) + public Response rollbackVNFVolumes( + @ApiParam(value = "aaiVolumeGroupId", + required = true) @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId, + @ApiParam(value = "RollbackVolumeGroupRequest", required = true) final RollbackVolumeGroupRequest req) { + logger.debug("rollbackVNFVolumes enter: {}", req.toJsonString()); + if (aaiVolumeGroupId == null || req.getVolumeGroupRollback() == null + || !aaiVolumeGroupId.equals(req.getVolumeGroupRollback().getVolumeGroupId())) { + return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity(VOLUME_GROUPID_MISSING) + .build(); + } + RollbackVNFVolumesTask task = new RollbackVNFVolumesTask(req); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling create, send generic failure as sync resp to caller + logger.error("{} {} Exception - rollbackVNFVolumes: ", MessageEnum.RA_ROLLBACK_VNF_ERR, + ErrorCode.BusinessProcesssError.getValue(), e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("rollbackVNFVolumes exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class RollbackVNFVolumesTask implements Runnable { + private final RollbackVolumeGroupRequest req; + private RollbackVolumeGroupResponse response = null; + private VolumeGroupExceptionResponse eresp = null; + private boolean sendxml; + + public RollbackVNFVolumesTask(RollbackVolumeGroupRequest req) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<RollbackVolumeGroupResponse>(response) {} + : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + logger.debug("RollbackVNFVolumesTask start"); + try { + VolumeGroupRollback vgr = req.getVolumeGroupRollback(); + VnfRollback vrb = new VnfRollback(vgr.getVolumeGroupStackId(), vgr.getTenantId(), vgr.getCloudOwnerId(), + vgr.getCloudSiteId(), true, true, vgr.getMsoRequest(), null, null, null, null); + + // Support different Adapter Implementations + MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(vrb.getMode(), vrb.getCloudSiteId()); + vnfAdapter.rollbackVnf(vrb); + response = new RollbackVolumeGroupResponse(true, req.getMessageId()); + } catch (VnfException e) { + logger.debug(EXCEPTION, e); + eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, + req.getMessageId()); + } + if (!req.isSynchronous()) { + // This is asynch, so POST response back to caller + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("RollbackVNFVolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse()); + } + + } + + @PUT + @Path("{aaiVolumeGroupId}") + @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "UpdateVNFVolumes", response = Response.class, notes = "Update an existing vnfVolume") + @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully updated"), + @ApiResponse(code = 202, message = "update vnfVolume request has been successfully accepted (async only)"), + @ApiResponse(code = 500, message = "update vnfVolume failed, examine entity object for details")}) + public Response updateVNFVolumes( + @ApiParam(value = "aaiVolumeGroupId", + required = true) @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId, + @ApiParam(value = "mode", required = true) @QueryParam("mode") String mode, + @ApiParam(value = "UpdateVolumeGroupRequest", required = true) final UpdateVolumeGroupRequest req) { + logger.debug("updateVNFVolumes enter: {}", req.toJsonString()); + if (aaiVolumeGroupId == null || !aaiVolumeGroupId.equals(req.getVolumeGroupId())) { + return Response.status(HttpStatus.SC_BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity(VOLUME_GROUPID_MISSING) + .build(); + } + UpdateVNFVolumesTask task = new UpdateVNFVolumesTask(req, mode); + if (req.isSynchronous()) { + // This is a synchronous request + task.run(); + return Response.status(task.getStatusCode()).entity(task.getGenericEntityResponse()).build(); + } else { + // This is an asynchronous request + try { + Thread t1 = new Thread(task); + t1.start(); + } catch (Exception e) { + // problem handling create, send generic failure as sync resp to caller + logger.error("{} {} Exception - updateVNFVolumes: ", MessageEnum.RA_UPDATE_VNF_ERR, + ErrorCode.BusinessProcesssError.getValue(), e); + return Response.serverError().build(); + } + // send sync response (ACK) to caller + logger.debug("updateVNFVolumes exit"); + return Response.status(HttpStatus.SC_ACCEPTED).build(); + } + } + + public class UpdateVNFVolumesTask implements Runnable { + private final UpdateVolumeGroupRequest req; + private UpdateVolumeGroupResponse response = null; + private VolumeGroupExceptionResponse eresp = null; + private boolean sendxml; + private String mode; + + public UpdateVNFVolumesTask(UpdateVolumeGroupRequest req, String mode) { + this.req = req; + this.sendxml = true; // can be set with a field or header later + this.mode = mode; + } + + public int getStatusCode() { + return (response != null) ? HttpStatus.SC_OK : HttpStatus.SC_BAD_REQUEST; + } + + public Object getGenericEntityResponse() { + return (response != null) ? new GenericEntity<UpdateVolumeGroupResponse>(response) {} + : new GenericEntity<VolumeGroupExceptionResponse>(eresp) {}; + } + + private String getResponse() { + if (response != null) { + return sendxml ? response.toXmlString() : response.toJsonString(); + } else { + return sendxml ? eresp.toXmlString() : eresp.toJsonString(); + } + } + + @Override + public void run() { + logger.debug("UpdateVNFVolumesTask start"); + try { + Holder<Map<String, String>> outputs = new Holder<>(); + Holder<VnfRollback> vnfRollback = new Holder<>(); + String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); + logger.debug("in updateVfModuleVolume - completeVnfVfModuleType={}", completeVnfVfModuleType); + + if (req.getCloudSiteId().equals(TESTING_KEYWORD)) { + outputs.value = testMap(); + } else { + // Support different Adapter Implementations + MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, req.getCloudSiteId()); + vnfAdapter.updateVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + // req.getVnfType(), + completeVnfVfModuleType, req.getVnfVersion(), req.getVolumeGroupStackId(), "VOLUME", null, + null, req.getVolumeGroupStackId(), req.getModelCustomizationUuid(), + req.getVolumeGroupParams(), req.getMsoRequest(), outputs, vnfRollback); + } + response = new UpdateVolumeGroupResponse(req.getVolumeGroupId(), req.getVolumeGroupStackId(), + outputs.value, req.getMessageId()); + } catch (VnfException e) { + logger.debug(EXCEPTION, e); + eresp = new VolumeGroupExceptionResponse(e.getMessage(), MsoExceptionCategory.INTERNAL, true, + req.getMessageId()); + } + if (!req.isSynchronous()) { + // This is asynch, so POST response back to caller + BpelRestClient bpelClient = bpelRestClientProvider.get(); + bpelClient.bpelPost(getResponse(), req.getNotificationUrl(), sendxml); + } + logger.debug("UpdateVNFVolumesTask exit: code= {} {} {}", getStatusCode(), RESP, getResponse()); + } + } + + @GET + @Path("{aaiVolumeGroupId}") + @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @ApiOperation(value = "QueryVNFVolumes", response = Response.class, notes = "Query an existing vnfVolume") + @ApiResponses({@ApiResponse(code = 200, message = "vnfVolume has been successfully queried"), + @ApiResponse(code = 500, message = "query vnfVolume failed, examine entity object for details")}) + public Response queryVNFVolumes( + @ApiParam(value = "aaiVolumeGroupId", + required = true) @PathParam("aaiVolumeGroupId") String aaiVolumeGroupId, + @ApiParam(value = "cloudSiteId", required = true) @QueryParam("cloudSiteId") String cloudSiteId, + @ApiParam(value = "cloudOwner", required = true) @QueryParam("cloudOwner") String cloudOwner, + @ApiParam(value = "tenantId", required = true) @QueryParam("tenantId") String tenantId, + @ApiParam(value = "volumeGroupStackId", + required = true) @QueryParam("volumeGroupStackId") String volumeGroupStackId, + @ApiParam(value = "skipAAI", required = true) @QueryParam("skipAAI") Boolean skipAAI, + @ApiParam(value = "msoRequest.requestId", + required = true) @QueryParam("msoRequest.requestId") String requestId, + @ApiParam(value = "msoRequest.serviceInstanceId", + required = true) @QueryParam("msoRequest.serviceInstanceId") String serviceInstanceId, + @ApiParam(value = "mode", required = true) @QueryParam("mode") String mode) { + // This request responds synchronously only + logger.debug("queryVNFVolumes enter: {} {}", aaiVolumeGroupId, volumeGroupStackId); + MsoRequest msoRequest = new MsoRequest(requestId, serviceInstanceId); + + try { + int respStatus = HttpStatus.SC_OK; + QueryVolumeGroupResponse qryResp = + new QueryVolumeGroupResponse(aaiVolumeGroupId, volumeGroupStackId, null, null); + Holder<Boolean> vnfExists = new Holder<>(); + Holder<String> vfModuleId = new Holder<>(); + Holder<VnfStatus> status = new Holder<>(); + Holder<Map<String, String>> outputs = new Holder<>(); + if (cloudSiteId != null && cloudSiteId.equals(TESTING_KEYWORD)) { + if (tenantId != null && tenantId.equals(TESTING_KEYWORD)) { + throw new VnfException("testing."); + } + vnfExists.value = true; + vfModuleId.value = TESTING_KEYWORD; + status.value = VnfStatus.ACTIVE; + outputs.value = testMap(); + } else { + // Support different Adapter Implementations + MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudSiteId); + vnfAdapter.queryVnf(cloudSiteId, cloudOwner, tenantId, volumeGroupStackId, msoRequest, vnfExists, + vfModuleId, status, outputs); + } + if (!vnfExists.value) { + logger.debug("VNFVolumes not found"); + qryResp.setVolumeGroupStatus(status.value); + respStatus = HttpStatus.SC_NOT_FOUND; + } else { + logger.debug("VNFVolumes found {}, status={}", vfModuleId.value, status.value); + qryResp.setVolumeGroupStatus(status.value); + qryResp.setVolumeGroupOutputs(outputs.value); + } + logger.debug("Query queryVNFVolumes exit"); + return Response.status(respStatus).entity(new GenericEntity<QueryVolumeGroupResponse>(qryResp) {}).build(); + } catch (VnfException e) { + logger.error("{} {} AaiVolumeGroupId: {} VnfException - queryVNFVolumes: ", MessageEnum.RA_QUERY_VNF_ERR, + ErrorCode.BusinessProcesssError.getValue(), aaiVolumeGroupId, e); + VolumeGroupExceptionResponse excResp = new VolumeGroupExceptionResponse(e.getMessage(), + MsoExceptionCategory.INTERNAL, Boolean.FALSE, null); + logger.debug("Query queryVNFVolumes exit"); + return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR) + .entity(new GenericEntity<VolumeGroupExceptionResponse>(excResp) {}).build(); + } + } + public static Map<String, String> testMap() { - Map<String, String> m = new HashMap<>(); - m.put("mickey", "7"); - m.put("clyde", "10"); - m.put("wayne", "99"); - return m; + Map<String, String> m = new HashMap<>(); + m.put("mickey", "7"); + m.put("clyde", "10"); + m.put("wayne", "99"); + return m; } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/CreateVnfNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/CreateVnfNotification.java index ba301b10fe..e3c59fd93d 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/CreateVnfNotification.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/CreateVnfNotification.java @@ -22,7 +22,6 @@ package org.onap.so.adapters.vnf.async.client; import java.util.ArrayList; import java.util.List; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -30,9 +29,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for createVnfNotification complex type. + * <p> + * Java class for createVnfNotification complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="createVnfNotification"> @@ -76,15 +77,8 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "createVnfNotification", propOrder = { - "messageId", - "completed", - "exception", - "errorMessage", - "vnfId", - "outputs", - "rollback" -}) +@XmlType(name = "createVnfNotification", + propOrder = {"messageId", "completed", "exception", "errorMessage", "vnfId", "outputs", "rollback"}) public class CreateVnfNotification { @XmlElement(required = true) @@ -99,10 +93,8 @@ public class CreateVnfNotification { /** * Gets the value of the messageId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getMessageId() { return messageId; @@ -111,10 +103,8 @@ public class CreateVnfNotification { /** * Sets the value of the messageId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setMessageId(String value) { this.messageId = value; @@ -139,10 +129,8 @@ public class CreateVnfNotification { /** * Gets the value of the exception property. * - * @return - * possible object is - * {@link MsoExceptionCategory } - * + * @return possible object is {@link MsoExceptionCategory } + * */ public MsoExceptionCategory getException() { return exception; @@ -151,10 +139,8 @@ public class CreateVnfNotification { /** * Sets the value of the exception property. * - * @param value - * allowed object is - * {@link MsoExceptionCategory } - * + * @param value allowed object is {@link MsoExceptionCategory } + * */ public void setException(MsoExceptionCategory value) { this.exception = value; @@ -163,10 +149,8 @@ public class CreateVnfNotification { /** * Gets the value of the errorMessage property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getErrorMessage() { return errorMessage; @@ -175,10 +159,8 @@ public class CreateVnfNotification { /** * Sets the value of the errorMessage property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setErrorMessage(String value) { this.errorMessage = value; @@ -187,10 +169,8 @@ public class CreateVnfNotification { /** * Gets the value of the vnfId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVnfId() { return vnfId; @@ -199,10 +179,8 @@ public class CreateVnfNotification { /** * Sets the value of the vnfId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVnfId(String value) { this.vnfId = value; @@ -211,10 +189,8 @@ public class CreateVnfNotification { /** * Gets the value of the outputs property. * - * @return - * possible object is - * {@link CreateVnfNotification.Outputs } - * + * @return possible object is {@link CreateVnfNotification.Outputs } + * */ public CreateVnfNotification.Outputs getOutputs() { return outputs; @@ -223,10 +199,8 @@ public class CreateVnfNotification { /** * Sets the value of the outputs property. * - * @param value - * allowed object is - * {@link CreateVnfNotification.Outputs } - * + * @param value allowed object is {@link CreateVnfNotification.Outputs } + * */ public void setOutputs(CreateVnfNotification.Outputs value) { this.outputs = value; @@ -235,10 +209,8 @@ public class CreateVnfNotification { /** * Gets the value of the rollback property. * - * @return - * possible object is - * {@link VnfRollback } - * + * @return possible object is {@link VnfRollback } + * */ public VnfRollback getRollback() { return rollback; @@ -247,10 +219,8 @@ public class CreateVnfNotification { /** * Sets the value of the rollback property. * - * @param value - * allowed object is - * {@link VnfRollback } - * + * @param value allowed object is {@link VnfRollback } + * */ public void setRollback(VnfRollback value) { this.rollback = value; @@ -258,9 +228,11 @@ public class CreateVnfNotification { /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -288,9 +260,7 @@ public class CreateVnfNotification { * */ @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "entry" - }) + @XmlType(name = "", propOrder = {"entry"}) public static class Outputs { protected List<CreateVnfNotification.Outputs.Entry> entry; @@ -299,21 +269,20 @@ public class CreateVnfNotification { * Gets the value of the entry property. * * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the entry property. + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you + * make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> + * method for the entry property. * * <p> * For example, to add a new item, do as follows: + * * <pre> - * getEntry().add(newItem); + * getEntry().add(newItem); * </pre> * * * <p> - * Objects of the following type(s) are allowed in the list - * {@link CreateVnfNotification.Outputs.Entry } + * Objects of the following type(s) are allowed in the list {@link CreateVnfNotification.Outputs.Entry } * * */ @@ -326,9 +295,11 @@ public class CreateVnfNotification { /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -346,10 +317,7 @@ public class CreateVnfNotification { * */ @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "key", - "value" - }) + @XmlType(name = "", propOrder = {"key", "value"}) public static class Entry { protected String key; @@ -358,10 +326,8 @@ public class CreateVnfNotification { /** * Gets the value of the key property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getKey() { return key; @@ -370,10 +336,8 @@ public class CreateVnfNotification { /** * Sets the value of the key property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setKey(String value) { this.key = value; @@ -382,10 +346,8 @@ public class CreateVnfNotification { /** * Gets the value of the value property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getValue() { return value; @@ -394,10 +356,8 @@ public class CreateVnfNotification { /** * Sets the value of the value property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setValue(String value) { this.value = value; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/DeleteVnfNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/DeleteVnfNotification.java index d8c533b041..434cf7f772 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/DeleteVnfNotification.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/DeleteVnfNotification.java @@ -27,9 +27,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for deleteVnfNotification complex type. + * <p> + * Java class for deleteVnfNotification complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="deleteVnfNotification"> @@ -49,12 +51,7 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "deleteVnfNotification", propOrder = { - "messageId", - "completed", - "exception", - "errorMessage" -}) +@XmlType(name = "deleteVnfNotification", propOrder = {"messageId", "completed", "exception", "errorMessage"}) public class DeleteVnfNotification { @XmlElement(required = true) @@ -66,10 +63,8 @@ public class DeleteVnfNotification { /** * Gets the value of the messageId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getMessageId() { return messageId; @@ -78,10 +73,8 @@ public class DeleteVnfNotification { /** * Sets the value of the messageId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setMessageId(String value) { this.messageId = value; @@ -106,10 +99,8 @@ public class DeleteVnfNotification { /** * Gets the value of the exception property. * - * @return - * possible object is - * {@link MsoExceptionCategory } - * + * @return possible object is {@link MsoExceptionCategory } + * */ public MsoExceptionCategory getException() { return exception; @@ -118,10 +109,8 @@ public class DeleteVnfNotification { /** * Sets the value of the exception property. * - * @param value - * allowed object is - * {@link MsoExceptionCategory } - * + * @param value allowed object is {@link MsoExceptionCategory } + * */ public void setException(MsoExceptionCategory value) { this.exception = value; @@ -130,10 +119,8 @@ public class DeleteVnfNotification { /** * Gets the value of the errorMessage property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getErrorMessage() { return errorMessage; @@ -142,10 +129,8 @@ public class DeleteVnfNotification { /** * Sets the value of the errorMessage property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setErrorMessage(String value) { this.errorMessage = value; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/MsoExceptionCategory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/MsoExceptionCategory.java index 73642a7f44..de389d354b 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/MsoExceptionCategory.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/MsoExceptionCategory.java @@ -25,10 +25,13 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for msoExceptionCategory. + * <p> + * Java class for msoExceptionCategory. * - * <p>The following schema fragment specifies the expected content contained within this class. * <p> + * The following schema fragment specifies the expected content contained within this class. + * <p> + * * <pre> * <simpleType name="msoExceptionCategory"> * <restriction base="{http://www.w3.org/2001/XMLSchema}string"> @@ -45,10 +48,7 @@ import javax.xml.bind.annotation.XmlType; @XmlEnum public enum MsoExceptionCategory { - OPENSTACK, - IO, - INTERNAL, - USERDATA; + OPENSTACK, IO, INTERNAL, USERDATA; public String value() { return name(); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/MsoRequest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/MsoRequest.java index a4253b0cef..b1159f1de7 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/MsoRequest.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/MsoRequest.java @@ -26,9 +26,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for msoRequest complex type. + * <p> + * Java class for msoRequest complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="msoRequest"> @@ -46,10 +48,7 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "msoRequest", propOrder = { - "requestId", - "serviceInstanceId" -}) +@XmlType(name = "msoRequest", propOrder = {"requestId", "serviceInstanceId"}) public class MsoRequest { protected String requestId; @@ -58,10 +57,8 @@ public class MsoRequest { /** * Gets the value of the requestId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getRequestId() { return requestId; @@ -70,10 +67,8 @@ public class MsoRequest { /** * Sets the value of the requestId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setRequestId(String value) { this.requestId = value; @@ -82,10 +77,8 @@ public class MsoRequest { /** * Gets the value of the serviceInstanceId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getServiceInstanceId() { return serviceInstanceId; @@ -94,10 +87,8 @@ public class MsoRequest { /** * Sets the value of the serviceInstanceId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setServiceInstanceId(String value) { this.serviceInstanceId = value; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/ObjectFactory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/ObjectFactory.java index 1e1a80e74c..ced49e2313 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/ObjectFactory.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/ObjectFactory.java @@ -29,23 +29,19 @@ import javax.xml.namespace.QName; /** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the org.onap.so.adapters.vnf.async.client package. - * <p>An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. + * This object contains factory methods for each Java content interface and Java element interface generated in the + * org.onap.so.adapters.vnf.async.client package. + * <p> + * An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content. + * The Java representation of XML content can consist of schema derived interfaces and classes representing the binding + * of schema type definitions, element declarations and model groups. Factory methods for each of these are provided in + * this class. * */ @XmlRegistry public class ObjectFactory { - private static final String URL= "http://org.onap.so/vnfNotify"; + private static final String URL = "http://org.onap.so/vnfNotify"; private final static QName _QueryVnfNotification_QNAME = new QName(URL, "queryVnfNotification"); private final static QName _RollbackVnfNotification_QNAME = new QName(URL, "rollbackVnfNotification"); private final static QName _CreateVnfNotification_QNAME = new QName(URL, "createVnfNotification"); @@ -53,11 +49,11 @@ public class ObjectFactory { private final static QName _UpdateVnfNotification_QNAME = new QName(URL, "updateVnfNotification"); /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onap.so.adapters.vnf.async.client + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: + * org.onap.so.adapters.vnf.async.client * */ - public ObjectFactory() { - } + public ObjectFactory() {} /** * Create an instance of {@link UpdateVnfNotification } @@ -169,7 +165,8 @@ public class ObjectFactory { */ @XmlElementDecl(namespace = URL, name = "queryVnfNotification") public JAXBElement<QueryVnfNotification> createQueryVnfNotification(QueryVnfNotification value) { - return new JAXBElement<QueryVnfNotification>(_QueryVnfNotification_QNAME, QueryVnfNotification.class, null, value); + return new JAXBElement<QueryVnfNotification>(_QueryVnfNotification_QNAME, QueryVnfNotification.class, null, + value); } /** @@ -178,7 +175,8 @@ public class ObjectFactory { */ @XmlElementDecl(namespace = URL, name = "rollbackVnfNotification") public JAXBElement<RollbackVnfNotification> createRollbackVnfNotification(RollbackVnfNotification value) { - return new JAXBElement<RollbackVnfNotification>(_RollbackVnfNotification_QNAME, RollbackVnfNotification.class, null, value); + return new JAXBElement<RollbackVnfNotification>(_RollbackVnfNotification_QNAME, RollbackVnfNotification.class, + null, value); } /** @@ -187,7 +185,8 @@ public class ObjectFactory { */ @XmlElementDecl(namespace = URL, name = "createVnfNotification") public JAXBElement<CreateVnfNotification> createCreateVnfNotification(CreateVnfNotification value) { - return new JAXBElement<CreateVnfNotification>(_CreateVnfNotification_QNAME, CreateVnfNotification.class, null, value); + return new JAXBElement<CreateVnfNotification>(_CreateVnfNotification_QNAME, CreateVnfNotification.class, null, + value); } /** @@ -196,7 +195,8 @@ public class ObjectFactory { */ @XmlElementDecl(namespace = URL, name = "deleteVnfNotification") public JAXBElement<DeleteVnfNotification> createDeleteVnfNotification(DeleteVnfNotification value) { - return new JAXBElement<DeleteVnfNotification>(_DeleteVnfNotification_QNAME, DeleteVnfNotification.class, null, value); + return new JAXBElement<DeleteVnfNotification>(_DeleteVnfNotification_QNAME, DeleteVnfNotification.class, null, + value); } /** @@ -205,7 +205,8 @@ public class ObjectFactory { */ @XmlElementDecl(namespace = URL, name = "updateVnfNotification") public JAXBElement<UpdateVnfNotification> createUpdateVnfNotification(UpdateVnfNotification value) { - return new JAXBElement<UpdateVnfNotification>(_UpdateVnfNotification_QNAME, UpdateVnfNotification.class, null, value); + return new JAXBElement<UpdateVnfNotification>(_UpdateVnfNotification_QNAME, UpdateVnfNotification.class, null, + value); } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/QueryVnfNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/QueryVnfNotification.java index 0fd701d4f6..8968851fe1 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/QueryVnfNotification.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/QueryVnfNotification.java @@ -22,7 +22,6 @@ package org.onap.so.adapters.vnf.async.client; import java.util.ArrayList; import java.util.List; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -30,9 +29,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for queryVnfNotification complex type. + * <p> + * Java class for queryVnfNotification complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="queryVnfNotification"> @@ -77,16 +78,8 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "queryVnfNotification", propOrder = { - "messageId", - "completed", - "exception", - "errorMessage", - "vnfExists", - "vnfId", - "status", - "outputs" -}) +@XmlType(name = "queryVnfNotification", + propOrder = {"messageId", "completed", "exception", "errorMessage", "vnfExists", "vnfId", "status", "outputs"}) public class QueryVnfNotification { @XmlElement(required = true) @@ -102,10 +95,8 @@ public class QueryVnfNotification { /** * Gets the value of the messageId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getMessageId() { return messageId; @@ -114,10 +105,8 @@ public class QueryVnfNotification { /** * Sets the value of the messageId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setMessageId(String value) { this.messageId = value; @@ -142,10 +131,8 @@ public class QueryVnfNotification { /** * Gets the value of the exception property. * - * @return - * possible object is - * {@link MsoExceptionCategory } - * + * @return possible object is {@link MsoExceptionCategory } + * */ public MsoExceptionCategory getException() { return exception; @@ -154,10 +141,8 @@ public class QueryVnfNotification { /** * Sets the value of the exception property. * - * @param value - * allowed object is - * {@link MsoExceptionCategory } - * + * @param value allowed object is {@link MsoExceptionCategory } + * */ public void setException(MsoExceptionCategory value) { this.exception = value; @@ -166,10 +151,8 @@ public class QueryVnfNotification { /** * Gets the value of the errorMessage property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getErrorMessage() { return errorMessage; @@ -178,10 +161,8 @@ public class QueryVnfNotification { /** * Sets the value of the errorMessage property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setErrorMessage(String value) { this.errorMessage = value; @@ -190,10 +171,8 @@ public class QueryVnfNotification { /** * Gets the value of the vnfExists property. * - * @return - * possible object is - * {@link Boolean } - * + * @return possible object is {@link Boolean } + * */ public Boolean isVnfExists() { return vnfExists; @@ -202,10 +181,8 @@ public class QueryVnfNotification { /** * Sets the value of the vnfExists property. * - * @param value - * allowed object is - * {@link Boolean } - * + * @param value allowed object is {@link Boolean } + * */ public void setVnfExists(Boolean value) { this.vnfExists = value; @@ -214,10 +191,8 @@ public class QueryVnfNotification { /** * Gets the value of the vnfId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVnfId() { return vnfId; @@ -226,10 +201,8 @@ public class QueryVnfNotification { /** * Sets the value of the vnfId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVnfId(String value) { this.vnfId = value; @@ -238,10 +211,8 @@ public class QueryVnfNotification { /** * Gets the value of the status property. * - * @return - * possible object is - * {@link VnfStatus } - * + * @return possible object is {@link VnfStatus } + * */ public VnfStatus getStatus() { return status; @@ -250,10 +221,8 @@ public class QueryVnfNotification { /** * Sets the value of the status property. * - * @param value - * allowed object is - * {@link VnfStatus } - * + * @param value allowed object is {@link VnfStatus } + * */ public void setStatus(VnfStatus value) { this.status = value; @@ -262,10 +231,8 @@ public class QueryVnfNotification { /** * Gets the value of the outputs property. * - * @return - * possible object is - * {@link QueryVnfNotification.Outputs } - * + * @return possible object is {@link QueryVnfNotification.Outputs } + * */ public QueryVnfNotification.Outputs getOutputs() { return outputs; @@ -274,10 +241,8 @@ public class QueryVnfNotification { /** * Sets the value of the outputs property. * - * @param value - * allowed object is - * {@link QueryVnfNotification.Outputs } - * + * @param value allowed object is {@link QueryVnfNotification.Outputs } + * */ public void setOutputs(QueryVnfNotification.Outputs value) { this.outputs = value; @@ -285,9 +250,11 @@ public class QueryVnfNotification { /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -315,9 +282,7 @@ public class QueryVnfNotification { * */ @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "entry" - }) + @XmlType(name = "", propOrder = {"entry"}) public static class Outputs { protected List<QueryVnfNotification.Outputs.Entry> entry; @@ -326,21 +291,20 @@ public class QueryVnfNotification { * Gets the value of the entry property. * * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the entry property. + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you + * make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> + * method for the entry property. * * <p> * For example, to add a new item, do as follows: + * * <pre> - * getEntry().add(newItem); + * getEntry().add(newItem); * </pre> * * * <p> - * Objects of the following type(s) are allowed in the list - * {@link QueryVnfNotification.Outputs.Entry } + * Objects of the following type(s) are allowed in the list {@link QueryVnfNotification.Outputs.Entry } * * */ @@ -353,9 +317,11 @@ public class QueryVnfNotification { /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -373,10 +339,7 @@ public class QueryVnfNotification { * */ @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "key", - "value" - }) + @XmlType(name = "", propOrder = {"key", "value"}) public static class Entry { protected String key; @@ -385,10 +348,8 @@ public class QueryVnfNotification { /** * Gets the value of the key property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getKey() { return key; @@ -397,10 +358,8 @@ public class QueryVnfNotification { /** * Sets the value of the key property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setKey(String value) { this.key = value; @@ -409,10 +368,8 @@ public class QueryVnfNotification { /** * Gets the value of the value property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getValue() { return value; @@ -421,10 +378,8 @@ public class QueryVnfNotification { /** * Sets the value of the value property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setValue(String value) { this.value = value; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/RollbackVnfNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/RollbackVnfNotification.java index 05947f5e62..e5f8878e84 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/RollbackVnfNotification.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/RollbackVnfNotification.java @@ -27,9 +27,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for rollbackVnfNotification complex type. + * <p> + * Java class for rollbackVnfNotification complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="rollbackVnfNotification"> @@ -49,12 +51,7 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "rollbackVnfNotification", propOrder = { - "messageId", - "completed", - "exception", - "errorMessage" -}) +@XmlType(name = "rollbackVnfNotification", propOrder = {"messageId", "completed", "exception", "errorMessage"}) public class RollbackVnfNotification { @XmlElement(required = true) @@ -66,10 +63,8 @@ public class RollbackVnfNotification { /** * Gets the value of the messageId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getMessageId() { return messageId; @@ -78,10 +73,8 @@ public class RollbackVnfNotification { /** * Sets the value of the messageId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setMessageId(String value) { this.messageId = value; @@ -106,10 +99,8 @@ public class RollbackVnfNotification { /** * Gets the value of the exception property. * - * @return - * possible object is - * {@link MsoExceptionCategory } - * + * @return possible object is {@link MsoExceptionCategory } + * */ public MsoExceptionCategory getException() { return exception; @@ -118,10 +109,8 @@ public class RollbackVnfNotification { /** * Sets the value of the exception property. * - * @param value - * allowed object is - * {@link MsoExceptionCategory } - * + * @param value allowed object is {@link MsoExceptionCategory } + * */ public void setException(MsoExceptionCategory value) { this.exception = value; @@ -130,10 +119,8 @@ public class RollbackVnfNotification { /** * Gets the value of the errorMessage property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getErrorMessage() { return errorMessage; @@ -142,10 +129,8 @@ public class RollbackVnfNotification { /** * Sets the value of the errorMessage property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setErrorMessage(String value) { this.errorMessage = value; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/UpdateVnfNotification.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/UpdateVnfNotification.java index 13fa8cb0ef..b738d6dc64 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/UpdateVnfNotification.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/UpdateVnfNotification.java @@ -22,7 +22,6 @@ package org.onap.so.adapters.vnf.async.client; import java.util.ArrayList; import java.util.List; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -30,9 +29,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for updateVnfNotification complex type. + * <p> + * Java class for updateVnfNotification complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="updateVnfNotification"> @@ -75,14 +76,8 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "updateVnfNotification", propOrder = { - "messageId", - "completed", - "exception", - "errorMessage", - "outputs", - "rollback" -}) +@XmlType(name = "updateVnfNotification", + propOrder = {"messageId", "completed", "exception", "errorMessage", "outputs", "rollback"}) public class UpdateVnfNotification { @XmlElement(required = true) @@ -96,10 +91,8 @@ public class UpdateVnfNotification { /** * Gets the value of the messageId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getMessageId() { return messageId; @@ -108,10 +101,8 @@ public class UpdateVnfNotification { /** * Sets the value of the messageId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setMessageId(String value) { this.messageId = value; @@ -136,10 +127,8 @@ public class UpdateVnfNotification { /** * Gets the value of the exception property. * - * @return - * possible object is - * {@link MsoExceptionCategory } - * + * @return possible object is {@link MsoExceptionCategory } + * */ public MsoExceptionCategory getException() { return exception; @@ -148,10 +137,8 @@ public class UpdateVnfNotification { /** * Sets the value of the exception property. * - * @param value - * allowed object is - * {@link MsoExceptionCategory } - * + * @param value allowed object is {@link MsoExceptionCategory } + * */ public void setException(MsoExceptionCategory value) { this.exception = value; @@ -160,10 +147,8 @@ public class UpdateVnfNotification { /** * Gets the value of the errorMessage property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getErrorMessage() { return errorMessage; @@ -172,10 +157,8 @@ public class UpdateVnfNotification { /** * Sets the value of the errorMessage property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setErrorMessage(String value) { this.errorMessage = value; @@ -184,10 +167,8 @@ public class UpdateVnfNotification { /** * Gets the value of the outputs property. * - * @return - * possible object is - * {@link UpdateVnfNotification.Outputs } - * + * @return possible object is {@link UpdateVnfNotification.Outputs } + * */ public UpdateVnfNotification.Outputs getOutputs() { return outputs; @@ -196,10 +177,8 @@ public class UpdateVnfNotification { /** * Sets the value of the outputs property. * - * @param value - * allowed object is - * {@link UpdateVnfNotification.Outputs } - * + * @param value allowed object is {@link UpdateVnfNotification.Outputs } + * */ public void setOutputs(UpdateVnfNotification.Outputs value) { this.outputs = value; @@ -208,10 +187,8 @@ public class UpdateVnfNotification { /** * Gets the value of the rollback property. * - * @return - * possible object is - * {@link VnfRollback } - * + * @return possible object is {@link VnfRollback } + * */ public VnfRollback getRollback() { return rollback; @@ -220,10 +197,8 @@ public class UpdateVnfNotification { /** * Sets the value of the rollback property. * - * @param value - * allowed object is - * {@link VnfRollback } - * + * @param value allowed object is {@link VnfRollback } + * */ public void setRollback(VnfRollback value) { this.rollback = value; @@ -231,9 +206,11 @@ public class UpdateVnfNotification { /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -261,9 +238,7 @@ public class UpdateVnfNotification { * */ @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "entry" - }) + @XmlType(name = "", propOrder = {"entry"}) public static class Outputs { protected List<UpdateVnfNotification.Outputs.Entry> entry; @@ -272,21 +247,20 @@ public class UpdateVnfNotification { * Gets the value of the entry property. * * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the entry property. + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you + * make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> + * method for the entry property. * * <p> * For example, to add a new item, do as follows: + * * <pre> - * getEntry().add(newItem); + * getEntry().add(newItem); * </pre> * * * <p> - * Objects of the following type(s) are allowed in the list - * {@link UpdateVnfNotification.Outputs.Entry } + * Objects of the following type(s) are allowed in the list {@link UpdateVnfNotification.Outputs.Entry } * * */ @@ -299,9 +273,11 @@ public class UpdateVnfNotification { /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -319,10 +295,7 @@ public class UpdateVnfNotification { * */ @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "key", - "value" - }) + @XmlType(name = "", propOrder = {"key", "value"}) public static class Entry { protected String key; @@ -331,10 +304,8 @@ public class UpdateVnfNotification { /** * Gets the value of the key property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getKey() { return key; @@ -343,10 +314,8 @@ public class UpdateVnfNotification { /** * Sets the value of the key property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setKey(String value) { this.key = value; @@ -355,10 +324,8 @@ public class UpdateVnfNotification { /** * Gets the value of the value property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getValue() { return value; @@ -367,10 +334,8 @@ public class UpdateVnfNotification { /** * Sets the value of the value property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setValue(String value) { this.value = value; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify.java index 24370b4d79..d4bdaa3d34 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify.java @@ -30,15 +30,11 @@ import javax.xml.ws.RequestWrapper; /** - * This class was generated by the JAX-WS RI. - * JAX-WS RI 2.2.9-b14002 - * Generated source version: 2.2 + * This class was generated by the JAX-WS RI. JAX-WS RI 2.2.9-b14002 Generated source version: 2.2 * */ @WebService(name = "vnfAdapterNotify", targetNamespace = "http://org.onap.so/vnfNotify") -@XmlSeeAlso({ - ObjectFactory.class -}) +@XmlSeeAlso({ObjectFactory.class}) public interface VnfAdapterNotify { @@ -51,17 +47,13 @@ public interface VnfAdapterNotify { */ @WebMethod @Oneway - @RequestWrapper(localName = "rollbackVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.RollbackVnfNotification") + @RequestWrapper(localName = "rollbackVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", + className = "org.onap.so.adapters.vnf.async.client.RollbackVnfNotification") @Action(input = "http://org.onap.so/notify/adapterNotify/rollbackVnfNotificationRequest") - public void rollbackVnfNotification( - @WebParam(name = "messageId", targetNamespace = "") - String messageId, - @WebParam(name = "completed", targetNamespace = "") - boolean completed, - @WebParam(name = "exception", targetNamespace = "") - MsoExceptionCategory exception, - @WebParam(name = "errorMessage", targetNamespace = "") - String errorMessage); + public void rollbackVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId, + @WebParam(name = "completed", targetNamespace = "") boolean completed, + @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception, + @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage); /** * @@ -76,25 +68,17 @@ public interface VnfAdapterNotify { */ @WebMethod @Oneway - @RequestWrapper(localName = "queryVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.QueryVnfNotification") + @RequestWrapper(localName = "queryVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", + className = "org.onap.so.adapters.vnf.async.client.QueryVnfNotification") @Action(input = "http://org.onap.so/notify/adapterNotify/queryVnfNotificationRequest") - public void queryVnfNotification( - @WebParam(name = "messageId", targetNamespace = "") - String messageId, - @WebParam(name = "completed", targetNamespace = "") - boolean completed, - @WebParam(name = "exception", targetNamespace = "") - MsoExceptionCategory exception, - @WebParam(name = "errorMessage", targetNamespace = "") - String errorMessage, - @WebParam(name = "vnfExists", targetNamespace = "") - Boolean vnfExists, - @WebParam(name = "vnfId", targetNamespace = "") - String vnfId, - @WebParam(name = "status", targetNamespace = "") - VnfStatus status, - @WebParam(name = "outputs", targetNamespace = "") - org.onap.so.adapters.vnf.async.client.QueryVnfNotification.Outputs outputs); + public void queryVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId, + @WebParam(name = "completed", targetNamespace = "") boolean completed, + @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception, + @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage, + @WebParam(name = "vnfExists", targetNamespace = "") Boolean vnfExists, + @WebParam(name = "vnfId", targetNamespace = "") String vnfId, + @WebParam(name = "status", targetNamespace = "") VnfStatus status, @WebParam(name = "outputs", + targetNamespace = "") org.onap.so.adapters.vnf.async.client.QueryVnfNotification.Outputs outputs); /** * @@ -108,23 +92,17 @@ public interface VnfAdapterNotify { */ @WebMethod @Oneway - @RequestWrapper(localName = "createVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.CreateVnfNotification") + @RequestWrapper(localName = "createVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", + className = "org.onap.so.adapters.vnf.async.client.CreateVnfNotification") @Action(input = "http://org.onap.so/notify/adapterNotify/createVnfNotificationRequest") - public void createVnfNotification( - @WebParam(name = "messageId", targetNamespace = "") - String messageId, - @WebParam(name = "completed", targetNamespace = "") - boolean completed, - @WebParam(name = "exception", targetNamespace = "") - MsoExceptionCategory exception, - @WebParam(name = "errorMessage", targetNamespace = "") - String errorMessage, - @WebParam(name = "vnfId", targetNamespace = "") - String vnfId, - @WebParam(name = "outputs", targetNamespace = "") - org.onap.so.adapters.vnf.async.client.CreateVnfNotification.Outputs outputs, - @WebParam(name = "rollback", targetNamespace = "") - VnfRollback rollback); + public void createVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId, + @WebParam(name = "completed", targetNamespace = "") boolean completed, + @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception, + @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage, + @WebParam(name = "vnfId", targetNamespace = "") String vnfId, + @WebParam(name = "outputs", + targetNamespace = "") org.onap.so.adapters.vnf.async.client.CreateVnfNotification.Outputs outputs, + @WebParam(name = "rollback", targetNamespace = "") VnfRollback rollback); /** * @@ -137,21 +115,16 @@ public interface VnfAdapterNotify { */ @WebMethod @Oneway - @RequestWrapper(localName = "updateVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.UpdateVnfNotification") + @RequestWrapper(localName = "updateVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", + className = "org.onap.so.adapters.vnf.async.client.UpdateVnfNotification") @Action(input = "http://org.onap.so/notify/adapterNotify/updateVnfNotificationRequest") - public void updateVnfNotification( - @WebParam(name = "messageId", targetNamespace = "") - String messageId, - @WebParam(name = "completed", targetNamespace = "") - boolean completed, - @WebParam(name = "exception", targetNamespace = "") - MsoExceptionCategory exception, - @WebParam(name = "errorMessage", targetNamespace = "") - String errorMessage, - @WebParam(name = "outputs", targetNamespace = "") - org.onap.so.adapters.vnf.async.client.UpdateVnfNotification.Outputs outputs, - @WebParam(name = "rollback", targetNamespace = "") - VnfRollback rollback); + public void updateVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId, + @WebParam(name = "completed", targetNamespace = "") boolean completed, + @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception, + @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage, + @WebParam(name = "outputs", + targetNamespace = "") org.onap.so.adapters.vnf.async.client.UpdateVnfNotification.Outputs outputs, + @WebParam(name = "rollback", targetNamespace = "") VnfRollback rollback); /** * @@ -162,16 +135,12 @@ public interface VnfAdapterNotify { */ @WebMethod @Oneway - @RequestWrapper(localName = "deleteVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", className = "org.onap.so.adapters.vnf.async.client.DeleteVnfNotification") + @RequestWrapper(localName = "deleteVnfNotification", targetNamespace = "http://org.onap.so/vnfNotify", + className = "org.onap.so.adapters.vnf.async.client.DeleteVnfNotification") @Action(input = "http://org.onap.so/notify/adapterNotify/deleteVnfNotificationRequest") - public void deleteVnfNotification( - @WebParam(name = "messageId", targetNamespace = "") - String messageId, - @WebParam(name = "completed", targetNamespace = "") - boolean completed, - @WebParam(name = "exception", targetNamespace = "") - MsoExceptionCategory exception, - @WebParam(name = "errorMessage", targetNamespace = "") - String errorMessage); + public void deleteVnfNotification(@WebParam(name = "messageId", targetNamespace = "") String messageId, + @WebParam(name = "completed", targetNamespace = "") boolean completed, + @WebParam(name = "exception", targetNamespace = "") MsoExceptionCategory exception, + @WebParam(name = "errorMessage", targetNamespace = "") String errorMessage); } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify_Service.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify_Service.java index 4b140b1b30..e1a42706a9 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify_Service.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfAdapterNotify_Service.java @@ -21,7 +21,6 @@ package org.onap.so.adapters.vnf.async.client; import java.net.URL; - import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.WebEndpoint; @@ -31,25 +30,24 @@ import javax.xml.ws.WebServiceFeature; /** - * This class was generated by the JAX-WS RI. - * JAX-WS RI 2.2.9-b14002 - * Generated source version: 2.2 + * This class was generated by the JAX-WS RI. JAX-WS RI 2.2.9-b14002 Generated source version: 2.2 * */ -@WebServiceClient(name = "vnfAdapterNotify", targetNamespace = "http://org.onap.so/vnfNotify", wsdlLocation = "/VnfAdapterNotify.wsdl") -public class VnfAdapterNotify_Service - extends Service -{ +@WebServiceClient(name = "vnfAdapterNotify", targetNamespace = "http://org.onap.so/vnfNotify", + wsdlLocation = "/VnfAdapterNotify.wsdl") +public class VnfAdapterNotify_Service extends Service { private final static URL VNFADAPTERNOTIFY_WSDL_LOCATION; private final static WebServiceException VNFADAPTERNOTIFY_EXCEPTION; private final static QName VNFADAPTERNOTIFY_QNAME = new QName("http://org.onap.so/vnfNotify", "vnfAdapterNotify"); static { - VNFADAPTERNOTIFY_WSDL_LOCATION = org.onap.so.adapters.vnf.async.client.VnfAdapterNotify_Service.class.getResource("/VnfAdapterNotify.wsdl"); + VNFADAPTERNOTIFY_WSDL_LOCATION = org.onap.so.adapters.vnf.async.client.VnfAdapterNotify_Service.class + .getResource("/VnfAdapterNotify.wsdl"); WebServiceException e = null; if (VNFADAPTERNOTIFY_WSDL_LOCATION == null) { - e = new WebServiceException("Cannot find '/VnfAdapterNotify.wsdl' wsdl. Place the resource correctly in the classpath."); + e = new WebServiceException( + "Cannot find '/VnfAdapterNotify.wsdl' wsdl. Place the resource correctly in the classpath."); } VNFADAPTERNOTIFY_EXCEPTION = e; } @@ -80,28 +78,28 @@ public class VnfAdapterNotify_Service /** * - * @return - * returns VnfAdapterNotify + * @return returns VnfAdapterNotify */ @WebEndpoint(name = "MsoVnfAdapterAsyncImplPort") public VnfAdapterNotify getMsoVnfAdapterAsyncImplPort() { - return super.getPort(new QName("http://org.onap.so/vnfNotify", "MsoVnfAdapterAsyncImplPort"), VnfAdapterNotify.class); + return super.getPort(new QName("http://org.onap.so/vnfNotify", "MsoVnfAdapterAsyncImplPort"), + VnfAdapterNotify.class); } /** * - * @param features - * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. - * @return - * returns VnfAdapterNotify + * @param features A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features + * not in the <code>features</code> parameter will have their default values. + * @return returns VnfAdapterNotify */ @WebEndpoint(name = "MsoVnfAdapterAsyncImplPort") public VnfAdapterNotify getMsoVnfAdapterAsyncImplPort(WebServiceFeature... features) { - return super.getPort(new QName("http://org.onap.so/vnfNotify", "MsoVnfAdapterAsyncImplPort"), VnfAdapterNotify.class, features); + return super.getPort(new QName("http://org.onap.so/vnfNotify", "MsoVnfAdapterAsyncImplPort"), + VnfAdapterNotify.class, features); } private static URL __getWsdlLocation() { - if (VNFADAPTERNOTIFY_EXCEPTION!= null) { + if (VNFADAPTERNOTIFY_EXCEPTION != null) { throw VNFADAPTERNOTIFY_EXCEPTION; } return VNFADAPTERNOTIFY_WSDL_LOCATION; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfRollback.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfRollback.java index 9ad20738d0..7d8b4d1b41 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfRollback.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfRollback.java @@ -26,9 +26,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for vnfRollback complex type. + * <p> + * Java class for vnfRollback complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType name="vnfRollback"> @@ -50,14 +52,8 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "vnfRollback", propOrder = { - "cloudSiteId", - "msoRequest", - "tenantCreated", - "tenantId", - "vnfCreated", - "vnfId" -}) +@XmlType(name = "vnfRollback", + propOrder = {"cloudSiteId", "msoRequest", "tenantCreated", "tenantId", "vnfCreated", "vnfId"}) public class VnfRollback { protected String cloudSiteId; @@ -70,10 +66,8 @@ public class VnfRollback { /** * Gets the value of the cloudSiteId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getCloudSiteId() { return cloudSiteId; @@ -82,10 +76,8 @@ public class VnfRollback { /** * Sets the value of the cloudSiteId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setCloudSiteId(String value) { this.cloudSiteId = value; @@ -94,10 +86,8 @@ public class VnfRollback { /** * Gets the value of the msoRequest property. * - * @return - * possible object is - * {@link MsoRequest } - * + * @return possible object is {@link MsoRequest } + * */ public MsoRequest getMsoRequest() { return msoRequest; @@ -106,10 +96,8 @@ public class VnfRollback { /** * Sets the value of the msoRequest property. * - * @param value - * allowed object is - * {@link MsoRequest } - * + * @param value allowed object is {@link MsoRequest } + * */ public void setMsoRequest(MsoRequest value) { this.msoRequest = value; @@ -134,10 +122,8 @@ public class VnfRollback { /** * Gets the value of the tenantId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getTenantId() { return tenantId; @@ -146,10 +132,8 @@ public class VnfRollback { /** * Sets the value of the tenantId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setTenantId(String value) { this.tenantId = value; @@ -174,10 +158,8 @@ public class VnfRollback { /** * Gets the value of the vnfId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVnfId() { return vnfId; @@ -186,10 +168,8 @@ public class VnfRollback { /** * Sets the value of the vnfId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVnfId(String value) { this.vnfId = value; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfStatus.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfStatus.java index 1998ae0ce9..767777767c 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfStatus.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/async/client/VnfStatus.java @@ -25,10 +25,13 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for vnfStatus. + * <p> + * Java class for vnfStatus. * - * <p>The following schema fragment specifies the expected content contained within this class. * <p> + * The following schema fragment specifies the expected content contained within this class. + * <p> + * * <pre> * <simpleType name="vnfStatus"> * <restriction base="{http://www.w3.org/2001/XMLSchema}string"> @@ -45,10 +48,7 @@ import javax.xml.bind.annotation.XmlType; @XmlEnum public enum VnfStatus { - ACTIVE, - FAILED, - NOTFOUND, - UNKNOWN; + ACTIVE, FAILED, NOTFOUND, UNKNOWN; public String value() { return name(); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfAlreadyExists.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfAlreadyExists.java index 38283aa17b..31ad3f4fc3 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfAlreadyExists.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfAlreadyExists.java @@ -25,18 +25,19 @@ package org.onap.so.adapters.vnf.exceptions; import javax.xml.ws.WebFault; /** - * This class reports an exception when trying to create a VNF when another - * VNF of the same name already exists in the target cloud/tenant. Note that - * the createVnf method suppresses this exception by default. + * This class reports an exception when trying to create a VNF when another VNF of the same name already exists in the + * target cloud/tenant. Note that the createVnf method suppresses this exception by default. * * */ -@WebFault (name="VnfAlreadyExists", faultBean="org.onap.so.adapters.vnf.exceptions.VnfExceptionBean", targetNamespace="http://org.onap.so/vnf") +@WebFault(name = "VnfAlreadyExists", faultBean = "org.onap.so.adapters.vnf.exceptions.VnfExceptionBean", + targetNamespace = "http://org.onap.so/vnf") public class VnfAlreadyExists extends VnfException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public VnfAlreadyExists (String name, String cloudId, String cloudOwner, String tenantId, String vnfId) { - super("Resource " + name + " already exists in owner/cloud/tenant " + cloudOwner + "/" + cloudId + "/" + tenantId + " with ID " + vnfId); - } + public VnfAlreadyExists(String name, String cloudId, String cloudOwner, String tenantId, String vnfId) { + super("Resource " + name + " already exists in owner/cloud/tenant " + cloudOwner + "/" + cloudId + "/" + + tenantId + " with ID " + vnfId); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfException.java index 39f48e64dd..c5dd92eda9 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfException.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfException.java @@ -23,58 +23,58 @@ package org.onap.so.adapters.vnf.exceptions; import javax.xml.ws.WebFault; - import org.onap.so.openstack.exceptions.MsoException; import org.onap.so.openstack.exceptions.MsoExceptionCategory; /** - * This class simply extends Exception (without addition additional functionality) - * to provide an identifier for VNF related exceptions on create, delete, query. + * This class simply extends Exception (without addition additional functionality) to provide an identifier for VNF + * related exceptions on create, delete, query. * * */ -@WebFault (name="VnfException", faultBean="org.onap.so.adapters.vnf.exceptions.VnfExceptionBean", targetNamespace="http://org.onap.so/vnf") +@WebFault(name = "VnfException", faultBean = "org.onap.so.adapters.vnf.exceptions.VnfExceptionBean", + targetNamespace = "http://org.onap.so/vnf") public class VnfException extends Exception { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; + + private VnfExceptionBean faultInfo; + + public VnfException(String msg) { + super(msg); + faultInfo = new VnfExceptionBean(msg); + } + + public VnfException(Throwable e) { + super(e); + faultInfo = new VnfExceptionBean(e.getMessage()); + } + + public VnfException(String msg, Throwable e) { + super(msg, e); + faultInfo = new VnfExceptionBean(msg); + } + + public VnfException(String msg, MsoExceptionCategory category) { + super(msg); + faultInfo = new VnfExceptionBean(msg, category); + } + + public VnfException(String msg, MsoExceptionCategory category, Throwable e) { + super(msg, e); + faultInfo = new VnfExceptionBean(msg, category); + } - private VnfExceptionBean faultInfo; - - public VnfException (String msg) { - super(msg); - faultInfo = new VnfExceptionBean (msg); - } - - public VnfException (Throwable e) { - super(e); - faultInfo = new VnfExceptionBean (e.getMessage()); - } - - public VnfException (String msg, Throwable e) { - super (msg, e); - faultInfo = new VnfExceptionBean (msg); - } + public VnfException(MsoException e) { + super(e); + faultInfo = new VnfExceptionBean(e.getContextMessage(), e.getCategory()); + } - public VnfException (String msg, MsoExceptionCategory category) { - super(msg); - faultInfo = new VnfExceptionBean (msg, category); - } - - public VnfException (String msg, MsoExceptionCategory category, Throwable e) { - super (msg, e); - faultInfo = new VnfExceptionBean (msg, category); - } - - public VnfException (MsoException e) { - super (e); - faultInfo = new VnfExceptionBean (e.getContextMessage(), e.getCategory()); - } - - public VnfExceptionBean getFaultInfo() { - return faultInfo; - } + public VnfExceptionBean getFaultInfo() { + return faultInfo; + } - public void setFaultInfo(VnfExceptionBean faultInfo) { - this.faultInfo = faultInfo; - } + public void setFaultInfo(VnfExceptionBean faultInfo) { + this.faultInfo = faultInfo; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfExceptionBean.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfExceptionBean.java index 011afa72ee..30e9fa590c 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfExceptionBean.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfExceptionBean.java @@ -22,7 +22,6 @@ package org.onap.so.adapters.vnf.exceptions; import java.io.Serializable; - import org.onap.so.openstack.exceptions.MsoExceptionCategory; /** @@ -33,42 +32,42 @@ public class VnfExceptionBean implements Serializable { private static final long serialVersionUID = -5699310749783790095L; private String message; - private MsoExceptionCategory category; - private Boolean rolledBack; + private MsoExceptionCategory category; + private Boolean rolledBack; - public VnfExceptionBean () {} + public VnfExceptionBean() {} - public VnfExceptionBean (String message) { - // Create a default category to prevent null pointer exceptions - this(message, MsoExceptionCategory.INTERNAL); - } + public VnfExceptionBean(String message) { + // Create a default category to prevent null pointer exceptions + this(message, MsoExceptionCategory.INTERNAL); + } - public VnfExceptionBean (String message, MsoExceptionCategory category) { - this.message = message; - this.category = category; - } + public VnfExceptionBean(String message, MsoExceptionCategory category) { + this.message = message; + this.category = category; + } - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } - public void setMessage(String message) { - this.message = message; - } + public void setMessage(String message) { + this.message = message; + } - public MsoExceptionCategory getCategory () { - return category; - } + public MsoExceptionCategory getCategory() { + return category; + } - public void setCategory (MsoExceptionCategory category) { - this.category = category; - } + public void setCategory(MsoExceptionCategory category) { + this.category = category; + } - public Boolean isRolledBack() { - return rolledBack; - } + public Boolean isRolledBack() { + return rolledBack; + } - public void setRolledBack(Boolean rolledBack) { - this.rolledBack = rolledBack; - } + public void setRolledBack(Boolean rolledBack) { + this.rolledBack = rolledBack; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfNotFound.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfNotFound.java index 18d622453b..4220d389c5 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfNotFound.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/exceptions/VnfNotFound.java @@ -24,18 +24,19 @@ package org.onap.so.adapters.vnf.exceptions; import javax.xml.ws.WebFault; /** - * This class reports an exception when trying to update a Network that does - * not exist in the target cloud/tenant. Note that deleteNetwork suppresses - * this exception (deletion of non-existent network is considered a success). + * This class reports an exception when trying to update a Network that does not exist in the target cloud/tenant. Note + * that deleteNetwork suppresses this exception (deletion of non-existent network is considered a success). * * */ -@WebFault (name="VnfNotFound", faultBean="org.onap.so.adapters.vnf.exceptions.VnfExceptionBean", targetNamespace="http://org.onap.so/vnf") +@WebFault(name = "VnfNotFound", faultBean = "org.onap.so.adapters.vnf.exceptions.VnfExceptionBean", + targetNamespace = "http://org.onap.so/vnf") public class VnfNotFound extends VnfException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public VnfNotFound (String cloudId, String cloudOwner, String tenantId, String vnfName) { - super("Resource " + vnfName + " not found in owner/cloud/tenant " + cloudOwner + "/" + cloudId + "/" + tenantId); - } + public VnfNotFound(String cloudId, String cloudOwner, String tenantId, String vnfName) { + super("Resource " + vnfName + " not found in owner/cloud/tenant " + cloudOwner + "/" + cloudId + "/" + + tenantId); + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java index 6b06761474..c6fd73d9cb 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java @@ -1,17 +1,14 @@ /* * Copyright (C) 2018 Bell Canada. 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 + * 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 + * 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. + * 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. */ package org.onap.so.heatbridge; @@ -23,8 +20,8 @@ import org.openstack4j.model.compute.Server; import org.openstack4j.model.heat.Resource; /** - * Defines the contract to extract Heat Stack Resources from Openstack and inventory it to AAI. - * This API is used only to "create" objects in AAI. + * Defines the contract to extract Heat Stack Resources from Openstack and inventory it to AAI. This API is used only to + * "create" objects in AAI. */ public interface HeatBridgeApi { @@ -54,8 +51,9 @@ public interface HeatBridgeApi { List<String> extractStackResourceIdsByResourceType(List<Resource> stackResources, String resourceType); /** - * Get network IDs for a given list of network names. - * It is assumed that there is a one to one mapping between the name and ID. + * Get network IDs for a given list of network names. It is assumed that there is a one to one mapping between the + * name and ID. + * * @param networkNameList List of network names * @return List of matching network IDs */ diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeException.java index f993d71e4c..9bf2ec73f4 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeException.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeException.java @@ -1,17 +1,14 @@ /* * Copyright (C) 2018 Bell Canada. 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 + * 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 + * 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. + * 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. */ package org.onap.so.heatbridge; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java index 90ceeb7d1c..a5e6a4558f 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java @@ -1,17 +1,14 @@ /* * Copyright (C) 2018 Bell Canada. 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 + * 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 + * 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. + * 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. */ package org.onap.so.heatbridge; @@ -23,10 +20,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; - import javax.annotation.Nonnull; import javax.ws.rs.WebApplicationException; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.validator.routines.InetAddressValidator; import org.onap.aai.domain.yang.Flavor; @@ -65,7 +60,6 @@ import org.openstack4j.model.network.IP; import org.openstack4j.model.network.Network; import org.openstack4j.model.network.NetworkType; import org.openstack4j.model.network.Port; - import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; @@ -76,7 +70,8 @@ import com.google.common.collect.ImmutableMap; public class HeatBridgeImpl implements HeatBridgeApi { private static final Logger logger = LoggerFactory.getLogger(HeatBridgeImpl.class); - private static final String ERR_MSG_NULL_OS_CLIENT = "Initialization error: Null openstack client. Authenticate with Keystone first."; + private static final String ERR_MSG_NULL_OS_CLIENT = + "Initialization error: Null openstack client. Authenticate with Keystone first."; private static final String OOB_MGT_NETWORK_IDENTIFIER = "Management"; private OpenstackClient osClient; private AAIResourcesClient resourcesClient; @@ -89,7 +84,7 @@ public class HeatBridgeImpl implements HeatBridgeApi { public HeatBridgeImpl(AAIResourcesClient resourcesClient, final CloudIdentity cloudIdentity, - @Nonnull final String cloudOwner, @Nonnull final String cloudRegionId, @Nonnull final String tenantId) { + @Nonnull final String cloudOwner, @Nonnull final String cloudRegionId, @Nonnull final String tenantId) { Objects.requireNonNull(cloudOwner, "Null cloud-owner value!"); Objects.requireNonNull(cloudRegionId, "Null cloud-region identifier!"); Objects.requireNonNull(tenantId, "Null tenant identifier!"); @@ -105,10 +100,11 @@ public class HeatBridgeImpl implements HeatBridgeApi { @Override public OpenstackClient authenticate() throws HeatBridgeException { - this.osClient = new MsoCloudClientFactoryImpl(new OpenstackClientFactoryImpl()) - .getOpenstackClient(cloudIdentity.getIdentityUrl(), cloudIdentity.getMsoId(), cloudIdentity.getMsoPass(), cloudRegionId, tenantId); - logger.debug("Successfully authenticated with keystone for tenant: " + tenantId + " and cloud " - + "region: " + cloudRegionId); + this.osClient = new MsoCloudClientFactoryImpl(new OpenstackClientFactoryImpl()).getOpenstackClient( + cloudIdentity.getIdentityUrl(), cloudIdentity.getMsoId(), cloudIdentity.getMsoPass(), cloudRegionId, + tenantId); + logger.debug("Successfully authenticated with keystone for tenant: " + tenantId + " and cloud " + "region: " + + cloudRegionId); return osClient; } @@ -116,29 +112,27 @@ public class HeatBridgeImpl implements HeatBridgeApi { public List<Resource> queryNestedHeatStackResources(final String heatStackId) { Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT); Preconditions.checkState(!Strings.isNullOrEmpty(heatStackId), "Invalid heatStackId!"); - List<Resource> stackBasedResources = osClient - .getStackBasedResources(heatStackId, HeatBridgeConstants.OS_DEFAULT_HEAT_NESTING); + List<Resource> stackBasedResources = + osClient.getStackBasedResources(heatStackId, HeatBridgeConstants.OS_DEFAULT_HEAT_NESTING); logger.debug(stackBasedResources.size() + " heat stack resources are extracted for stack: " + heatStackId); return stackBasedResources; } @Override public List<String> extractStackResourceIdsByResourceType(final List<Resource> stackResources, - final String resourceType) { - return stackResources.stream() - .filter(stackResource -> stackResource.getType().equals(resourceType)) - .map(Resource::getPhysicalResourceId) - .collect(Collectors.toList()); + final String resourceType) { + return stackResources.stream().filter(stackResource -> stackResource.getType().equals(resourceType)) + .map(Resource::getPhysicalResourceId).collect(Collectors.toList()); } @Override public List<String> extractNetworkIds(final List<String> networkNameList) { Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT); return networkNameList.stream() - .map(netName -> osClient.listNetworksByFilter(ImmutableMap.of(HeatBridgeConstants.OS_NAME_KEY, netName))) - .filter(nets -> nets != null && nets.size() == 1) //extract network-id only if network-name is unique - .map(nets -> nets.get(0).getId()) - .collect(Collectors.toList()); + .map(netName -> osClient + .listNetworksByFilter(ImmutableMap.of(HeatBridgeConstants.OS_NAME_KEY, netName))) + .filter(nets -> nets != null && nets.size() == 1) // extract network-id only if network-name is unique + .map(nets -> nets.get(0).getId()).collect(Collectors.toList()); } @Override @@ -146,8 +140,8 @@ public class HeatBridgeImpl implements HeatBridgeApi { Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT); // Filter Openstack Compute resources - List<String> serverIds = extractStackResourceIdsByResourceType(stackResources, - HeatBridgeConstants.OS_SERVER_RESOURCE_TYPE); + List<String> serverIds = + extractStackResourceIdsByResourceType(stackResources, HeatBridgeConstants.OS_SERVER_RESOURCE_TYPE); return serverIds.stream().map(serverId -> osClient.getServerById(serverId)).collect(Collectors.toList()); } @@ -155,23 +149,24 @@ public class HeatBridgeImpl implements HeatBridgeApi { public List<org.openstack4j.model.compute.Image> extractOpenstackImagesFromServers(final List<Server> servers) { Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT); return servers.stream().map(Server::getImage) - .filter(distinctByProperty(org.openstack4j.model.compute.Image::getId)).collect(Collectors.toList()); + .filter(distinctByProperty(org.openstack4j.model.compute.Image::getId)).collect(Collectors.toList()); } @Override public List<org.openstack4j.model.compute.Flavor> extractOpenstackFlavorsFromServers(final List<Server> servers) { Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT); return servers.stream().map(Server::getFlavor) - .filter(distinctByProperty(org.openstack4j.model.compute.Flavor::getId)).collect(Collectors.toList()); + .filter(distinctByProperty(org.openstack4j.model.compute.Flavor::getId)).collect(Collectors.toList()); } @Override public void buildAddImagesToAaiAction(final List<org.openstack4j.model.compute.Image> images) - throws HeatBridgeException { + throws HeatBridgeException { for (org.openstack4j.model.compute.Image image : images) { Image aaiImage = aaiHelper.buildImage(image); try { - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.IMAGE, cloudOwner, cloudRegionId, aaiImage.getImageId()); + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.IMAGE, cloudOwner, cloudRegionId, + aaiImage.getImageId()); if (!resourcesClient.exists(uri)) { transaction.create(uri, aaiImage); logger.debug("Queuing AAI command to add image: " + aaiImage.getImageId()); @@ -179,19 +174,20 @@ public class HeatBridgeImpl implements HeatBridgeApi { logger.debug("Nothing to add since image: " + aaiImage.getImageId() + "already exists in AAI."); } } catch (WebApplicationException e) { - throw new HeatBridgeException("Failed to update image to AAI: " + aaiImage.getImageId() + ". Error" - + " cause: " + e, e); + throw new HeatBridgeException( + "Failed to update image to AAI: " + aaiImage.getImageId() + ". Error" + " cause: " + e, e); } } } @Override public void buildAddFlavorsToAaiAction(final List<org.openstack4j.model.compute.Flavor> flavors) - throws HeatBridgeException { + throws HeatBridgeException { for (org.openstack4j.model.compute.Flavor flavor : flavors) { Flavor aaiFlavor = aaiHelper.buildFlavor(flavor); try { - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.FLAVOR, cloudOwner, cloudRegionId, aaiFlavor.getFlavorId()); + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.FLAVOR, cloudOwner, cloudRegionId, + aaiFlavor.getFlavorId()); if (!resourcesClient.exists(uri)) { transaction.create(uri, aaiFlavor); logger.debug("Queuing AAI command to add flavor: " + aaiFlavor.getFlavorId()); @@ -199,31 +195,32 @@ public class HeatBridgeImpl implements HeatBridgeApi { logger.debug("Nothing to add since flavor: " + aaiFlavor.getFlavorId() + "already exists in AAI."); } } catch (WebApplicationException e) { - throw new HeatBridgeException("Failed to update flavor to AAI: " + aaiFlavor.getFlavorId() + ". Error" - + " cause: " + e, e); + throw new HeatBridgeException( + "Failed to update flavor to AAI: " + aaiFlavor.getFlavorId() + ". Error" + " cause: " + e, e); } } } @Override public void buildAddVserversToAaiAction(final String genericVnfId, final String vfModuleId, - final List<Server> servers) { + final List<Server> servers) { servers.forEach(server -> { Vserver vserver = aaiHelper.buildVserver(server.getId(), server); // Build vserver relationships to: image, flavor, pserver, vf-module - vserver.setRelationshipList(aaiHelper.getVserverRelationshipList(cloudOwner, cloudRegionId, genericVnfId, - vfModuleId, server)); - transaction.create(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegionId, tenantId, vserver.getVserverId()), vserver); + vserver.setRelationshipList( + aaiHelper.getVserverRelationshipList(cloudOwner, cloudRegionId, genericVnfId, vfModuleId, server)); + transaction.create(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegionId, + tenantId, vserver.getVserverId()), vserver); }); } @Override public void buildAddVserverLInterfacesToAaiAction(final List<Resource> stackResources, - final List<String> oobMgtNetIds) { + final List<String> oobMgtNetIds) { Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT); - List<String> portIds = extractStackResourceIdsByResourceType(stackResources, - HeatBridgeConstants.OS_PORT_RESOURCE_TYPE); + List<String> portIds = + extractStackResourceIdsByResourceType(stackResources, HeatBridgeConstants.OS_PORT_RESOURCE_TYPE); for (String portId : portIds) { Port port = osClient.getPortById(portId); LInterface lIf = new LInterface(); @@ -240,8 +237,8 @@ public class HeatBridgeImpl implements HeatBridgeApi { updateLInterfaceVlan(port, lIf); // Update l-interface to the vserver - transaction.create(AAIUriFactory.createResourceUri( - AAIObjectType.L_INTERFACE, cloudOwner, cloudRegionId, tenantId, port.getDeviceId(), lIf.getInterfaceName()), lIf); + transaction.create(AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, cloudOwner, cloudRegionId, + tenantId, port.getDeviceId(), lIf.getInterfaceName()), lIf); } } @@ -278,56 +275,57 @@ public class HeatBridgeImpl implements HeatBridgeApi { } /** - * Needs to be corrected according to the specification that is in draft - * If pserver/p-interface does not have a SRIOV-PF object matching the PCI-ID of the Openstack port object, then - * create it in AAI. - * Openstack SRIOV Port object has pci-id (to match sriov-pf on pserver/p-interface), physical-network ID (that - * matches the p-interface name). + * Needs to be corrected according to the specification that is in draft If pserver/p-interface does not have a + * SRIOV-PF object matching the PCI-ID of the Openstack port object, then create it in AAI. Openstack SRIOV Port + * object has pci-id (to match sriov-pf on pserver/p-interface), physical-network ID (that matches the p-interface + * name). * * @param port Openstack port object * @param lIf AAI l-interface object */ private void updateSriovPfToPserver(final Port port, final LInterface lIf) { if (port.getProfile() == null || Strings - .isNullOrEmpty(port.getProfile().get(HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY).toString())) { + .isNullOrEmpty(port.getProfile().get(HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY).toString())) { logger.debug("The SRIOV port:" + port.getName() + " is missing physical-network-id, cannot update " - + "sriov-pf object for host pserver: " + port.getHostId()); + + "sriov-pf object for host pserver: " + port.getHostId()); return; } - Optional<String> matchingPifName = HeatBridgeUtils - .getMatchingPserverPifName(port.getProfile().get(HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY).toString()); + Optional<String> matchingPifName = HeatBridgeUtils.getMatchingPserverPifName( + port.getProfile().get(HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY).toString()); if (matchingPifName.isPresent()) { // Update l-interface description String pserverHostName = port.getHostId(); - lIf.setInterfaceDescription( - "Attached to SR-IOV port: " + pserverHostName + "::" + matchingPifName.get()); + lIf.setInterfaceDescription("Attached to SR-IOV port: " + pserverHostName + "::" + matchingPifName.get()); try { - Optional<PInterface> matchingPIf = resourcesClient.get(PInterface.class, - AAIUriFactory.createResourceUri(AAIObjectType.P_INTERFACE, pserverHostName, matchingPifName.get()).depth(Depth.ONE)); + Optional<PInterface> matchingPIf = resourcesClient.get(PInterface.class, + AAIUriFactory + .createResourceUri(AAIObjectType.P_INTERFACE, pserverHostName, matchingPifName.get()) + .depth(Depth.ONE)); if (matchingPIf.isPresent()) { - SriovPfs pIfSriovPfs = matchingPIf.get().getSriovPfs(); + SriovPfs pIfSriovPfs = matchingPIf.get().getSriovPfs(); if (pIfSriovPfs == null) { pIfSriovPfs = new SriovPfs(); } // Extract PCI-ID from OS port object String pfPciId = port.getProfile().get(HeatBridgeConstants.OS_PCI_SLOT_KEY).toString(); - + List<SriovPf> existingSriovPfs = pIfSriovPfs.getSriovPf(); if (CollectionUtils.isEmpty(existingSriovPfs) || existingSriovPfs.stream() - .noneMatch(existingSriovPf -> existingSriovPf.getPfPciId().equals(pfPciId))) { + .noneMatch(existingSriovPf -> existingSriovPf.getPfPciId().equals(pfPciId))) { // Add sriov-pf object with PCI-ID to AAI SriovPf sriovPf = new SriovPf(); sriovPf.setPfPciId(pfPciId); - logger.debug("Queuing AAI command to update sriov-pf object to pserver: " + pserverHostName + "/" + - matchingPifName.get()); - transaction.create(AAIUriFactory.createResourceUri( - AAIObjectType.SRIOV_PF, pserverHostName, matchingPifName.get(), sriovPf.getPfPciId()), sriovPf); + logger.debug("Queuing AAI command to update sriov-pf object to pserver: " + pserverHostName + + "/" + matchingPifName.get()); + transaction.create(AAIUriFactory.createResourceUri(AAIObjectType.SRIOV_PF, pserverHostName, + matchingPifName.get(), sriovPf.getPfPciId()), sriovPf); } } } catch (WebApplicationException e) { // Silently log that we failed to update the Pserver p-interface with PCI-ID - logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.GENERAL_EXCEPTION, pserverHostName, matchingPifName.get(), cloudOwner, - tenantId, "OpenStack", "Heatbridge", ErrorCode.DataError.getValue(), "Exception - Failed to add sriov-pf object to pserver", e); + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.GENERAL_EXCEPTION, pserverHostName, + matchingPifName.get(), cloudOwner, tenantId, "OpenStack", "Heatbridge", + ErrorCode.DataError.getValue(), "Exception - Failed to add sriov-pf object to pserver", e); } } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/constants/HeatBridgeConstants.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/constants/HeatBridgeConstants.java index 1f302341ad..dd64d53732 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/constants/HeatBridgeConstants.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/constants/HeatBridgeConstants.java @@ -1,17 +1,14 @@ /* * Copyright (C) 2018 Bell Canada. 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 + * 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 + * 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. + * 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. */ package org.onap.so.heatbridge.constants; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactory.java index 100b50e502..edf5e2d339 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactory.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactory.java @@ -1,17 +1,14 @@ /* * Copyright (C) 2018 Bell Canada. 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 + * 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 + * 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. + * 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. */ package org.onap.so.heatbridge.factory; @@ -37,5 +34,6 @@ public interface MsoCloudClientFactory { */ - OpenstackClient getOpenstackClient(String url, String msoId, String msoPass, String cloudRegionId, String tenantId) throws HeatBridgeException; + OpenstackClient getOpenstackClient(String url, String msoId, String msoPass, String cloudRegionId, String tenantId) + throws HeatBridgeException; } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactoryImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactoryImpl.java index b70b32a4d6..bd74bf6aa0 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactoryImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactoryImpl.java @@ -1,17 +1,14 @@ /* * Copyright (C) 2018 Bell Canada. 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 + * 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 + * 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. + * 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. */ package org.onap.so.heatbridge.factory; @@ -29,10 +26,9 @@ import org.onap.so.heatbridge.openstack.factory.OpenstackClientFactory; import org.onap.so.utils.CryptoUtils; /** - * This class implements {@link MsoCloudClientFactory} - * It loads the cloud configuration from SO and uses it to authenticate with keystone. - * As a result of authentication with keystone, it returns the Openstack client with the auth token so that - * subsequent API calls to Openstack can be made. + * This class implements {@link MsoCloudClientFactory} It loads the cloud configuration from SO and uses it to + * authenticate with keystone. As a result of authentication with keystone, it returns the Openstack client with the + * auth token so that subsequent API calls to Openstack can be made. */ public class MsoCloudClientFactoryImpl implements MsoCloudClientFactory { @@ -42,23 +38,23 @@ public class MsoCloudClientFactoryImpl implements MsoCloudClientFactory { Objects.requireNonNull(openstackClientFactory, "Null OpenstackClientFactory object"); this.openstackClientFactory = openstackClientFactory; } + @Override - public OpenstackClient getOpenstackClient(@Nonnull String url, @Nonnull String msoId, @Nonnull String msoPass, @Nonnull String cloudRegionId, @Nonnull String tenantId) throws - HeatBridgeException { + public OpenstackClient getOpenstackClient(@Nonnull String url, @Nonnull String msoId, @Nonnull String msoPass, + @Nonnull String cloudRegionId, @Nonnull String tenantId) throws HeatBridgeException { Objects.requireNonNull(url, "Null openstack url!"); Objects.requireNonNull(msoId, "Null openstack user id!"); Objects.requireNonNull(msoPass, "Null openstack password!"); Objects.requireNonNull(cloudRegionId, "Null cloud-region ID!"); Objects.requireNonNull(tenantId, "Null tenant ID!"); try { - final OpenstackAccess osAccess = new OpenstackAccessBuilder() - .setBaseUrl(url) // keystone URL - .setUser(msoId) // keystone username - .setPassword(CryptoUtils.decryptCloudConfigPassword(msoPass)) // keystone decrypted password - .setRegion(cloudRegionId) // openstack region - .setDomainName(HeatBridgeConstants.OS_DEFAULT_DOMAIN_NAME) // hardcode to "default" - .setTenantId(tenantId) // tenantId - .build(); + final OpenstackAccess osAccess = new OpenstackAccessBuilder().setBaseUrl(url) // keystone URL + .setUser(msoId) // keystone username + .setPassword(CryptoUtils.decryptCloudConfigPassword(msoPass)) // keystone decrypted password + .setRegion(cloudRegionId) // openstack region + .setDomainName(HeatBridgeConstants.OS_DEFAULT_DOMAIN_NAME) // hardcode to "default" + .setTenantId(tenantId) // tenantId + .build(); // Identify the Keystone version String version = new URL(url).getPath().replace("/", ""); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java index a0f1f0798f..515f2dc0e5 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java @@ -1,17 +1,14 @@ /* * Copyright (C) 2018 Bell Canada. * - * 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 + * 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 + * 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. + * 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. */ package org.onap.so.heatbridge.helpers; @@ -49,58 +46,49 @@ public class AaiHelper { * @param vfModuleId AAI vf-module identifier * @param server Openstack Server object */ - public RelationshipList getVserverRelationshipList(final String cloudOwner, final String cloudRegionId, final String - genericVnfId, final String vfModuleId, final Server server) { + public RelationshipList getVserverRelationshipList(final String cloudOwner, final String cloudRegionId, + final String genericVnfId, final String vfModuleId, final Server server) { RelationshipList relationshipList = new RelationshipList(); List<Relationship> relationships = relationshipList.getRelationship(); // vserver to pserver relationship - Relationship pserverRelationship = buildRelationship(HeatBridgeConstants.AAI_PSERVER, - ImmutableMap.<String, String>builder() - .put(HeatBridgeConstants.AAI_PSERVER_HOSTNAME, server.getHypervisorHostname()) - .build()); + Relationship pserverRelationship = + buildRelationship(HeatBridgeConstants.AAI_PSERVER, ImmutableMap.<String, String>builder() + .put(HeatBridgeConstants.AAI_PSERVER_HOSTNAME, server.getHypervisorHostname()).build()); relationships.add(pserverRelationship); // vserver to vf-module relationship Relationship vfModuleRelationship = buildRelationship(HeatBridgeConstants.AAI_VF_MODULE, - ImmutableMap.<String, String>builder() - .put(HeatBridgeConstants.AAI_GENERIC_VNF_ID, genericVnfId) - .put(HeatBridgeConstants.AAI_VF_MODULE_ID, vfModuleId) - .build()); + ImmutableMap.<String, String>builder().put(HeatBridgeConstants.AAI_GENERIC_VNF_ID, genericVnfId) + .put(HeatBridgeConstants.AAI_VF_MODULE_ID, vfModuleId).build()); relationships.add(vfModuleRelationship); // vserver to image relationship Relationship imageRel = buildRelationship(HeatBridgeConstants.AAI_IMAGE, - ImmutableMap.<String, String>builder() - .put(HeatBridgeConstants.AAI_CLOUD_OWNER, cloudOwner) - .put(HeatBridgeConstants.AAI_CLOUD_REGION_ID, cloudRegionId) - .put(HeatBridgeConstants.AAI_IMAGE_ID, server.getImage().getId()) - .build()); + ImmutableMap.<String, String>builder().put(HeatBridgeConstants.AAI_CLOUD_OWNER, cloudOwner) + .put(HeatBridgeConstants.AAI_CLOUD_REGION_ID, cloudRegionId) + .put(HeatBridgeConstants.AAI_IMAGE_ID, server.getImage().getId()).build()); relationships.add(imageRel); // vserver to flavor relationship Relationship flavorRel = buildRelationship(HeatBridgeConstants.AAI_FLAVOR, - ImmutableMap.<String, String>builder() - .put(HeatBridgeConstants.AAI_CLOUD_OWNER, cloudOwner) - .put(HeatBridgeConstants.AAI_CLOUD_REGION_ID, cloudRegionId) - .put(HeatBridgeConstants.AAI_FLAVOR_ID, server.getFlavor().getId()) - .build()); + ImmutableMap.<String, String>builder().put(HeatBridgeConstants.AAI_CLOUD_OWNER, cloudOwner) + .put(HeatBridgeConstants.AAI_CLOUD_REGION_ID, cloudRegionId) + .put(HeatBridgeConstants.AAI_FLAVOR_ID, server.getFlavor().getId()).build()); relationships.add(flavorRel); return relationshipList; } public RelationshipList getLInterfaceRelationshipList(final String pserverName, final String pIfName, - final String pfPciId) { + final String pfPciId) { RelationshipList relationshipList = new RelationshipList(); List<Relationship> relationships = relationshipList.getRelationship(); // sriov-vf to sriov-pf relationship Relationship sriovPfRelationship = buildRelationship(HeatBridgeConstants.AAI_SRIOV_PF, - ImmutableMap.<String, String>builder() - .put(HeatBridgeConstants.AAI_PSERVER_HOSTNAME, pserverName) - .put(HeatBridgeConstants.AAI_P_INTERFACE_NAME, pIfName) - .put(HeatBridgeConstants.AAI_SRIOV_PF_PCI_ID, pfPciId) - .build()); + ImmutableMap.<String, String>builder().put(HeatBridgeConstants.AAI_PSERVER_HOSTNAME, pserverName) + .put(HeatBridgeConstants.AAI_P_INTERFACE_NAME, pIfName) + .put(HeatBridgeConstants.AAI_SRIOV_PF_PCI_ID, pfPciId).build()); relationships.add(sriovPfRelationship); return relationshipList; @@ -122,7 +110,7 @@ public class AaiHelper { vserver.setVserverName2(server.getName()); vserver.setProvStatus(server.getStatus().value()); server.getLinks().stream().filter(link -> link.getRel().equals(HeatBridgeConstants.OS_RESOURCES_SELF_LINK_KEY)) - .findFirst().ifPresent(link -> vserver.setVserverSelflink(link.getHref())); + .findFirst().ifPresent(link -> vserver.setVserverSelflink(link.getHref())); return vserver; } @@ -139,7 +127,7 @@ public class AaiHelper { aaiImage.setImageOsDistro(HeatBridgeConstants.OS_UNKNOWN_KEY); aaiImage.setImageOsVersion(HeatBridgeConstants.OS_UNKNOWN_KEY); image.getLinks().stream().filter(link -> link.getRel().equals(HeatBridgeConstants.OS_RESOURCES_SELF_LINK_KEY)) - .findFirst().ifPresent(link -> aaiImage.setImageSelflink(link.getHref())); + .findFirst().ifPresent(link -> aaiImage.setImageSelflink(link.getHref())); return aaiImage; } @@ -154,7 +142,7 @@ public class AaiHelper { aaiFlavor.setFlavorId(flavor.getId()); aaiFlavor.setFlavorName(flavor.getName()); flavor.getLinks().stream().filter(link -> link.getRel().equals(HeatBridgeConstants.OS_RESOURCES_SELF_LINK_KEY)) - .findFirst().ifPresent(link -> aaiFlavor.setFlavorSelflink(link.getHref())); + .findFirst().ifPresent(link -> aaiFlavor.setFlavorSelflink(link.getHref())); return aaiFlavor; } @@ -167,7 +155,7 @@ public class AaiHelper { public List<String> getFlavorsUriFromVserver(final List<Vserver> vservers) { List<String> flavorUris = new ArrayList<>(); vservers.forEach(vserver -> flavorUris.addAll( - filterRelatedLinksByRelatedToProperty(vserver.getRelationshipList(), HeatBridgeConstants.AAI_FLAVOR))); + filterRelatedLinksByRelatedToProperty(vserver.getRelationshipList(), HeatBridgeConstants.AAI_FLAVOR))); return flavorUris; } @@ -180,7 +168,7 @@ public class AaiHelper { public List<String> getImagesUriFromVserver(final List<Vserver> vservers) { List<String> imageUris = new ArrayList<>(); vservers.forEach(vserver -> imageUris.addAll( - filterRelatedLinksByRelatedToProperty(vserver.getRelationshipList(), HeatBridgeConstants.AAI_IMAGE))); + filterRelatedLinksByRelatedToProperty(vserver.getRelationshipList(), HeatBridgeConstants.AAI_IMAGE))); return imageUris; } @@ -192,20 +180,18 @@ public class AaiHelper { */ public Map<String, List<String>> getPserverToPciIdMap(final List<Vserver> vservers) { Map<String, List<String>> pserverToPciIdMap = new HashMap<>(); - for(Vserver vserver : vservers) { - if(vserver.getLInterfaces() != null) { - List<String> pciIds = vserver.getLInterfaces().getLInterface() - .stream() - .filter(lInterface -> lInterface.getSriovVfs() != null - && CollectionUtils.isNotEmpty(lInterface.getSriovVfs().getSriovVf())) - .flatMap(lInterface -> lInterface.getSriovVfs().getSriovVf().stream()) - .map(SriovVf::getPciId) - .collect(Collectors.toList()); + for (Vserver vserver : vservers) { + if (vserver.getLInterfaces() != null) { + List<String> pciIds = vserver.getLInterfaces().getLInterface().stream() + .filter(lInterface -> lInterface.getSriovVfs() != null + && CollectionUtils.isNotEmpty(lInterface.getSriovVfs().getSriovVf())) + .flatMap(lInterface -> lInterface.getSriovVfs().getSriovVf().stream()).map(SriovVf::getPciId) + .collect(Collectors.toList()); if (CollectionUtils.isNotEmpty(pciIds)) { List<String> matchingPservers = extractRelationshipDataValue(vserver.getRelationshipList(), - HeatBridgeConstants.AAI_PSERVER, HeatBridgeConstants.AAI_PSERVER_HOSTNAME); + HeatBridgeConstants.AAI_PSERVER, HeatBridgeConstants.AAI_PSERVER_HOSTNAME); Preconditions.checkState(matchingPservers != null && matchingPservers.size() == 1, - "Invalid pserver relationships for vserver: " + vserver.getVserverName()); + "Invalid pserver relationships for vserver: " + vserver.getVserverName()); pserverToPciIdMap.put(matchingPservers.get(0), pciIds); } } @@ -214,8 +200,8 @@ public class AaiHelper { } /** - * Extract from relationship-list object all the relationship-value that match the related-to and - * relationship-key fields. + * Extract from relationship-list object all the relationship-value that match the related-to and relationship-key + * fields. * * @param relationshipListObj AAI relationship-list object * @param relatedToProperty related-to value @@ -223,15 +209,14 @@ public class AaiHelper { * @return relationship-value matching the key requested for the relationship object of type related-to property */ private List<String> extractRelationshipDataValue(final RelationshipList relationshipListObj, - final String relatedToProperty, final String relationshipKey) { + final String relatedToProperty, final String relationshipKey) { if (relationshipListObj != null && relationshipListObj.getRelationship() != null) { return relationshipListObj.getRelationship().stream() - .filter(relationship -> relationship.getRelatedTo().equals(relatedToProperty)) - .map(Relationship::getRelationshipData) - .flatMap(Collection::stream) - .filter(data -> data.getRelationshipKey() != null && relationshipKey.equals(data.getRelationshipKey())) - .map(RelationshipData::getRelationshipValue) - .collect(Collectors.toList()); + .filter(relationship -> relationship.getRelatedTo().equals(relatedToProperty)) + .map(Relationship::getRelationshipData).flatMap(Collection::stream) + .filter(data -> data.getRelationshipKey() != null + && relationshipKey.equals(data.getRelationshipKey())) + .map(RelationshipData::getRelationshipValue).collect(Collectors.toList()); } return new ArrayList<>(); } @@ -244,12 +229,11 @@ public class AaiHelper { * @return a list of related-links filtered by the specified related-to property */ private List<String> filterRelatedLinksByRelatedToProperty(final RelationshipList relationshipListObj, - final String relatedToProperty) { + final String relatedToProperty) { if (relationshipListObj != null && relationshipListObj.getRelationship() != null) { return relationshipListObj.getRelationship().stream() - .filter(relationship -> relationship.getRelatedTo().equals(relatedToProperty)) - .map(Relationship::getRelatedLink) - .collect(Collectors.toList()); + .filter(relationship -> relationship.getRelatedTo().equals(relatedToProperty)) + .map(Relationship::getRelatedLink).collect(Collectors.toList()); } return new ArrayList<>(); } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClient.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClient.java index 143e33581d..1fa41ee2a0 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClient.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClient.java @@ -27,6 +27,7 @@ public interface OpenstackClient { /** * Get a server object by server ID + * * @param serverId Unique server-name (simple name) or server-id (UUID) * @return Server object */ @@ -34,6 +35,7 @@ public interface OpenstackClient { /** * Get a port object by port ID + * * @param portId Unique UUID of the port. * @return Port object. */ @@ -41,12 +43,14 @@ public interface OpenstackClient { /** * Returns a list of all ports we have the right to see + * * @return List of all Openstack ports */ List<Port> getAllPorts(); /** * Returns a list of all the resources for the stack + * * @param stackId Stack name or unique UUID * @param nestingDepth The recursion level for which resources will be listed. * @return List of Openstack Stack resources @@ -55,6 +59,7 @@ public interface OpenstackClient { /** * Get a network instance by network ID + * * @param networkId Unique UUID of the network. * @return Network object. */ @@ -62,6 +67,7 @@ public interface OpenstackClient { /** * List networks by filtering parameters + * * @param filterParams key-value pairs for filtering params * @return List of filtered Network objects */ diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientImpl.java index ebd4753323..2843eb226e 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientImpl.java @@ -38,15 +38,13 @@ abstract class OpenstackClientImpl implements OpenstackClient { } @Override - public List<Port> getAllPorts() { return (List<Port>)getClient().networking().port().list(); } + public List<Port> getAllPorts() { + return (List<Port>) getClient().networking().port().list(); + } @Override public List<Resource> getStackBasedResources(String stackId, int nestingDepth) { - return getClient().heat() - .resources() - .list(stackId, nestingDepth) - .stream() - .filter(Objects::nonNull) + return getClient().heat().resources().list(stackId, nestingDepth).stream().filter(Objects::nonNull) .collect(Collectors.toList()); } @@ -62,6 +60,7 @@ abstract class OpenstackClientImpl implements OpenstackClient { /** * Retrieves the specific client to utilize. + * * @return The specific client to utilize */ protected abstract OSClient getClient(); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactoryImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactoryImpl.java index 141dd4fe50..25b3f1dbeb 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactoryImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactoryImpl.java @@ -40,15 +40,14 @@ public class OpenstackClientFactoryImpl implements OpenstackClientFactory { OSClientV3 client; try { - client = OSFactory.builderV3() - .endpoint(osAccess.getUrl()) - .credentials(osAccess.getUser(), osAccess.getPassword(), osAccess.getDomainNameIdentifier()) - .scopeToProject(Identifier.byId(osAccess.getTenantId())) - .authenticate() - .useRegion(osAccess.getRegion()); + client = OSFactory.builderV3().endpoint(osAccess.getUrl()) + .credentials(osAccess.getUser(), osAccess.getPassword(), osAccess.getDomainNameIdentifier()) + .scopeToProject(Identifier.byId(osAccess.getTenantId())).authenticate() + .useRegion(osAccess.getRegion()); return new OpenstackV3ClientImpl(client); } catch (AuthenticationException exception) { - throw new OpenstackClientException("Failed to authenticate with Keystone-v3: " + osAccess.getUrl(), exception); + throw new OpenstackClientException("Failed to authenticate with Keystone-v3: " + osAccess.getUrl(), + exception); } } @@ -62,16 +61,13 @@ public class OpenstackClientFactoryImpl implements OpenstackClientFactory { OSClientV2 client; try { - client = OSFactory.builderV2() - .endpoint(osAccess.getUrl()) - .credentials(osAccess.getUser(), osAccess.getPassword()) - .tenantId(osAccess.getTenantId()) - .authenticate() - .useRegion(osAccess.getRegion()); + client = OSFactory.builderV2().endpoint(osAccess.getUrl()) + .credentials(osAccess.getUser(), osAccess.getPassword()).tenantId(osAccess.getTenantId()) + .authenticate().useRegion(osAccess.getRegion()); return new OpenstackV2ClientImpl(client); } catch (AuthenticationException exception) { throw new OpenstackClientException("Failed to authenticate with Keystone-v2.0: " + osAccess.getUrl(), - exception); + exception); } } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/utils/HeatBridgeUtils.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/utils/HeatBridgeUtils.java index 7daa8c2c71..d3faf1d7bf 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/utils/HeatBridgeUtils.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/utils/HeatBridgeUtils.java @@ -1,17 +1,14 @@ /* * Copyright (C) 2018 Bell Canada. 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 + * 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 + * 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. + * 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. */ package org.onap.so.heatbridge.utils; @@ -36,25 +33,25 @@ public class HeatBridgeUtils { private static final String COMPUTE_SIDE_DEDICATED_SRIOV_PREFIX = "sriov-d-"; public static Optional<String> getMatchingPserverPifName(@Nonnull final String physicalNetworkName) { - Preconditions.checkState(!Strings.isNullOrEmpty(physicalNetworkName), "Physical network name is null or " - + "empty!"); + Preconditions.checkState(!Strings.isNullOrEmpty(physicalNetworkName), + "Physical network name is null or " + "empty!"); if (physicalNetworkName.contains(OS_SIDE_DEDICATED_SRIOV_PREFIX)) { - return Optional - .of(physicalNetworkName.replace(OS_SIDE_DEDICATED_SRIOV_PREFIX, COMPUTE_SIDE_DEDICATED_SRIOV_PREFIX)); + return Optional.of( + physicalNetworkName.replace(OS_SIDE_DEDICATED_SRIOV_PREFIX, COMPUTE_SIDE_DEDICATED_SRIOV_PREFIX)); } else if (physicalNetworkName.contains(OS_SIDE_SHARED_SRIOV_PREFIX)) { return Optional - .of(physicalNetworkName.replace(OS_SIDE_SHARED_SRIOV_PREFIX, COMPUTE_SIDE_SHARED_SRIOV_PREFIX)); + .of(physicalNetworkName.replace(OS_SIDE_SHARED_SRIOV_PREFIX, COMPUTE_SIDE_SHARED_SRIOV_PREFIX)); } return Optional.empty(); } public static Optional<String> getMatchingPhysicalNetworkName(final String pserverPinterfaceName) { if (pserverPinterfaceName.contains(COMPUTE_SIDE_DEDICATED_SRIOV_PREFIX)) { - return Optional - .of(pserverPinterfaceName.replace(COMPUTE_SIDE_DEDICATED_SRIOV_PREFIX, OS_SIDE_DEDICATED_SRIOV_PREFIX)); + return Optional.of( + pserverPinterfaceName.replace(COMPUTE_SIDE_DEDICATED_SRIOV_PREFIX, OS_SIDE_DEDICATED_SRIOV_PREFIX)); } else if (pserverPinterfaceName.contains(COMPUTE_SIDE_SHARED_SRIOV_PREFIX)) { return Optional - .of(pserverPinterfaceName.replace(COMPUTE_SIDE_SHARED_SRIOV_PREFIX, OS_SIDE_SHARED_SRIOV_PREFIX)); + .of(pserverPinterfaceName.replace(COMPUTE_SIDE_SHARED_SRIOV_PREFIX, OS_SIDE_SHARED_SRIOV_PREFIX)); } return Optional.empty(); } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduBlueprint.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduBlueprint.java index cef0371789..df714803e8 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduBlueprint.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduBlueprint.java @@ -23,67 +23,62 @@ package org.onap.so.vdu.utils; import java.util.Map; /* - * This Java bean class describes the template model of a VDU as distributed - * by SDC to SO. It is composed of one or more templates, one of which must be - * the main template, + * This Java bean class describes the template model of a VDU as distributed by SDC to SO. It is composed of one or more + * templates, one of which must be the main template, * - * The structure of this class corresponds to the format in which the templates - * and associated artifacts are represented in the SO Catalog. + * The structure of this class corresponds to the format in which the templates and associated artifacts are represented + * in the SO Catalog. * - * The map keys will be the "path" that is used to reference these artifacts within - * the other templates. This may be relevant to how different VDU plugins package - * the files for delivery to the sub-orchestrator. + * The map keys will be the "path" that is used to reference these artifacts within the other templates. This may be + * relevant to how different VDU plugins package the files for delivery to the sub-orchestrator. * - * In the future, it is possible that pre-packaged blueprints (e.g. complete TOSCA CSARs) - * could be stored in the catalog (and added to this structure). + * In the future, it is possible that pre-packaged blueprints (e.g. complete TOSCA CSARs) could be stored in the catalog + * (and added to this structure). * * This bean is passed as an input to instantiateVdu and updateVdu. */ public class VduBlueprint { - String vduModelId; - String mainTemplateName; - Map<String,byte[]> templateFiles; - Map<String,byte[]> attachedFiles; + String vduModelId; + String mainTemplateName; + Map<String, byte[]> templateFiles; + Map<String, byte[]> attachedFiles; - public String getVduModelId() { - return vduModelId; - } + public String getVduModelId() { + return vduModelId; + } - public void setVduModelId(String vduModelId) { - this.vduModelId = vduModelId; - } + public void setVduModelId(String vduModelId) { + this.vduModelId = vduModelId; + } - public String getMainTemplateName() { - return mainTemplateName; - } + public String getMainTemplateName() { + return mainTemplateName; + } - public void setMainTemplateName(String mainTemplateName) { - this.mainTemplateName = mainTemplateName; - } + public void setMainTemplateName(String mainTemplateName) { + this.mainTemplateName = mainTemplateName; + } - public Map<String, byte[]> getTemplateFiles() { - return templateFiles; - } + public Map<String, byte[]> getTemplateFiles() { + return templateFiles; + } - public void setTemplateFiles(Map<String, byte[]> templateFiles) { - this.templateFiles = templateFiles; - } + public void setTemplateFiles(Map<String, byte[]> templateFiles) { + this.templateFiles = templateFiles; + } - public Map<String, byte[]> getAttachedFiles() { - return attachedFiles; - } + public Map<String, byte[]> getAttachedFiles() { + return attachedFiles; + } - public void setAttachedFiles(Map<String, byte[]> attachedFiles) { - this.attachedFiles = attachedFiles; - } + public void setAttachedFiles(Map<String, byte[]> attachedFiles) { + this.attachedFiles = attachedFiles; + } - @Override + @Override public String toString() { - return "VduInfo {" + - "id='" + vduModelId + '\'' + - "mainTemplateName='" + mainTemplateName + '\'' + - '}'; + return "VduInfo {" + "id='" + vduModelId + '\'' + "mainTemplateName='" + mainTemplateName + '\'' + '}'; } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduInfo.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduInfo.java index 227d513a0b..22e3e1f5e9 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduInfo.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduInfo.java @@ -26,104 +26,97 @@ import java.util.HashMap; /* * This Java bean class relays VDU status information in a cloud-agnostic format. * - * This bean is returned by all implementors of the MsoVduUtils interface operations - * (instantiate, query, delete). + * This bean is returned by all implementors of the MsoVduUtils interface operations (instantiate, query, delete). */ public class VduInfo { - // Set defaults for everything - private String vduInstanceId = ""; - private String vduInstanceName = ""; - private VduStatus status = VduStatus.NOTFOUND; - private Map<String,Object> outputs = new HashMap<>(); - private Map<String,Object> inputs = new HashMap<>(); - private String lastAction; - private String actionStatus; - private String errorMessage; - - public VduInfo () { - } - - // Add more constructors as appropriate - // - - public VduInfo (String id, Map<String,Object> outputs) { - this.vduInstanceId = id; - if (outputs != null) this.outputs = outputs; - } - - public VduInfo (String id) { - this.vduInstanceId = id; - } - - public VduInfo (String id, VduStatus status) { - this.vduInstanceId = id; - this.status = status; - } - - public String getVnfInstanceId() { - return vduInstanceId; - } - - public void setVnfInstanceId (String id) { - this.vduInstanceId = id; - } - - public String getVnfInstanceName() { - return vduInstanceName; - } - - public void setVnfInstanceName (String name) { - this.vduInstanceName = name; - } - - public VduStatus getStatus() { - return status; - } - - public void setStatus (VduStatus status) { - this.status = status; - } - - public Map<String,Object> getOutputs () { - return outputs; - } - - public void setOutputs (Map<String,Object> outputs) { - this.outputs = outputs; - } - - public Map<String,Object> getInputs () { - return inputs; - } - - public void setInputs (Map<String,Object> inputs) { - this.inputs = inputs; - } - - public String getLastAction() { - return lastAction; - } - - public String getActionStatus() { - return actionStatus; - } - - public String getErrorMessage() { - return errorMessage; - } - - @Override + // Set defaults for everything + private String vduInstanceId = ""; + private String vduInstanceName = ""; + private VduStatus status = VduStatus.NOTFOUND; + private Map<String, Object> outputs = new HashMap<>(); + private Map<String, Object> inputs = new HashMap<>(); + private String lastAction; + private String actionStatus; + private String errorMessage; + + public VduInfo() {} + + // Add more constructors as appropriate + // + + public VduInfo(String id, Map<String, Object> outputs) { + this.vduInstanceId = id; + if (outputs != null) + this.outputs = outputs; + } + + public VduInfo(String id) { + this.vduInstanceId = id; + } + + public VduInfo(String id, VduStatus status) { + this.vduInstanceId = id; + this.status = status; + } + + public String getVnfInstanceId() { + return vduInstanceId; + } + + public void setVnfInstanceId(String id) { + this.vduInstanceId = id; + } + + public String getVnfInstanceName() { + return vduInstanceName; + } + + public void setVnfInstanceName(String name) { + this.vduInstanceName = name; + } + + public VduStatus getStatus() { + return status; + } + + public void setStatus(VduStatus status) { + this.status = status; + } + + public Map<String, Object> getOutputs() { + return outputs; + } + + public void setOutputs(Map<String, Object> outputs) { + this.outputs = outputs; + } + + public Map<String, Object> getInputs() { + return inputs; + } + + public void setInputs(Map<String, Object> inputs) { + this.inputs = inputs; + } + + public String getLastAction() { + return lastAction; + } + + public String getActionStatus() { + return actionStatus; + } + + public String getErrorMessage() { + return errorMessage; + } + + @Override public String toString() { - return "VduInfo {" + - "id='" + vduInstanceId + '\'' + - "name='" + vduInstanceName + '\'' + - ", inputs='" + inputs + '\'' + - ", outputs='" + outputs + '\'' + - ", lastAction='" + lastAction + '\'' + - ", status='" + status + '\'' + - ", errorMessage='" + errorMessage + '\'' + - '}'; + return "VduInfo {" + "id='" + vduInstanceId + '\'' + "name='" + vduInstanceName + '\'' + ", inputs='" + inputs + + '\'' + ", outputs='" + outputs + '\'' + ", lastAction='" + lastAction + '\'' + ", status='" + status + + '\'' + ", errorMessage='" + errorMessage + '\'' + '}'; } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduPlugin.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduPlugin.java index 871260a86d..1350694c0e 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduPlugin.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduPlugin.java @@ -20,126 +20,103 @@ package org.onap.so.vdu.utils; /** - * This interface defines a common API for template-based cloud deployments. - * The methods here should be adaptable for Openstack (Heat), Cloudify (TOSCA), - * Aria (TOSCA), Multi-VIM (TBD), and others (e.g. Azure Resource Manager). + * This interface defines a common API for template-based cloud deployments. The methods here should be adaptable for + * Openstack (Heat), Cloudify (TOSCA), Aria (TOSCA), Multi-VIM (TBD), and others (e.g. Azure Resource Manager). * - * The deployed instances are referred to here as Virtual Deployment Units (VDUs). - * The package of templates that define a give VDU is referred to as its blueprint. + * The deployed instances are referred to here as Virtual Deployment Units (VDUs). The package of templates that define + * a give VDU is referred to as its blueprint. * - * Template-based orchestrators all follow a similar template/blueprint model. - * - One main template that is the top level definition - * - Optional nested templates referenced/included by the main template - * - Optional files attached to the template package, typically containing - * configuration files, install scripts, orchestration scripts, etc. - * - * The main template also defines the required inputs for creating a new instance, - * and output values exposed by successfully deployed instances. Inputs and outputs - * may include simple or complex (JSON) data types. - * - * Each implementation of this interface is expected to understand the MSO CloudConfig - * to obtain the credentials for its sub-orchestrator and the targeted cloud. - * The sub-orchestrator may have different credentials from the cloud (e.g. an Aria - * instance in front of an Openstack cloud) or they may be the same (e.g. Heat) + * Template-based orchestrators all follow a similar template/blueprint model. - One main template that is the top level + * definition - Optional nested templates referenced/included by the main template - Optional files attached to the + * template package, typically containing configuration files, install scripts, orchestration scripts, etc. + * + * The main template also defines the required inputs for creating a new instance, and output values exposed by + * successfully deployed instances. Inputs and outputs may include simple or complex (JSON) data types. + * + * Each implementation of this interface is expected to understand the MSO CloudConfig to obtain the credentials for its + * sub-orchestrator and the targeted cloud. The sub-orchestrator may have different credentials from the cloud (e.g. an + * Aria instance in front of an Openstack cloud) or they may be the same (e.g. Heat) */ import java.util.Map; - import org.onap.so.openstack.exceptions.MsoException; public interface VduPlugin { /** - * The instantiateVdu interface deploys a new VDU instance from a blueprint package. - * The templates and files in the blueprint may be pre-installed where supported - * (e.g. in Cloudify or Aria), or may be passed in directly (e.g. for Heat). These - * files are expressed as byte arrays, though only text files are expected from ASDC. - * - * For some VIMs, this may be a single command (e.g. Heat -> create stack) or may - * require a series of API calls (e.g. Cloudify -> upload blueprint, create deployment, - * execute install workflow). These details are hidden within the implementation. - * The instantiation should be fully completed before returning. On failures, this - * method is expected to back out the attempt, leaving the cloud in its previous state. - * - * It is expected that parameters have been validated and contain at minimum the - * required parameters for the given template with no extra parameters. + * The instantiateVdu interface deploys a new VDU instance from a blueprint package. The templates and files in the + * blueprint may be pre-installed where supported (e.g. in Cloudify or Aria), or may be passed in directly (e.g. for + * Heat). These files are expressed as byte arrays, though only text files are expected from ASDC. + * + * For some VIMs, this may be a single command (e.g. Heat -> create stack) or may require a series of API calls + * (e.g. Cloudify -> upload blueprint, create deployment, execute install workflow). These details are hidden within + * the implementation. The instantiation should be fully completed before returning. On failures, this method is + * expected to back out the attempt, leaving the cloud in its previous state. + * + * It is expected that parameters have been validated and contain at minimum the required parameters for the given + * template with no extra parameters. * - * The VDU name supplied by the caller will be globally unique, and identify the artifact - * in A&AI. Inventory is managed by the higher levels invoking this function. + * The VDU name supplied by the caller will be globally unique, and identify the artifact in A&AI. Inventory is + * managed by the higher levels invoking this function. * - * @param cloudSiteId The target cloud for the VDU. Maps to a CloudConfig entry. - * @param tenantId The cloud tenant in which to deploy the VDU. The meaning may differ by - * cloud provider, but every cloud supports some sort of tenant partitioning. + * @param cloudSiteId The target cloud for the VDU. Maps to a CloudConfig entry. + * @param tenantId The cloud tenant in which to deploy the VDU. The meaning may differ by cloud provider, but every + * cloud supports some sort of tenant partitioning. * @param vduInstanceName A unique name for the VDU instance to create - * @param vduBlueprint Object containing the collection of templates and files that comprise - * the blueprint for this VDU. - * @param inputs A map of key/value inputs. Values may be strings, numbers, or JSON objects. - * @param environmentFile A file containing default parameter name/value pairs. This is - * primarily for Heat, though ASDC may create a similar file for other orchestrators. + * @param vduBlueprint Object containing the collection of templates and files that comprise the blueprint for this + * VDU. + * @param inputs A map of key/value inputs. Values may be strings, numbers, or JSON objects. + * @param environmentFile A file containing default parameter name/value pairs. This is primarily for Heat, though + * ASDC may create a similar file for other orchestrators. * @param timeoutMinutes Timeout after which the instantiation attempt will be cancelled - * @param suppressBackout Flag to preserve the deployment on install Failure. Should normally - * be False except in troubleshooting/debug cases + * @param suppressBackout Flag to preserve the deployment on install Failure. Should normally be False except in + * troubleshooting/debug cases * * @return A VduInfo object - * @throws MsoException Thrown if the sub-orchestrator API calls fail or if a timeout occurs. - * Various subclasses of MsoException may be thrown. + * @throws MsoException Thrown if the sub-orchestrator API calls fail or if a timeout occurs. Various subclasses of + * MsoException may be thrown. */ - public VduInfo instantiateVdu ( - String cloudSiteId, - String tenantId, - String vduInstanceName, - VduBlueprint vduBlueprint, - Map <String, ?> inputs, - String environmentFile, - int timeoutMinutes, - boolean suppressBackout) - throws MsoException; + public VduInfo instantiateVdu(String cloudSiteId, String tenantId, String vduInstanceName, + VduBlueprint vduBlueprint, Map<String, ?> inputs, String environmentFile, int timeoutMinutes, + boolean suppressBackout) throws MsoException; + - /** - * Query a deployed VDU instance. This call will return a VduInfo object, or null - * if the deployment does not exist. + * Query a deployed VDU instance. This call will return a VduInfo object, or null if the deployment does not exist. * - * Some VIM orchestrators identify deployment instances by string UUIDs, and others - * by integers. In the latter case, the ID will be passed in as a numeric string. + * Some VIM orchestrators identify deployment instances by string UUIDs, and others by integers. In the latter case, + * the ID will be passed in as a numeric string. * - * The returned VduInfo object contains the input and output parameter maps, - * as well as other properties of the deployment (name, status, last action, etc.). + * The returned VduInfo object contains the input and output parameter maps, as well as other properties of the + * deployment (name, status, last action, etc.). * * @param cloudSiteId The target cloud to query for the VDU. * @param tenantId The cloud tenant in which to query * @param vduInstanceId The ID of the deployment to query * * @return A VduInfo object - * @throws MsoException Thrown if the VIM/sub-orchestrator API calls fail. - * Various subclasses of MsoException may be thrown. + * @throws MsoException Thrown if the VIM/sub-orchestrator API calls fail. Various subclasses of MsoException may be + * thrown. */ - public VduInfo queryVdu ( - String cloudSiteId, - String tenantId, - String vduInstanceId) - throws MsoException; + public VduInfo queryVdu(String cloudSiteId, String tenantId, String vduInstanceId) throws MsoException; + - /** - * Delete a VDU instance by ID. If the VIM sub-orchestrator supports pre-installation - * of blueprints, the blueprint itself may remain installed. This is recommended, since - * other VDU instances may be using it. - * - * Some VIM orchestrators identify deployment instances by string UUIDs, and others - * by integers. In the latter case, the ID will be passed in as a numeric string. - * - * For some VIMs, deletion may be a single command (e.g. Heat -> delete stack) or a - * series of API calls (e.g. Cloudify -> execute uninstall workflow, delete deployment). - * These details are hidden within the implementation. The deletion should be fully - * completed before returning. - * - * The successful return is a VduInfo object which contains the state of the object just prior - * to deletion, with a status of DELETED. If the deployment was not found, the VduInfo object - * should be empty (with a status of NOTFOUND). There is no rollback from a successful deletion. - * - * A deletion failure will result in an undefined deployment state - the components may - * or may not have been all or partially uninstalled, so the resulting deployment must - * be considered invalid. + * Delete a VDU instance by ID. If the VIM sub-orchestrator supports pre-installation of blueprints, the blueprint + * itself may remain installed. This is recommended, since other VDU instances may be using it. + * + * Some VIM orchestrators identify deployment instances by string UUIDs, and others by integers. In the latter case, + * the ID will be passed in as a numeric string. + * + * For some VIMs, deletion may be a single command (e.g. Heat -> delete stack) or a series of API calls (e.g. + * Cloudify -> execute uninstall workflow, delete deployment). These details are hidden within the implementation. + * The deletion should be fully completed before returning. + * + * The successful return is a VduInfo object which contains the state of the object just prior to deletion, with a + * status of DELETED. If the deployment was not found, the VduInfo object should be empty (with a status of + * NOTFOUND). There is no rollback from a successful deletion. + * + * A deletion failure will result in an undefined deployment state - the components may or may not have been all or + * partially uninstalled, so the resulting deployment must be considered invalid. * * @param cloudSiteId The target cloud from which to delete the VDU. * @param tenantId The cloud tenant in which to delete the VDU. @@ -149,100 +126,81 @@ public interface VduPlugin { * * @return A VduInfo object, representing the state of the instance just prior to deletion. * - * @throws MsoException Thrown if the API calls fail or if a timeout occurs. - * Various subclasses of MsoException may be thrown. + * @throws MsoException Thrown if the API calls fail or if a timeout occurs. Various subclasses of MsoException may + * be thrown. */ - public VduInfo deleteVdu ( - String cloudSiteId, - String tenantId, - String vduInstanceId, - int timeoutMinutes, - boolean keepBlueprintLoaded) - throws MsoException; + public VduInfo deleteVdu(String cloudSiteId, String tenantId, String vduInstanceId, int timeoutMinutes, + boolean keepBlueprintLoaded) throws MsoException; + - /** - * The updateVdu interface attempts to update a VDU in-place, using either new inputs or - * a new model definition (i.e. updated templates/blueprints). This depends on the - * capabilities of the targeted sub-orchestrator, as not all implementations are expected - * to support this ability. It is primary included initially only for Heat. - * - * It is expected that parameters have been validated and contain at minimum the required - * parameters for the given template with no extra parameters. The VDU instance name cannot - * be updated. - * - * The update should be fully completed before returning. The successful return is a - * VduInfo object containing the updated VDU state. - * - * An update failure will result in an undefined deployment state - the components may - * or may not have been all or partially modified, deleted, recreated, etc. So the resulting - * VDU must be considered invalid. - * - * @param cloudSiteId The target cloud for the VDU. Maps to a CloudConfig entry. - * @param tenantId The cloud tenant in which to deploy the VDU. The meaning may differ by - * cloud provider, but every cloud supports some sort of tenant partitioning. + * The updateVdu interface attempts to update a VDU in-place, using either new inputs or a new model definition + * (i.e. updated templates/blueprints). This depends on the capabilities of the targeted sub-orchestrator, as not + * all implementations are expected to support this ability. It is primary included initially only for Heat. + * + * It is expected that parameters have been validated and contain at minimum the required parameters for the given + * template with no extra parameters. The VDU instance name cannot be updated. + * + * The update should be fully completed before returning. The successful return is a VduInfo object containing the + * updated VDU state. + * + * An update failure will result in an undefined deployment state - the components may or may not have been all or + * partially modified, deleted, recreated, etc. So the resulting VDU must be considered invalid. + * + * @param cloudSiteId The target cloud for the VDU. Maps to a CloudConfig entry. + * @param tenantId The cloud tenant in which to deploy the VDU. The meaning may differ by cloud provider, but every + * cloud supports some sort of tenant partitioning. * @param vduInstanceId The unique ID for the VDU instance to update. - * @param vduBlueprint Object containing the collection of templates and files that comprise - * the blueprint for this VDU. - * @param inputs A map of key/value inputs. Values may be strings, numbers, or JSON objects. - * @param environmentFile A file containing default parameter name/value pairs. This is - * primarily for Heat, though ASDC may create a similar file for other orchestrators. + * @param vduBlueprint Object containing the collection of templates and files that comprise the blueprint for this + * VDU. + * @param inputs A map of key/value inputs. Values may be strings, numbers, or JSON objects. + * @param environmentFile A file containing default parameter name/value pairs. This is primarily for Heat, though + * ASDC may create a similar file for other orchestrators. * @param timeoutMinutes Timeout after which the instantiation attempt will be cancelled * * @return A VduInfo object - * @throws MsoException Thrown if the sub-orchestrator API calls fail or if a timeout occurs. - * Various subclasses of MsoException may be thrown. + * @throws MsoException Thrown if the sub-orchestrator API calls fail or if a timeout occurs. Various subclasses of + * MsoException may be thrown. */ - public VduInfo updateVdu ( - String cloudSiteId, - String tenantId, - String vduInstanceId, - VduBlueprint vduBlueprint, - Map <String, ?> inputs, - String environmentFile, - int timeoutMinutes) - throws MsoException; + public VduInfo updateVdu(String cloudSiteId, String tenantId, String vduInstanceId, VduBlueprint vduBlueprint, + Map<String, ?> inputs, String environmentFile, int timeoutMinutes) throws MsoException; + - /** - * Check if a blueprint package has been installed in the sub-orchestrator and available - * for use at a targeted cloud site. If the specific sub-orchestrator does not support - * pre-installation, then those implementations should always return False. + * Check if a blueprint package has been installed in the sub-orchestrator and available for use at a targeted cloud + * site. If the specific sub-orchestrator does not support pre-installation, then those implementations should + * always return False. * * @param cloudSiteId The cloud site where the blueprint is needed * @param vduModelId Unique ID of the VDU model to query * * @throws MsoException Thrown if the API call fails. */ - public boolean isBlueprintLoaded (String cloudSiteId, String vduModelId) - throws MsoException; + public boolean isBlueprintLoaded(String cloudSiteId, String vduModelId) throws MsoException; + - /** - * Install a blueprint package to the target sub-orchestrator for a cloud site. - * The blueprints 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. + * Install a blueprint package to the target sub-orchestrator for a cloud site. The blueprints 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. * * @param cloudSiteId The cloud site where the blueprint is needed - * @param vduBlueprint Object containing the collection of templates and files that comprise - * the blueprint for this VDU. + * @param vduBlueprint Object containing the collection of templates and files that comprise the blueprint for this + * VDU. * @param failIfExists Flag to return an error if blueprint already exists * * @throws MsoException Thrown if the API call fails. */ - public void uploadBlueprint (String cloudSiteId, - VduBlueprint vduBlueprint, - boolean failIfExists) - throws MsoException; + public void uploadBlueprint(String cloudSiteId, VduBlueprint vduBlueprint, boolean failIfExists) + throws MsoException; /** - * Indicator that this VIM sub-orchestrator implementation supports independent upload - * of blueprint packages. Each implementation should return a constant value. + * Indicator that this VIM sub-orchestrator implementation supports independent upload of blueprint packages. Each + * implementation should return a constant value. * * @returns True if the sub-orchestrator supports blueprint pre-installation (upload). */ - public boolean blueprintUploadSupported (); + public boolean blueprintUploadSupported(); } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduStatus.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduStatus.java index 1412b02da0..0c4b9e01b9 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduStatus.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/vdu/utils/VduStatus.java @@ -25,13 +25,8 @@ package org.onap.so.vdu.utils; * Enum status values to capture the state of a generic (cloud-agnostic) VDU. */ public enum VduStatus { - NOTFOUND, - INSTANTIATING, - INSTANTIATED, - DELETING, - DELETED, // Note - only returned in success response to deleteVdu call. - UPDATING, - FAILED, - UNKNOWN + NOTFOUND, INSTANTIATING, INSTANTIATED, DELETING, DELETED, // Note - only returned in success response to deleteVdu + // call. + UPDATING, FAILED, UNKNOWN } |