diff options
28 files changed, 8 insertions, 8649 deletions
diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/QueryVolumeGroupResponse.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/QueryVolumeGroupResponse.java deleted file mode 100644 index a95df93a27..0000000000 --- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/QueryVolumeGroupResponse.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.vnfrest; - - -import java.util.Map; -import javax.xml.bind.annotation.XmlRootElement; -import org.onap.so.openstack.beans.VnfStatus; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@XmlRootElement(name = "queryVolumeGroupResponse") -public class QueryVolumeGroupResponse { - private static final Logger logger = LoggerFactory.getLogger(QueryVolumeGroupResponse.class); - private String volumeGroupId; - private String volumeGroupStackId; - private VnfStatus volumeGroupStatus; - private Map<String, String> volumeGroupOutputs; - - public QueryVolumeGroupResponse() {} - - public QueryVolumeGroupResponse(String volumeGroupId, String volumeGroupStackId, VnfStatus volumeGroupStatus, - Map<String, String> volumeGroupOutputs) { - super(); - this.volumeGroupId = volumeGroupId; - this.volumeGroupStackId = volumeGroupStackId; - this.volumeGroupStatus = volumeGroupStatus; - this.volumeGroupOutputs = volumeGroupOutputs; - } - - public String getVolumeGroupId() { - return volumeGroupId; - } - - public void setVolumeGroupId(String volumeGroupId) { - this.volumeGroupId = volumeGroupId; - } - - public String getVolumeGroupStackId() { - return volumeGroupStackId; - } - - public void setVolumeGroupStackId(String volumeGroupStackId) { - this.volumeGroupStackId = volumeGroupStackId; - } - - public VnfStatus getVolumeGroupStatus() { - return volumeGroupStatus; - } - - public void setVolumeGroupStatus(VnfStatus volumeGroupStatus) { - this.volumeGroupStatus = volumeGroupStatus; - } - - public Map<String, String> getVolumeGroupOutputs() { - return volumeGroupOutputs; - } - - public void setVolumeGroupOutputs(Map<String, String> volumeGroupOutputs) { - this.volumeGroupOutputs = volumeGroupOutputs; - } - - public String toJsonString() { - String jsonString = null; - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.enable(SerializationFeature.WRAP_ROOT_VALUE); - jsonString = mapper.writeValueAsString(this); - } catch (Exception e) { - logger.debug("Exception :", e); - } - return jsonString; - } -} 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 9badd795eb..8f815f1827 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 @@ -40,11 +40,6 @@ import org.onap.so.adapters.tenant.MsoTenantAdapterImpl; import org.onap.so.adapters.tenant.TenantAdapterRest; import org.onap.so.adapters.vnf.MsoVnfAdapterAsyncImpl; import org.onap.so.adapters.vnf.MsoVnfAdapterImpl; -import org.onap.so.adapters.vnf.MsoVnfCloudifyAdapterImpl; -import org.onap.so.adapters.vnf.VnfAdapterRest; -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; @@ -64,14 +59,6 @@ public class CXFConfiguration { @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; @@ -82,8 +69,6 @@ public class CXFConfiguration { @Autowired private MsoVnfAdapterAsyncImpl vnfAdapterAsyncImpl; @Autowired - private MsoVnfCloudifyAdapterImpl vnfCloudifyAdapterImpl; - @Autowired private CloudRegionRestV1 cloudRegionRestV1; @Autowired private JettisonStyleMapperProvider jettisonStyleObjectMapper; @@ -169,24 +154,12 @@ public class CXFConfiguration { return endpoint; } - @Bean - public Endpoint vnfCloudAdapterEndpoint() { - EndpointImpl endpoint = new EndpointImpl(springBus(), vnfCloudifyAdapterImpl); - endpoint.publish("/VnfCloudifyAdapterImpl"); - endpoint.setWsdlLocation("VnfCloudifyAdapterImpl.wsdl"); - endpoint.getInInterceptors().add(new SOAPLoggingInInterceptor()); - endpoint.getOutInterceptors().add(new SOAPLoggingOutInterceptor()); - endpoint.getOutFaultInterceptors().add(new SOAPLoggingOutInterceptor()); - return endpoint; - } - // Uses Jettson Style marshalling semantics @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)); endpoint.setAddress("/rest"); endpoint.setFeatures(Arrays.asList(createSwaggerFeature(), new LoggingFeature())); endpoint.setProviders(Arrays.asList(new JacksonJsonProvider(jettisonStyleObjectMapper.getMapper()), 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 deleted file mode 100644 index 0074dca03c..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapter.java +++ /dev/null @@ -1,150 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.vnf; - - -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.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; -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; - - @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 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 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 = "vnfId") @XmlElement(required = true) String vnfId, - @WebParam(name = "vfModuleId") @XmlElement(required = true) String vfModuleId, - @WebParam(name = "modelCustomizationUuid") @XmlElement(required = false) String modelCustomizationUuid, - @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 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 13ca78a1f5..4b9c36b7b7 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 @@ -29,7 +29,6 @@ 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; /** @@ -37,6 +36,7 @@ import org.onap.so.openstack.mappers.MapAdapter; * are documented elsewhere (by the client service WSDL). * */ +@Deprecated @WebService(name = "VnfAdapterAsync", targetNamespace = "http://org.onap.so/vnfA") public interface MsoVnfAdapterAsync { /** @@ -61,31 +61,6 @@ public interface MsoVnfAdapterAsync { @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 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, @@ -94,12 +69,6 @@ public interface MsoVnfAdapterAsync { @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 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 68d1bebc51..3bea44b884 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 @@ -38,8 +38,6 @@ import javax.xml.ws.BindingProvider; import javax.xml.ws.Holder; import javax.xml.ws.handler.MessageContext; import org.onap.so.adapters.vnf.async.client.CreateVnfNotification; -import org.onap.so.adapters.vnf.async.client.QueryVnfNotification; -import org.onap.so.adapters.vnf.async.client.UpdateVnfNotification; import org.onap.so.adapters.vnf.async.client.VnfAdapterNotify; import org.onap.so.adapters.vnf.async.client.VnfAdapterNotify_Service; import org.onap.so.adapters.vnf.exceptions.VnfException; @@ -48,7 +46,6 @@ import org.onap.logging.filter.base.ErrorCode; import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.VnfRollback; -import org.onap.so.openstack.beans.VnfStatus; import org.onap.so.utils.CryptoUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -64,9 +61,7 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { private static final Logger logger = LoggerFactory.getLogger(MsoVnfAdapterAsyncImpl.class); private static final String BPEL_AUTH_PROP = "org.onap.so.adapters.vnf.bpelauth"; - private static final String ENCRYPTION_KEY_PROP = "org.onap.so.adapters.network.encryptionKey"; - private static final String UPDATE_VNFA = "{} UpdateVnfA"; - private static final String EXCEPTION_UPDATEVNF_NOTIFICATION = "{} {} Exception sending updateVnf notification "; + private static final String ENCRYPTION_KEY_PROP = "mso.msoKey"; @Autowired private Environment environment; @@ -122,15 +117,13 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { 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<>(); try { - vnfAdapter.createVnf(cloudSiteId, cloudOwner, tenantId, vnfType, vnfVersion, vnfName, requestType, + vnfImpl.createVnf(cloudSiteId, cloudOwner, tenantId, vnfType, vnfVersion, vnfName, requestType, volumeGroupHeatStackId, inputs, failIfExists, backout, enableBridge, msoRequest, vnfId, outputs, vnfRollback); } catch (VnfException e) { @@ -171,140 +164,6 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { 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) { - - logger.info(UPDATE_VNFA, MessageEnum.RA_ASYNC_UPDATE_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<>(); - - try { - vnfAdapter.updateVnf(cloudSiteId, cloudOwner, tenantId, vnfType, vnfVersion, vnfName, requestType, - volumeGroupHeatStackId, inputs, msoRequest, outputs, vnfRollback); - } catch (VnfException e) { - logger.error(EXCEPTION_UPDATEVNF_NOTIFICATION, MessageEnum.RA_UPDATE_VNF_ERR, - ErrorCode.BusinessProcessError.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()); - } catch (Exception e1) { - logger.error("{} {} Exception - fault info ", MessageEnum.RA_FAULT_INFO_EXC, - ErrorCode.BusinessProcessError.getValue(), e1); - } - // Build and send Asynchronous error response - try { - VnfAdapterNotify notifyPort = getNotifyEP(notificationUrl); - notifyPort.updateVnfNotification(messageId, false, exCat, eMsg, null, null); - } catch (Exception e1) { - logger.error(EXCEPTION_UPDATEVNF_NOTIFICATION, MessageEnum.RA_SEND_VNF_NOTIF_ERR, - ErrorCode.BusinessProcessError.getValue(), e1); - } - logger.info(UPDATE_VNFA, MessageEnum.RA_ASYNC_UPDATE_VNF_COMPLETE); - return; - } - 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)); - } catch (Exception e) { - logger.error(EXCEPTION_UPDATEVNF_NOTIFICATION, MessageEnum.RA_SEND_VNF_NOTIF_ERR, - ErrorCode.BusinessProcessError.getValue(), e); - } - logger.info(UPDATE_VNFA, 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. - * - * 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 - * @param tenantId Openstack tenant identifier - * @param vnfName VNF Name or Openstack ID - * @param msoRequest Request tracking information for logs - * @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) { - - logger.info(LoggingAnchor.ONE, MessageEnum.RA_ASYNC_QUERY_VNF); - - // Use the synchronous method to perform the actual query - 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<>(); - - try { - 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.BusinessProcessError.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()); - } catch (Exception e1) { - logger.error("{} {} Exception - fault info ", MessageEnum.RA_FAULT_INFO_EXC, - ErrorCode.BusinessProcessError.getValue(), e1); - } - // Build and send Asynchronous error response - try { - 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.BusinessProcessError.getValue(), e1); - } - logger.info("{} queryVnfA", MessageEnum.RA_ASYNC_QUERY_VNF_COMPLETE); - return; - } - - if (!vnfExists.value) { - 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)); - } catch (Exception e) { - logger.error("{} {} Exception sending queryVnf notification ", MessageEnum.RA_SEND_VNF_NOTIF_ERR, - ErrorCode.BusinessProcessError.getValue(), e); - } - - logger.info("{} queryVnfA", MessageEnum.RA_ASYNC_QUERY_VNF_COMPLETE); - return; - } - /** * This is the Asynchronous "Delete VNF" web service implementation. It will delete a VNF by name or ID in the * specified cloud and tenant. @@ -324,11 +183,8 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { logger.info(LoggingAnchor.ONE, MessageEnum.RA_ASYNC_DELETE_VNF); - // Use the synchronous method to perform the actual delete - MsoVnfAdapter vnfAdapter = vnfImpl; - try { - vnfAdapter.deleteVnf(cloudSiteId, cloudOwner, tenantId, vnfName, msoRequest); + vnfImpl.deleteVnf(cloudSiteId, cloudOwner, tenantId, vnfName, msoRequest); } catch (VnfException e) { logger.error("{} {} Exception sending deleteVnfA notification ", MessageEnum.RA_DELETE_VNF_ERR, ErrorCode.BusinessProcessError.getValue(), e); @@ -369,65 +225,6 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { 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 rollbackVnf operation - * to undo the creation. - */ - @Override - 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); - return; - } - - logger.info("{} rollbackVnfA", MessageEnum.RA_ASYNC_ROLLBACK_VNF); - - // Use the synchronous method to perform the actual rollback - MsoVnfAdapter vnfAdapter = vnfImpl; - - try { - vnfAdapter.rollbackVnf(rollback); - } catch (VnfException e) { - logger.error("{} {} Exception sending rollbackVnfA notification ", MessageEnum.RA_ROLLBACK_VNF_ERR, - ErrorCode.BusinessProcessError.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()); - } catch (Exception e1) { - logger.error("{} {} Exception - fault info ", MessageEnum.RA_FAULT_INFO_EXC, - ErrorCode.BusinessProcessError.getValue(), e1); - } - // Build and send Asynchronous error response - try { - 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.BusinessProcessError.getValue(), e1); - } - logger.info("{} rollbackVnfA", MessageEnum.RA_ASYNC_ROLLBACK_VNF_COMPLETE); - return; - } - - logger.debug("Async Rollback VNF:" + rollback.getVnfId()); - // Build and send Asynchronous response - try { - 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.BusinessProcessError.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(); @@ -471,47 +268,6 @@ public class MsoVnfAdapterAsyncImpl implements MsoVnfAdapterAsync { return outputs; } - private UpdateVnfNotification.Outputs copyUpdateOutputs(Holder<Map<String, String>> hMap) { - - UpdateVnfNotification.Outputs outputs = new UpdateVnfNotification.Outputs(); - - if (hMap != null && hMap.value != null) { - Map<String, String> sMap; - 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); - } - } - return outputs; - } - - private QueryVnfNotification.Outputs copyQueryOutputs(Holder<Map<String, String>> hMap) { - - QueryVnfNotification.Outputs outputs = new QueryVnfNotification.Outputs(); - - if (hMap != null && hMap.value != null) { - Map<String, String> sMap; - sMap = hMap.value; - - 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); - } - } - return outputs; - } - private VnfAdapterNotify getNotifyEP(String notificationUrl) { URL warWsdlLoc = null; 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 4617299f48..a58c0c10c5 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 @@ -30,7 +30,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; -import javax.jws.WebService; import javax.xml.ws.Holder; import org.apache.commons.collections.CollectionUtils; import org.onap.logging.filter.base.ErrorCode; @@ -59,7 +58,6 @@ 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; -import org.onap.so.openstack.beans.VnfStatus; import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; import org.onap.so.openstack.exceptions.MsoException; import org.onap.so.openstack.exceptions.MsoExceptionCategory; @@ -81,11 +79,9 @@ 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") @Component @Transactional -public class MsoVnfAdapterImpl implements MsoVnfAdapter { +public class MsoVnfAdapterImpl { @Autowired private CloudConfig cloudConfig; @@ -96,7 +92,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { private static final Logger logger = LoggerFactory.getLogger(MsoVnfAdapterImpl.class); - private static final String VNF_ADAPTER_SERVICE_NAME = "MSO-BPMN:MSO-VnfAdapter."; 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 ObjectMapper JSON_MAPPER = new ObjectMapper(); @@ -139,7 +134,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { /** * 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"); } @@ -175,7 +169,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { * @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, @@ -218,75 +211,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // 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"); - } - - /** - * 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). - * - * @param cloudSiteId CLLI code of the cloud site in which to query - * @param tenantId Openstack tenant identifier - * @param vnfName VNF Name or Openstack ID - * @param msoRequest Request tracking information for logs - * @param vnfExists Flag reporting the result of the query - * @param vnfId Holder for output VNF Openstack ID - * @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 { - - logger.debug("Querying VNF {} in {}/{}", vnfName, cloudSiteId, tenantId); - - // Will capture execution time for metrics - - StackInfo heatStack; - try { - heatStack = msoHeatUtils.queryStack(cloudSiteId, cloudOwner, tenantId, vnfName); - } catch (MsoException me) { - 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; - logger.error(LoggingAnchor.EIGHT, MessageEnum.RA_QUERY_VNF_ERR.toString(), vnfName, cloudSiteId, tenantId, - OPENSTACK, "QueryVNF", ErrorCode.DataError.getValue(), "Exception - " + QUERY_STACK, me); - logger.debug(error); - throw new VnfException(me); - } - - // Populate the outputs based on the returned Stack information - // - 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); - } else { - vnfExists.value = Boolean.TRUE; - status.value = stackStatusToVnfStatus(heatStack.getStatus()); - vnfId.value = heatStack.getCanonicalName(); - outputs.value = copyStringOutputs(heatStack.getOutputs()); - - 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. @@ -299,7 +223,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { * @param vnfName VNF Name or Openstack ID * @param msoRequest Request tracking information for logs */ - @Override public void deleteVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, MsoRequest msoRequest) throws VnfException { @@ -368,7 +291,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { * 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 { // rollback may be null (e.g. if stack already existed when Create was called) if (rollback == null) { @@ -404,19 +326,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { return; } - private VnfStatus stackStatusToVnfStatus(HeatStatus stackStatus) { - switch (stackStatus) { - case CREATED: - return VnfStatus.ACTIVE; - case UPDATED: - return VnfStatus.ACTIVE; - case FAILED: - return VnfStatus.FAILED; - default: - return VnfStatus.UNKNOWN; - } - } - private Map<String, String> copyStringOutputs(Map<String, Object> stackOutputs) { Map<String, String> stringOutputs = new HashMap<>(); for (Map.Entry<String, Object> entry : stackOutputs.entrySet()) { @@ -570,7 +479,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { return stringMap; } - @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, @@ -1138,7 +1046,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } } - @Override public void deleteVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, String vnfId, String vfModuleId, String modelCustomizationUuid, MsoRequest msoRequest, Holder<Map<String, String>> outputs) throws VnfException { @@ -1212,7 +1119,6 @@ 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, @@ -1220,8 +1126,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { 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"); @@ -1334,7 +1238,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // 1604 Cinder Volume support - handle a nestedStackId if sent (volumeGroupHeatStackId): StackInfo nestedHeatStack = null; - Map<String, Object> nestedVolumeOutputs = null; if (nestedStackId != null) { try { logger.debug("Querying for nestedStackId = {}", nestedStackId); @@ -1360,13 +1263,11 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { throw new VnfException(error, MsoExceptionCategory.USERDATA); } else { logger.debug("Found nested heat stack - copying values to inputs *later*"); - nestedVolumeOutputs = nestedHeatStack.getOutputs(); msoHeatUtils.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) { try { logger.debug("Querying for nestedBaseStackId = {}", nestedBaseStackId); @@ -1392,7 +1293,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { throw new VnfException(error, MsoExceptionCategory.USERDATA); } else { logger.debug("Found nested base heat stack - copying values to inputs *later*"); - baseStackOutputs = nestedBaseHeatStack.getOutputs(); msoHeatUtils.copyStringOutputsToInputs(inputs, nestedBaseHeatStack.getOutputs(), false); } } @@ -1832,56 +1732,4 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { 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; - } - - /* - * 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<>(); - 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 : nestedTemplates.keySet()) { - files.put(keyString, nestedTemplates.get(keyString)); - } - } else { - // Handle if we only have one or neither: - if (haveGetFiles) { - files = getFiles; - } - if (haveNestedTemplates) { - files = nestedTemplates; - } - } - return files; - } } 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 deleted file mode 100644 index ba837a9718..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImpl.java +++ /dev/null @@ -1,1142 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (C) 2018 IBM. - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.vnf; - - -import java.util.ArrayList; -import java.util.HashMap; -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.logger.LoggingAnchor; -import com.woorea.openstack.heat.Heat; -import org.onap.so.adapters.vnf.exceptions.VnfAlreadyExists; -import org.onap.so.adapters.vnf.exceptions.VnfException; -import org.onap.so.cloud.CloudConfig; -import org.onap.so.db.catalog.beans.CloudSite; -import org.onap.so.cloudify.beans.DeploymentInfo; -import org.onap.so.cloudify.beans.DeploymentStatus; -import org.onap.so.cloudify.exceptions.MsoCloudifyManagerNotFound; -import org.onap.so.cloudify.utils.MsoCloudifyUtils; -import org.onap.so.db.catalog.beans.HeatEnvironment; -import org.onap.so.db.catalog.beans.HeatFiles; -import org.onap.so.db.catalog.beans.HeatTemplate; -import org.onap.so.db.catalog.beans.HeatTemplateParam; -import org.onap.so.db.catalog.beans.VfModule; -import org.onap.so.db.catalog.beans.VfModuleCustomization; -import org.onap.so.db.catalog.beans.VnfResource; -import org.onap.so.db.catalog.data.repository.VFModuleCustomizationRepository; -import org.onap.so.db.catalog.utils.MavenLikeVersioning; -import org.onap.so.entity.MsoRequest; -import org.onap.logging.filter.base.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; -import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; -import org.onap.so.openstack.exceptions.MsoException; -import org.onap.so.openstack.exceptions.MsoExceptionCategory; -import org.onap.so.openstack.utils.MsoHeatEnvironmentEntry; -import org.onap.so.openstack.utils.MsoHeatEnvironmentParameter; -import org.onap.so.openstack.utils.MsoKeystoneUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.transaction.annotation.Transactional; - -@Component -@Transactional -@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); - - private static final String CHECK_REQD_PARAMS = "org.onap.so.adapters.vnf.checkRequiredParameters"; - private static final String CLOUDIFY = "Cloudify"; - - private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); - private static final String BRACKETS = LoggingAnchor.NINE; - private static final String OPENSTACK = "OpenStack"; - - @Autowired - protected CloudConfig cloudConfig; - - @Autowired - private VFModuleCustomizationRepository vfModuleCustomRepo; - - @Autowired - private Environment environment; - - @Autowired - protected MsoKeystoneUtils keystoneUtils; - - @Autowired - protected MsoCloudifyUtils cloudifyUtils; - - /** - * DO NOT use that constructor to instantiate this class, the msoPropertiesfactory will be NULL. - * - * @see MsoVnfCloudifyAdapterImpl#MsoVnfAdapterImpl(MsoPropertiesFactory, CloudConfigFactory) - */ - public MsoVnfCloudifyAdapterImpl() { - - } - - /** - * 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 Cloudify Adapter"); - } - - /** - * 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. - 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. - * - */ - @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); - } - - /** - * This is the "Query VNF" web service implementation. - * - * 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). - * - * 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 - * @param tenantId Openstack tenant identifier - ignored for Cloudify - * @param vnfName VNF Name (should match a deployment ID) - * @param msoRequest Request tracking information for logs - * @param vnfExists Flag reporting the result of the query - * @param vnfId Holder for output VNF ID - * @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); - - 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. - logger.debug("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(BRACKETS, 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; - status.value = deploymentStatusToVnfStatus(deployment); - vnfId.value = deployment.getId(); - outputs.value = copyStringOutputs(deployment.getOutputs()); - - logger.debug("VNF {} found in Cloudify, ID = {}", vnfName, 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", vnfName); - } - } - - - /** - * 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); - } - - /** - * 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. - */ - @Override - public void rollbackVnf(VnfRollback rollback) throws VnfException { - // rollback may be null (e.g. if stack already existed when Create was called) - if (rollback == null) { - logger.info(LoggingAnchor.THREE, MessageEnum.RA_ROLLBACK_NULL.toString(), OPENSTACK, "rollbackVnf"); - return; - } - - // Don't rollback if nothing was done originally - if (!rollback.getVnfCreated()) { - return; - } - - // Get the elements of the VnfRollback object for easier access - String cloudSiteId = rollback.getCloudSiteId(); - String cloudOwner = rollback.getCloudOwner(); - String tenantId = rollback.getTenantId(); - String vfModuleId = rollback.getVfModuleStackId(); - - logger.debug("Rolling Back VF Module {} in {}", vfModuleId, cloudOwner + "/" + cloudSiteId + "/" + tenantId); - - 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. - 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); - - // 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(BRACKETS, 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); - } - } - - - 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<>(); - for (Map.Entry<String, Object> entry : stackOutputs.entrySet()) { - if (entry.getValue() instanceof String) { - stringOutputs.put(entry.getKey(), (String) entry.getValue()); - } else if (entry.getValue() instanceof Integer) { - try { - String str = "" + entry.getValue(); - stringOutputs.put(entry.getKey(), str); - } catch (Exception e) { - logger.error("Unable to add " + entry.getKey() + " to outputs", e); - } - } else if (entry.getValue() instanceof JsonNode) { - try { - String str = this.convertNode((JsonNode) entry.getValue()); - stringOutputs.put(entry.getKey(), str); - } catch (Exception e) { - logger.error("Unable to add " + entry.getKey() + " to outputs - exception converting JsonNode", e); - } - } else if (entry.getValue() instanceof java.util.LinkedHashMap) { - try { - String str = JSON_MAPPER.writeValueAsString(entry.getValue()); - stringOutputs.put(entry.getKey(), str); - } catch (Exception e) { - logger.error("Unable to add " + entry.getKey() + " to outputs - exception converting LinkedHashMap", - e); - } - } else { - try { - String str = entry.getValue().toString(); - stringOutputs.put(entry.getKey(), str); - } catch (Exception e) { - logger.error("Unable to add " + entry.getKey() + " to outputs - unable to call .toString() ", e); - } - } - } - return stringOutputs; - } - - - 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 (Map.Entry<String, Object> entry : inputs.entrySet()) { - String outputString; - try { - outputString = entry.getValue().toString(); - } catch (Exception e) { - outputString = "Unable to call toString() on the value for " + entry.getKey(); - } - sb.append("\t\nitem " + i++ + ": '" + entry.getKey() + "'='" + outputString + "'"); - } - } - logger.debug(sb.toString()); - } - - 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 (Map.Entry<String, Object> entry : inputs.entrySet()) { - sb.append("\titem " + i++ + ": " + entry.getKey() + "=" + entry.getValue()); - } - } - logger.debug(sb.toString()); - } - - private String convertNode(final JsonNode node) { - try { - final Object obj = JSON_MAPPER.treeToValue(node, Object.class); - final String json = JSON_MAPPER.writeValueAsString(obj); - return json; - } catch (JsonParseException jpe) { - logger.error("Error converting json to string ", jpe); - } catch (Exception e) { - logger.error("Error converting json to string ", e); - } - return "[Error converting json to string]"; - } - - private Map<String, String> convertMapStringObjectToStringString(Map<String, Object> objectMap) { - if (objectMap == null) { - return null; - } - Map<String, String> stringMap = new HashMap<>(); - for (Map.Entry<String, Object> entry : objectMap.entrySet()) { - if (!stringMap.containsKey(entry.getKey())) { - Object obj = entry.getValue(); - if (obj instanceof String) { - stringMap.put(entry.getKey(), (String) entry.getValue()); - } 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(entry.getKey(), str); - } catch (Exception e) { - logger.error("DANGER WILL ROBINSON: unable to convert value for JsonNode " + entry.getKey(), 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"); - try { - String str = JSON_MAPPER.writeValueAsString(obj); - stringMap.put(entry.getKey(), str); - } catch (Exception e) { - logger.error( - "DANGER WILL ROBINSON: unable to convert value for LinkedHashMap " + entry.getKey(), e); - } - } else if (obj instanceof Integer) { - try { - String str = "" + obj; - stringMap.put(entry.getKey(), str); - } catch (Exception e) { - logger.error("DANGER WILL ROBINSON: unable to convert value for Integer " + entry.getKey(), e); - } - } else { - try { - String str = obj.toString(); - stringMap.put(entry.getKey(), str); - } catch (Exception e) { - logger.error("DANGER WILL ROBINSON: unable to convert value " + entry.getKey(), e); - } - } - } - } - - return stringMap; - } - - /** - * 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. - * - * 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. - * - * 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 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 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) - * @param msoRequest Request tracking information for logs - * @param vnfId Holder for output VNF Cloudify Deployment ID - * @param outputs Holder for Map of VNF outputs from Deployment (assigned IPs, etc) - * @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 { - - // 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(LoggingAnchor.FIVE, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), - "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 = ""; - - if ("".equals(volumeGroupId) || "null".equals(volumeGroupId)) - volumeGroupId = null; - - if ("".equals(baseVfModuleId) || "null".equals(baseVfModuleId)) - baseVfModuleId = null; - - if (inputs == null) { - // Create an empty set of inputs - inputs = new HashMap<>(); - logger.debug("inputs == null - setting to empty"); - } else { - this.sendMapToDebug(inputs); - } - - // Check if this is for a "Volume" module - boolean isVolumeRequest = false; - if (requestType.startsWith("VOLUME")) { - isVolumeRequest = true; - } - - logger.debug("requestType = " + requestType + ", volumeGroupStackId = " + volumeGroupId + ", baseStackId = " - + baseVfModuleId); - - // Build a default rollback object (no actions performed) - VnfRollback vfRollback = new VnfRollback(); - vfRollback.setCloudSiteId(cloudSiteId); - vfRollback.setCloudOwner(cloudOwner); - vfRollback.setTenantId(tenantId); - vfRollback.setMsoRequest(msoRequest); - vfRollback.setRequestType(requestType); - 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 - - // Get the VNF/VF Module definition from the Catalog DB first. - // There are three relevant records: VfModule, VfModuleCustomization, VnfResource - - VfModule vf = 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; - logger.debug(error); - logger.error(LoggingAnchor.FIVE, 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) { - - logger.error("unhandled exception in create VF - [Query]", e); - 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); - if (!cloudSiteOp.isPresent()) { - 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(LoggingAnchor.FIVE, MessageEnum.RA_CONFIG_EXC.toString(), error, OPENSTACK, - ErrorCode.BusinessProcessError.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. - - try { - 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; - logger.error(LoggingAnchor.EIGHT, MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudSiteId, - tenantId, CLOUDIFY, "queryDeployment", ErrorCode.DataError.getValue(), - "Exception - queryDeployment", me); - logger.debug(error); - - // Convert to a generic VnfException - 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(BRACKETS, 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()); - 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(BRACKETS, 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(BRACKETS, 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(BRACKETS, 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(BRACKETS, 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()); - } - } - - - // Collect outputs from Base Modules and Volume Modules - Map<String, Object> baseModuleOutputs = null; - Map<String, Object> volumeGroupOutputs = null; - - // If a Volume Group was provided, query its outputs for inclusion in Module input parameters - if (volumeGroupId != null) { - DeploymentInfo volumeDeployment = null; - try { - 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; - logger.error(BRACKETS, MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId, 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); - } - - 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(BRACKETS, MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId, cloudSiteId, tenantId, - error, CLOUDIFY, "queryDeployment(volume)", ErrorCode.BusinessProcessError.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 - - if (vf.getIsBase()) { - logger.debug("This is a BASE Module request"); - vfRollback.setIsBase(true); - } else { - logger.debug("This is an Add-On Module request"); - - // 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"); - } - - if (baseVfModuleId != null) { - 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(BRACKETS, 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"; - logger.error(BRACKETS, MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId, cloudSiteId, - tenantId, error, CLOUDIFY, "queryDeployment(Base)", - ErrorCode.BusinessProcessError.getValue(), - "Create VFModule: Base " + "Module DOES NOT EXIST"); - logger.debug(error); - throw new VnfException(error, MsoExceptionCategory.USERDATA); - } else { - logger.debug("Found base module"); - baseModuleOutputs = baseDeployment.getOutputs(); - this.sendMapToDebug(baseModuleOutputs, "baseModuleOutputs"); - } - } - } - - - // Ready to deploy the new VNF - - // 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. - 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 - + ", modelCustomizationUuid=" + modelCustomizationUuid + ", vfModuleUuid=" + vf.getModelUUID() - + ", reqType=" + requestType; - logger.error(LoggingAnchor.SIX, 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 + ", modelCustomizationUuid=" - + modelCustomizationUuid + ", vfModuleUuid=" + vf.getModelUUID() + ", reqType=" + requestType; - logger.error(LoggingAnchor.FIVE, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), "Heat Environment ID", - OPENSTACK, ErrorCode.DataError.getValue(), error); - // Alarm on this error, configuration must be fixed - throw new VnfException(error, MsoExceptionCategory.INTERNAL); - } else { - logger.debug("Got Heat Environment from DB: {}", heatEnvironment.getEnvironment()); - } - - - try { - // All variables converted to their native object types - HashMap<String, Object> goldenInputs = new HashMap<>(); - List<String> extraInputs = new ArrayList<>(); - - // 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<>(); - for (Map.Entry<String, Object> entry : inputs.entrySet()) { - goldenInputs.put(entry.getKey(), entry.getValue()); - } - } else { - // Build maps for the parameters (including aliases) to simplify checks - HashMap<String, HeatTemplateParam> params = new HashMap<>(); - - 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 && !"".equals(alias) && !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 (Map.Entry<String, Object> entry : volumeGroupOutputs.entrySet()) { - if (params.containsKey(entry.getKey()) && !goldenInputs.containsKey(entry.getKey())) { - goldenInputs.put(entry.getKey(), entry.getValue()); - } - } - } - - // Next add in Base Module Outputs if there are any. Copy directly without conversions. - if (baseModuleOutputs != null && !baseModuleOutputs.isEmpty()) { - for (Map.Entry<String, Object> entry : baseModuleOutputs.entrySet()) { - if (params.containsKey(entry.getKey()) && !goldenInputs.containsKey(entry.getKey())) { - goldenInputs.put(entry.getKey(), entry.getValue()); - } - } - } - - // 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.error("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(LoggingAnchor.FIVE, 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<>(); - - 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(LoggingAnchor.SEVEN, 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. - 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()); - - } catch (MsoException me) { - me.addContext("CreateVFModule"); - String error = "Create VF Module " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" - + tenantId + ": " + me; - logger.error(LoggingAnchor.EIGHT, MessageEnum.RA_CREATE_VNF_ERR.toString(), vfModuleType, cloudOwner, - cloudSiteId, tenantId, CLOUDIFY, ErrorCode.DataError.getValue(), - "MsoException - createDeployment", me); - logger.debug(error); - throw new VnfException(me); - } catch (NullPointerException npe) { - String error = "Create VFModule " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" - + tenantId + ": " + npe; - logger.error(LoggingAnchor.EIGHT, 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"); - } catch (Exception e) { - logger.error("unhandled exception at cloudify.createAndInstallDeployment", e); - throw new VnfException("Exception during cloudify.createAndInstallDeployment! " + e.getMessage()); - } - } catch (Exception e) { - logger.error("unhandled exception in create VF", e); - 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()); - vnfId.value = cloudifyDeployment.getId(); - outputs.value = copyStringOutputs(cloudifyDeployment.getOutputs()); - - rollback.value = vfRollback; - - logger.debug("VF Module successfully created {}", vfModuleName); - - } - - public void deleteVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, String vnfId, - String vfModuleId, String modelCustomizationUuid, MsoRequest msoRequest, - Holder<Map<String, String>> outputs) throws VnfException { - logger.debug("Deleting VF " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId); - - // 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); - } 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(BRACKETS, 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); - } - // 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. - 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(BRACKETS, 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); - } - - // On success, nothing is returned. - return; - } - - // 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); - } - -} 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 deleted file mode 100644 index 0ecfd15dde..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImpl.java +++ /dev/null @@ -1,1169 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -/** - * 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). - */ -package org.onap.so.adapters.vnf; - - -import java.util.ArrayList; -import java.util.HashMap; -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.logger.LoggingAnchor; -import org.onap.so.adapters.vdu.CloudInfo; -import org.onap.so.adapters.vdu.VduException; -import org.onap.so.adapters.vdu.VduInstance; -import org.onap.so.adapters.vdu.VduModelInfo; -import org.onap.so.adapters.vdu.VduPlugin; -import org.onap.so.adapters.vdu.VduStateType; -import org.onap.so.adapters.vdu.VduStatus; -import org.onap.so.adapters.vdu.mapper.VfModuleCustomizationToVduMapper; -import org.onap.so.adapters.vnf.exceptions.VnfAlreadyExists; -import org.onap.so.adapters.vnf.exceptions.VnfException; -import org.onap.so.cloud.CloudConfig; -import org.onap.so.db.catalog.beans.CloudSite; -import org.onap.so.cloudify.utils.MsoCloudifyUtils; -import org.onap.so.db.catalog.beans.HeatEnvironment; -import org.onap.so.db.catalog.beans.HeatTemplate; -import org.onap.so.db.catalog.beans.HeatTemplateParam; -import org.onap.so.db.catalog.beans.VfModule; -import org.onap.so.db.catalog.beans.VfModuleCustomization; -import org.onap.so.db.catalog.beans.VnfResource; -import org.onap.so.db.catalog.data.repository.VFModuleCustomizationRepository; -import org.onap.so.db.catalog.utils.MavenLikeVersioning; -import org.onap.so.entity.MsoRequest; -import org.onap.logging.filter.base.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.MsoException; -import org.onap.so.openstack.exceptions.MsoExceptionCategory; -import org.onap.so.openstack.utils.MsoHeatEnvironmentEntry; -import org.onap.so.openstack.utils.MsoHeatUtils; -import org.onap.so.openstack.utils.MsoKeystoneUtils; -import org.onap.so.openstack.utils.MsoMulticloudUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; -import 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") -@Component -@Transactional -public class MsoVnfPluginAdapterImpl implements MsoVnfAdapter { - - private static Logger logger = LoggerFactory.getLogger(MsoVnfPluginAdapterImpl.class); - - private static final String CHECK_REQD_PARAMS = "org.onap.so.adapters.vnf.checkRequiredParameters"; - private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); - - @Autowired - protected CloudConfig cloudConfig; - - @Autowired - private VFModuleCustomizationRepository vfModuleCustomRepo; - - @Autowired - private Environment environment; - - @Autowired - protected MsoKeystoneUtils keystoneUtils; - - @Autowired - protected MsoCloudifyUtils cloudifyUtils; - - @Autowired - protected MsoHeatUtils heatUtils; - - @Autowired - protected MsoMulticloudUtils multicloudUtils; - - @Autowired - protected VfModuleCustomizationToVduMapper vduMapper; - - /** - * DO NOT use that constructor to instantiate this class, the msoPropertiesfactory will be NULL. - * - * @see MsoVnfPluginAdapterImpl#MsoVnfAdapterImpl(MsoPropertiesFactory, CloudConfigFactory) - */ - public MsoVnfPluginAdapterImpl() { - - } - - /** - * 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 Plugin Adapter"); - } - - /** - * 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. - 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. - * - */ - @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); - } - - /** - * This is the "Query VNF" web service implementation. - * - * 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. - * - * @param cloudSiteId CLLI code of the cloud site in which to query - * @param tenantId Openstack tenant identifier - * @param vnfNameOrId VNF Name or ID to query - * @param msoRequest Request tracking information for logs - * @param vnfExists Flag reporting the result of the query - * @param vnfId Holder for output VNF ID - * @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 { - logger.debug("Querying VNF " + vnfNameOrId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId); - - VduInstance vduInstance; - 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(LoggingAnchor.NINE, 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); - } - return; - } - - - /** - * 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); - } - - /** - * 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. - */ - @Override - public void rollbackVnf(VnfRollback rollback) throws VnfException { - // rollback may be null (e.g. if stack already existed when Create was called) - if (rollback == null) { - logger.info(LoggingAnchor.THREE, MessageEnum.RA_ROLLBACK_NULL.toString(), "OpenStack", "rollbackVnf"); - return; - } - - // Don't rollback if nothing was done originally - if (!rollback.getVnfCreated()) { - return; - } - - // Get the elements of the VnfRollback object for easier access - String cloudSiteId = rollback.getCloudSiteId(); - String cloudOwner = rollback.getCloudOwner(); - String tenantId = rollback.getTenantId(); - CloudInfo cloudInfo = new CloudInfo(cloudSiteId, cloudOwner, tenantId, null); - - String vfModuleId = rollback.getVfModuleStackId(); - - logger.debug("Rolling Back VF Module " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId); - - VduInstance vduInstance = null; - - // Use the VduPlugin to delete the VF Module. - VduPlugin vduPlugin = getVduPlugin(cloudSiteId, cloudOwner); - - try { - // 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) { - // 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(LoggingAnchor.NINE, 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); - } - 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; - } - - /* - * 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 ("number".equalsIgnoreCase(type)) { - try { - return Integer.valueOf(inputValue.toString()); - } catch (Exception e) { - logger.debug("Unable to convert " + inputValue + " to an integer!", e); - return null; - } - } else if ("json".equalsIgnoreCase(type)) { - 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 ("boolean".equalsIgnoreCase(type)) { - return Boolean.valueOf(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<>(); - 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); - } - } 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); - } - } 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); - } - } - } - return stringOutputs; - } - - - 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; - } - - 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; - } - - private String convertNode(final JsonNode node) { - try { - final Object obj = JSON_MAPPER.treeToValue(node, Object.class); - final String json = JSON_MAPPER.writeValueAsString(obj); - return json; - } catch (JsonParseException jpe) { - logger.debug("Error converting json to string " + jpe.getMessage()); - } catch (Exception e) { - logger.debug("Error converting json to string " + e.getMessage()); - } - return "[Error converting json to string]"; - } - - private Map<String, String> convertMapStringObjectToStringString(Map<String, Object> objectMap) { - if (objectMap == null) { - return null; - } - Map<String, String> stringMap = new HashMap<>(); - for (String key : objectMap.keySet()) { - if (!stringMap.containsKey(key)) { - Object obj = objectMap.get(key); - if (obj instanceof String) { - stringMap.put(key, (String) objectMap.get(key)); - } 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 - } - } else if (obj instanceof java.util.LinkedHashMap) { - logger.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode"); - try { - 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); - } - } else { - try { - String str = obj.toString(); - stringMap.put(key, str); - } catch (Exception e) { - logger.debug( - "DANGER WILL ROBINSON: unable to convert value " + key + " (" + e.getMessage() + ")", - e); - } - } - } - } - - return stringMap; - } - - /** - * 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. - * - * 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. - * - * 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 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 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) - * @param msoRequest Request tracking information for logs - * @param vnfId Holder for output VF Module instance ID in the cloud - * @param outputs Holder for Map of VNF outputs from Deployment (assigned IPs, etc) - * @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 { - - // 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(LoggingAnchor.FIVE, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), - "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 = ""; - - if ("".equals(volumeGroupId) || "null".equals(volumeGroupId)) - volumeGroupId = null; - - if ("".equals(baseVfModuleId) || "null".equals(baseVfModuleId)) - baseVfModuleId = null; - - if (inputs == null) { - // Create an empty set of inputs - inputs = new HashMap<>(); - logger.debug("inputs == null - setting to empty"); - } else { - this.sendMapToDebug(inputs); - } - - // Check if this is for a "Volume" module - boolean isVolumeRequest = false; - if (requestType.startsWith("VOLUME")) { - isVolumeRequest = true; - } - - logger.debug("requestType = " + requestType + ", volumeGroupStackId = " + volumeGroupId + ", baseStackId = " - + baseVfModuleId); - - // Build a default rollback object (no actions performed) - VnfRollback vfRollback = new VnfRollback(); - vfRollback.setCloudSiteId(cloudSiteId); - vfRollback.setCloudOwner(cloudOwner); - vfRollback.setTenantId(tenantId); - vfRollback.setMsoRequest(msoRequest); - vfRollback.setRequestType(requestType); - 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 - - // Get the VNF/VF Module definition from the Catalog DB first. - // There are three relevant records: VfModule, VfModuleCustomization, VnfResource - - VfModule vfModule = null; - VnfResource vnfResource = null; - VfModuleCustomization vfModuleCust = null; - - try { - vfModuleCust = - vfModuleCustomRepo.findFirstByModelCustomizationUUIDOrderByCreatedDesc(modelCustomizationUuid); - - if (vfModuleCust == null) { - String error = "Create vfModule error: Unable to find vfModuleCust with modelCustomizationUuid=" - + modelCustomizationUuid; - logger.debug(error); - logger.error(LoggingAnchor.SIX, MessageEnum.RA_VNF_UNKNOWN_PARAM.toString(), - "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) { - - 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); - 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); - } else { - 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(LoggingAnchor.FIVE, MessageEnum.RA_CONFIG_EXC.toString(), error, "OpenStack", - ErrorCode.BusinessProcessError.getValue(), "Exception - setVersion"); - logger.debug(error); - throw new VnfException(error, MsoExceptionCategory.USERDATA); - } - } - // End Version check - - - VduInstance vduInstance = null; - CloudInfo cloudInfo = new CloudInfo(cloudSiteId, cloudOwner, tenantId, null); - - // Use the VduPlugin. - VduPlugin vduPlugin = getVduPlugin(cloudSiteId, cloudOwner); - - try { - 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; - logger.error(LoggingAnchor.NINE, MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, 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); - } - - // More precise handling/messaging if the Module already exists - if (vduInstance != null && !(vduInstance.getStatus().getState() == VduStateType.NOTFOUND)) { - 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(LoggingAnchor.NINE, 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()); - } else { - // Found existing deployment and client has not requested "failIfExists". - // Populate the outputs from the existing deployment. - - vnfId.value = vduInstance.getVduInstanceId(); - outputs.value = copyStringOutputs(vduInstance.getOutputs()); - return; - } - } - // Check through various detailed error cases - else if (status == VduStateType.INSTANTIATING || status == VduStateType.DELETING - || 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."; - logger.error(LoggingAnchor.NINE, 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()); - } 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."; - logger.error(LoggingAnchor.NINE, 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"); - logger.debug(error); - 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."; - logger.error(LoggingAnchor.NINE, 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"); - logger.debug(error); - 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."; - logger.error(LoggingAnchor.NINE, 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"); - logger.debug(error); - throw new VnfAlreadyExists(vfModuleName, cloudSiteId, cloudOwner, tenantId, - vduInstance.getVduInstanceId()); - } - } - - - // Collect outputs from Base Modules and Volume Modules - Map<String, Object> baseModuleOutputs = null; - Map<String, Object> volumeGroupOutputs = null; - - // If a Volume Group was provided, query its outputs for inclusion in Module input parameters - if (volumeGroupId != null) { - VduInstance volumeVdu; - try { - 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; - logger.error(LoggingAnchor.NINE, MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId, 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); - } - - 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(LoggingAnchor.TEN, MessageEnum.RA_QUERY_VNF_ERR.toString(), volumeGroupId, cloudOwner, - cloudSiteId, tenantId, error, "VDU", "queryVdu(volume)", - ErrorCode.BusinessProcessError.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 - - if (vfModule.getIsBase()) { - logger.debug("This is a BASE Module request"); - vfRollback.setIsBase(true); - } else { - logger.debug("This is an Add-On Module request"); - - // 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"); - } - - if (baseVfModuleId != null) { - VduInstance baseVdu; - 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(LoggingAnchor.NINE, 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(LoggingAnchor.TEN, MessageEnum.RA_QUERY_VNF_ERR.toString(), baseVfModuleId, cloudOwner, - cloudSiteId, tenantId, error, "VDU", "queryVdu(Base)", - ErrorCode.BusinessProcessError.getValue(), "Create VFModule: Base Module DOES NOT EXIST"); - logger.debug(error); - throw new VnfException(error, MsoExceptionCategory.USERDATA); - } else { - logger.debug("Found base module"); - baseModuleOutputs = baseVdu.getOutputs(); - this.sendMapToDebug(baseModuleOutputs, "baseModuleOutputs"); - } - } - } - - - // 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. - - 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 - + ", modelCustomizationUuid=" + modelCustomizationUuid + ", vfModuleUuid=" + vfModule.getModelUUID() - + ", reqType=" + requestType; - logger.error(LoggingAnchor.SIX, 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 { - logger.debug("Got HEAT Template from DB: " + heatTemplate.getHeatTemplate()); - } - - if (heatEnvironment == null) { - String error = "Update VNF: undefined Heat Environment. VF=" + vfModuleType + ", modelCustomizationUuid=" - + modelCustomizationUuid + ", vfModuleUuid=" + vfModule.getModelUUID() + ", reqType=" + requestType; - logger.error(LoggingAnchor.FIVE, 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()); - } - - - // 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. - - HashMap<String, Object> goldenInputs = new HashMap<>(); - List<String> extraInputs = new ArrayList<>(); - - Boolean skipInputChecks = false; - - if (skipInputChecks) { - goldenInputs = new HashMap<>(); - 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<>(); - - 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 && !"".equals(alias) && !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)) { - checkRequiredParameters = false; - logger.debug("CheckRequiredParameters is FALSE. Will still check but then skip blocking..." - + 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); - } - - // 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 - // 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()))) { - if (mhee != null && mhee.containsParameter(parm.getParamName())) { - 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(); - } - } - } - } - - if (missingParams != null) { - if (checkRequiredParameters) { - // Problem - missing one or more required parameters - String error = "Create VFModule: Missing Required inputs: " + missingParams; - logger.error(LoggingAnchor.FIVE, 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("No missing parameters found - ok to proceed"); - } - - } // NOTE: END PARAMETER CHECKING - - - // Here we go... ready to deploy the VF Module. - if (backout == null) - backout = true; - - try { - // Construct the VDU Model structure to pass to the targeted VduPlugin - VduModelInfo vduModel = null; - if (!isVolumeRequest) { - vduModel = vduMapper.mapVfModuleCustomizationToVdu(vfModuleCust); - } else { - vduModel = vduMapper.mapVfModuleCustVolumeToVdu(vfModuleCust); - } - - // Invoke the VduPlugin to instantiate the VF Module - vduInstance = vduPlugin.instantiateVdu(cloudInfo, vfModuleName, goldenInputs, vduModel, backout); - - } catch (VduException me) { - // Failed to instantiate the VDU. - me.addContext("CreateVFModule"); - String error = "Create VF Module " + vfModuleType + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId - + ": " + me; - logger.error(LoggingAnchor.EIGHT, 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(LoggingAnchor.EIGHT, 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; - logger.debug("Unhandled exception at vduPlugin.instantiateVdu", e); - logger.debug(error); - throw new VnfException("Exception during instantiateVdu: " + e.getMessage()); - } - - - // Reach this point if create is successful. - // Populate remaining rollback info and response parameters. - vfRollback.setVnfCreated(true); - vfRollback.setVnfId(vduInstance.getVduInstanceId()); - vnfId.value = vduInstance.getVduInstanceId(); - outputs.value = copyStringOutputs(vduInstance.getOutputs()); - - rollback.value = vfRollback; - - logger.debug("VF Module " + vfModuleName + " successfully created"); - return; - } - - - public void deleteVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vfModuleId, String vnfId, - String aaiVfModuleId, String modelCustomizationUuid, MsoRequest msoRequest, - Holder<Map<String, String>> outputs) throws VnfException { - - logger.debug("Deleting VF Module " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId); - - // Capture the output parameters on a delete, so need to query first - VduInstance vduInstance; - 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(LoggingAnchor.NINE, 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. - // The possible outcomes of deleteVdu are - // - a vnfInstance object with status of DELETED (success) - // - 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. - try { - // TODO: Get an appropriate timeout value - require access to the model - vduPlugin.deleteVdu(cloudInfo, vfModuleId, 5); - } catch (VduException me) { - me.addContext("DeleteVfModule"); - // Convert to a generic VnfException - String error = - "Delete VF: " + vfModuleId + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; - logger.error(LoggingAnchor.NINE, 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); - } - - // On success, nothing is returned. - return; - } - - // 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); - } - - /* - * 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 ("CLOUDIFY".equalsIgnoreCase(orchestrator)) { - return cloudifyUtils; - } else if ("HEAT".equalsIgnoreCase(orchestrator)) { - return heatUtils; - } else if ("MULTICLOUD".equalsIgnoreCase(orchestrator)) { - return multicloudUtils; - } else { - // Default if cloudSite record exists - return HEAT plugin - will fail later - return heatUtils; - } - } - // Default if no cloudSite record exists - return multicloud plugin - return multicloudUtils; - } -} 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 deleted file mode 100644 index 5b78d2f066..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java +++ /dev/null @@ -1,578 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Modifications Copyright (C) 2018 IBM. - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.vnf; - - -import java.util.Map; -import javax.inject.Provider; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -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.onap.so.logger.LoggingAnchor; -import org.apache.http.HttpStatus; -import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.adapters.vnf.exceptions.VnfException; -import org.onap.so.adapters.vnfrest.CreateVfModuleRequest; -import org.onap.so.adapters.vnfrest.CreateVfModuleResponse; -import org.onap.so.adapters.vnfrest.DeleteVfModuleRequest; -import org.onap.so.adapters.vnfrest.DeleteVfModuleResponse; -import org.onap.so.adapters.vnfrest.QueryVfModuleResponse; -import org.onap.so.adapters.vnfrest.RollbackVfModuleRequest; -import org.onap.so.adapters.vnfrest.RollbackVfModuleResponse; -import org.onap.so.adapters.vnfrest.UpdateVfModuleRequest; -import org.onap.so.adapters.vnfrest.UpdateVfModuleResponse; -import org.onap.so.adapters.vnfrest.VfModuleExceptionResponse; -import org.onap.so.adapters.vnfrest.VfModuleRollback; -import org.onap.so.entity.MsoRequest; -import org.onap.logging.filter.base.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.MsoExceptionCategory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -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; -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___ - */ -@Deprecated -@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; - - @Autowired - private Provider<BpelRestClient> bpelRestClientProvider; - - @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.BusinessProcessError.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 { - try { - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, req.getMsoRequest().getRequestId()); - } catch (Exception e) { - logger.error("Error adding RequestId to MDC", e); - } - String cloudsite = req.getCloudSiteId(); - Holder<Map<String, String>> outputs = new Holder<>(); - if (cloudsite != null && !cloudsite.equals(TESTING_KEYWORD)) { - vnfAdapter.deleteVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), - req.getVfModuleStackId(), req.getVnfId(), req.getVfModuleId(), - req.getModelCustomizationUuid(), req.getMsoRequest(), outputs); - } - response = new DeleteVfModuleResponse(req.getVnfId(), req.getVfModuleId(), Boolean.TRUE, - req.getMessageId(), outputs.value); - } catch (VnfException e) { - logger.error(LoggingAnchor.THREE, MessageEnum.RA_DELETE_VNF_ERR.toString(), - ErrorCode.BusinessProcessError.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()); - } - } - - - @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(LoggingAnchor.FIVE, MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, "queryVfModule", - ErrorCode.BusinessProcessError.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(LoggingAnchor.FOUR, MessageEnum.RA_CREATE_VNF_ERR, "createVfModule", - ErrorCode.BusinessProcessError, "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 { - try { - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, req.getMsoRequest().getRequestId()); - } catch (Exception e) { - logger.error("Error adding RequestId to MDC", e); - } - // 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.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) { - 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()); - } - } - - @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(LoggingAnchor.FOUR, MessageEnum.RA_UPDATE_VNF_ERR.toString(), "updateVfModule", - ErrorCode.BusinessProcessError.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 { - try { - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, req.getMsoRequest().getRequestId()); - } catch (Exception e) { - logger.error("Error adding RequestId to MDC", e); - } - 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()); - } - } - - - @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(LoggingAnchor.FOUR, MessageEnum.RA_ROLLBACK_VNF_ERR.toString(), "rollbackVfModule", - ErrorCode.BusinessProcessError.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 { - try { - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, req.getVfModuleRollback().getMsoRequest().getRequestId()); - } catch (Exception e) { - logger.error("Error adding RequestId to MDC", e); - } - 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(LoggingAnchor.THREE, MessageEnum.RA_ROLLBACK_VNF_ERR, ErrorCode.BusinessProcessError, - "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 deleted file mode 100644 index b53ac0f899..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestUtils.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.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; -import org.slf4j.LoggerFactory; -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; - } - -} 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 deleted file mode 100644 index 63b4c5d0f3..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java +++ /dev/null @@ -1,626 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (C) 2018 IBM. - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.vnf; - - -import java.util.Map; -import javax.inject.Provider; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -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.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.adapters.vnf.exceptions.VnfException; -import org.onap.so.adapters.vnfrest.CreateVfModuleRequest; -import org.onap.so.adapters.vnfrest.CreateVfModuleResponse; -import org.onap.so.adapters.vnfrest.DeleteVfModuleRequest; -import org.onap.so.adapters.vnfrest.DeleteVfModuleResponse; -import org.onap.so.adapters.vnfrest.QueryVfModuleResponse; -import org.onap.so.adapters.vnfrest.RollbackVfModuleRequest; -import org.onap.so.adapters.vnfrest.RollbackVfModuleResponse; -import org.onap.so.adapters.vnfrest.UpdateVfModuleRequest; -import org.onap.so.adapters.vnfrest.UpdateVfModuleResponse; -import org.onap.so.adapters.vnfrest.VfModuleExceptionResponse; -import org.onap.so.adapters.vnfrest.VfModuleRollback; -import org.onap.so.entity.MsoRequest; -import org.onap.logging.filter.base.ErrorCode; -import org.onap.so.logger.LoggingAnchor; -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.MsoExceptionCategory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -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; -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___ - * - * V2 incorporates run-time selection of sub-orchestrator implementation (Heat or Cloudify) based on the target cloud. - */ -@Deprecated -@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="; - private static final String BRACKETS = LoggingAnchor.FOUR; - - @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); - MDC.getCopyOfContextMap(); - t1.start(); - } catch (Exception e) { - // problem handling delete, send generic failure as sync resp to caller - logger.error(BRACKETS, MessageEnum.RA_DELETE_VNF_ERR.toString(), "deleteVfModule", - ErrorCode.BusinessProcessError.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 { - try { - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, req.getMsoRequest().getRequestId()); - } catch (Exception e) { - logger.error("Error adding RequestId to MDC", e); - } - String cloudsite = req.getCloudSiteId(); - Holder<Map<String, String>> outputs = new Holder<>(); - if (cloudsite != null) { - MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsite); - adapter.deleteVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), - req.getVfModuleStackId(), req.getVnfId(), req.getVfModuleId(), - req.getModelCustomizationUuid(), req.getMsoRequest(), outputs); - } - response = new DeleteVfModuleResponse(req.getVnfId(), req.getVfModuleId(), Boolean.TRUE, - req.getMessageId(), outputs.value); - } catch (VnfException e) { - logger.error(LoggingAnchor.THREE, MessageEnum.RA_DELETE_VNF_ERR.toString(), - ErrorCode.BusinessProcessError.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()); - MDC.clear(); - } - } - - /* - * 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<>(); - Holder<String> vfModuleId = new Holder<>(); - Holder<VnfStatus> status = new Holder<>(); - Holder<Map<String, String>> outputs = new Holder<>(); - - // 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(LoggingAnchor.FIVE, MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, "queryVfModule", - ErrorCode.BusinessProcessError.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(BRACKETS, MessageEnum.RA_CREATE_VNF_ERR.toString(), "createVfModule", - ErrorCode.BusinessProcessError.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 { - try { - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, req.getMsoRequest().getRequestId()); - } catch (Exception e) { - logger.error("Error adding RequestId to MDC", e); - } - // 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 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(BRACKETS, MessageEnum.RA_UPDATE_VNF_ERR.toString(), "updateVfModule", - ErrorCode.BusinessProcessError.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 { - try { - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, req.getMsoRequest().getRequestId()); - } catch (Exception e) { - logger.error("Error adding RequestId to MDC", e); - } - // 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); - - 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(BRACKETS, MessageEnum.RA_ROLLBACK_VNF_ERR.toString(), "rollbackVfModule", - ErrorCode.BusinessProcessError.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 { - try { - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, req.getVfModuleRollback().getMsoRequest().getRequestId()); - } catch (Exception e) { - logger.error("Error adding RequestId to MDC", e); - } - 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(LoggingAnchor.THREE, MessageEnum.RA_ROLLBACK_VNF_ERR.toString(), - ErrorCode.BusinessProcessError.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 deleted file mode 100644 index 7e12735e05..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRest.java +++ /dev/null @@ -1,626 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Modifications Copyright (C) 2018 IBM. - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.vnf; - - -import java.util.HashMap; -import java.util.Map; -import javax.inject.Provider; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -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.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.adapters.vnf.exceptions.VnfException; -import org.onap.so.adapters.vnfrest.CreateVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.CreateVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.DeleteVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.DeleteVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.QueryVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.RollbackVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.RollbackVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.UpdateVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.UpdateVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.VolumeGroupExceptionResponse; -import org.onap.so.adapters.vnfrest.VolumeGroupRollback; -import org.onap.so.entity.MsoRequest; -import org.onap.logging.filter.base.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.MsoExceptionCategory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -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; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - -/** - * 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") -@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.BusinessProcessError.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() { - try { - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, req.getMsoRequest().getRequestId()); - } catch (Exception e) { - logger.error("Error adding RequestId to MDC", e); - } - 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.BusinessProcessError.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() { - try { - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, req.getMsoRequest().getRequestId()); - } catch (Exception e) { - logger.error("Error adding RequestId to MDC", e); - } - 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.BusinessProcessError.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() { - try { - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, req.getVolumeGroupRollback().getMsoRequest().getRequestId()); - } catch (Exception e) { - logger.error("Error adding RequestId to MDC", e); - } - 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.BusinessProcessError.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 { - try { - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, req.getMsoRequest().getRequestId()); - } catch (Exception e) { - logger.error("Error adding RequestId to MDC", e); - } - 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.BusinessProcessError.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; - } -} 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 deleted file mode 100644 index a424fa92fd..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java +++ /dev/null @@ -1,606 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (C) 2018 IBM. - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.vnf; - - -import java.util.HashMap; -import java.util.Map; -import javax.inject.Provider; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -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.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.adapters.vnf.exceptions.VnfException; -import org.onap.so.adapters.vnfrest.CreateVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.CreateVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.DeleteVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.DeleteVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.QueryVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.RollbackVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.RollbackVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.UpdateVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.UpdateVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.VolumeGroupExceptionResponse; -import org.onap.so.adapters.vnfrest.VolumeGroupRollback; -import org.onap.so.entity.MsoRequest; -import org.onap.logging.filter.base.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.MsoExceptionCategory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -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; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; - -/** - * 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. - */ -@Path("/v2/volume-groups") -@Api(value = "/v2/volume-groups", description = "root of volume-groups adapters restful web service v2") -@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) { - 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.BusinessProcessError.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() { - try { - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, req.getMsoRequest().getRequestId()); - } catch (Exception e) { - logger.error("Error adding RequestId to MDC", e); - } - 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(); - - // 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.BusinessProcessError.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() { - try { - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, req.getMsoRequest().getRequestId()); - } catch (Exception e) { - logger.error("Error adding RequestId to MDC", e); - } - 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.BusinessProcessError.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() { - try { - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, req.getVolumeGroupRollback().getMsoRequest().getRequestId()); - } catch (Exception e) { - logger.error("Error adding RequestId to MDC", e); - } - 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.BusinessProcessError.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() { - try { - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, req.getMsoRequest().getRequestId()); - } catch (Exception e) { - logger.error("Error adding RequestId to MDC", e); - } - 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.BusinessProcessError.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; - } -} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImplTest.java index 46d9f89303..1a308b7c4c 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImplTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterAsyncImplTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -30,13 +30,11 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStackVfModule_200; import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackResponseAccess; import java.util.HashMap; -import java.util.Map; import org.apache.http.HttpStatus; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.onap.so.entity.MsoRequest; -import org.onap.so.openstack.beans.VnfRollback; import org.springframework.beans.factory.annotation.Autowired; public class MsoVnfAdapterAsyncImplTest extends BaseRestTestUtils { @@ -86,48 +84,6 @@ public class MsoVnfAdapterAsyncImplTest extends BaseRestTestUtils { } @Test - public void updateVnfTest() throws Exception { - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - Map<String, Object> map = new HashMap<>(); - map.put("key1", "value1"); - wireMockServer.stubFor(post(urlPathEqualTo("/notify/adapterNotify/updateVnfNotificationRequest")) - .withRequestBody(containing("messageId")).willReturn(aResponse().withStatus(HttpStatus.SC_OK))); - String notificationUrl = - "http://localhost:" + wireMockPort + "/notify/adapterNotify/updateVnfNotificationRequest"; - instance.updateVnfA("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "vSAMP12", "VFMOD", - "volumeGroupHeatStackId|1", map, "messageId", msoRequest, notificationUrl); - } - - @Test - public void updateVnfTest_Exception() throws Exception { - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - Map<String, Object> map = new HashMap<>(); - map.put("key1", "value1"); - wireMockServer.stubFor(post(urlPathEqualTo("/notify/adapterNotify/updateVnfNotificationRequest")) - .withRequestBody(containing("messageId")).willReturn(aResponse().withStatus(HttpStatus.SC_OK))); - String notificationUrl = - "http://localhost:" + wireMockPort + "/notify/adapterNotify/updateVnfNotificationRequest"; - instance.updateVnfA("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "vSAMP12", "VFMOD", - "volumeGroupHeatStackId|1", map, "messageId", msoRequest, notificationUrl); - wireMockServer.verify(1, postRequestedFor(urlEqualTo("/notify/adapterNotify/updateVnfNotificationRequest"))); - } - - @Test - public void queryVnfTest() { - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - instance.queryVnfA("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vSAMP12", "messageId", msoRequest, - "http://org.onap.so/notify/adapterNotify/updateVnfNotificationRequest"); - } - - @Test public void deleteVnfTest() { MsoRequest msoRequest = new MsoRequest(); msoRequest.setRequestId("12345"); @@ -136,14 +92,4 @@ public class MsoVnfAdapterAsyncImplTest extends BaseRestTestUtils { msoRequest, "http://org.onap.so/notify/adapterNotify/updateVnfNotificationRequest"); } - @Test - public void rollbackVnfTest() { - VnfRollback vnfRollBack = new VnfRollback(); - vnfRollBack.setCloudSiteId("mdt1"); - vnfRollBack.setCloudOwner("CloudOwner"); - vnfRollBack.setTenantId("88a6ca3ee0394ade9403f075db23167e"); - vnfRollBack.setVnfId("ff5256d1-5a33-55df-13ab-12abad84e7ff"); - instance.rollbackVnfA(vnfRollBack, "messageId", - "http://org.onap.so/notify/adapterNotify/updateVnfNotificationRequest"); - } } diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImplTest.java deleted file mode 100644 index 45504fcab5..0000000000 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfCloudifyAdapterImplTest.java +++ /dev/null @@ -1,308 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * Copyright (C) 2018 Huawei Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.vnf; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; -import static org.junit.Assert.assertTrue; -import java.util.HashMap; -import java.util.Map; -import javax.xml.ws.Holder; -import org.apache.http.HttpStatus; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.onap.so.adapters.vnf.exceptions.VnfException; -import org.onap.so.cloud.CloudConfig; -import org.onap.so.db.catalog.beans.CloudifyManager; -import org.onap.so.entity.MsoRequest; -import org.onap.so.openstack.beans.VnfRollback; -import org.springframework.beans.factory.annotation.Autowired; - -public class MsoVnfCloudifyAdapterImplTest extends BaseRestTestUtils { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Autowired - private MsoVnfCloudifyAdapterImpl instance; - - @Autowired - private CloudConfig cloudConfig; - - @Before - public void before() throws Exception { - super.setUp(); - CloudifyManager cloudifyManager = new CloudifyManager(); - cloudifyManager.setId("mtn13"); - cloudifyManager.setCloudifyUrl("http://localhost:" + wireMockPort + "/v2.0"); - cloudifyManager.setUsername("m93945"); - cloudifyManager.setPassword("93937EA01B94A10A49279D4572B48369"); - } - - /* - * @Test public void queryVnfExceptionTest() throws Exception { MsoRequest msoRequest = new MsoRequest(); - * msoRequest.setRequestId("12345"); msoRequest.setServiceInstanceId("12345"); Holder<Map<String, String>> outputs = - * new Holder<>(); instance.queryVnf("siteid", "CloudOwner", "1234", "vfname", msoRequest, new Holder<>(), new - * Holder<>(), new Holder<>(), outputs); - * - * assertTrue(outputs.value.isEmpty()); } - */ - - /* - * @Test public void queryVnfTest() throws Exception { - * - * - * MsoRequest msoRequest = new MsoRequest(); msoRequest.setRequestId("12345"); - * msoRequest.setServiceInstanceId("12345"); - * wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/deployments/vfname")) - * .willReturn(aResponse().withBody("{ \"id\": \"123\" }").withStatus(HttpStatus.SC_OK))); - * - * wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/deployments/vfname/outputs")) - * .willReturn(aResponse().withBody("{ \"deployment_id\": \"123\",\"outputs\":{\"abc\":\"abc\"} }") - * .withStatus(HttpStatus.SC_OK))); - * - * wireMockServer.stubFor(get(urlMatching("/v2.0/api/v3/executions?.*")).willReturn(aResponse() - * .withBody("{ \"items\": {\"id\": \"123\",\"workflow_id\":\"install\",\"status\":\"terminated\" } } ") - * .withStatus(HttpStatus.SC_OK))); - * - * instance.queryVnf("mtn13", "CloudOwner", "1234", "vfname", msoRequest, new Holder<>(), new Holder<>(), new - * Holder<>(), new Holder<>()); - * - * } - */ - - @Test - public void deleteVfModuleTest_ExceptionWhileQueryDeployment() throws Exception { - expectedException.expect(VnfException.class); - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - instance.deleteVfModule("mtn13", "CloudOwner", "1234", "vfname", "5aae1e49-805c-4f9f-bd78-055bf7451157", - "11420693-3f69-4c61-b3ee-9787c744e760", "customizationId", msoRequest, new Holder<>()); - } - - @Test - public void deleteVfModuleTest_ExceptionWhileDeleteDeployment() throws Exception { - expectedException.expect(VnfException.class); - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/deployments/vfname")) - .willReturn(aResponse().withBody("{ \"id\": \"123\" }").withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/deployments/vfname/outputs")) - .willReturn(aResponse().withBody("{ \"deployment_id\": \"123\",\"outputs\":{\"abc\":\"abc\"} }") - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching("/v2.0/api/v3/executions?.*")).willReturn(aResponse() - .withBody("{ \"items\": {\"id\": \"123\",\"workflow_id\":\"install\",\"status\":\"terminated\" } } ") - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/tokens")) - .willReturn(aResponse().withBodyFile("OpenstackResponse_Access.json").withStatus(HttpStatus.SC_OK))); - - instance.deleteVfModule("mtn13", "CloudOwner", "1234", "vfname", "5aae1e49-805c-4f9f-bd78-055bf7451157", - "11420693-3f69-4c61-b3ee-9787c744e760", "customizationId", msoRequest, new Holder<>()); - } - - @Test - public void deleteVnfVnfExceptionTest() throws Exception { - expectedException.expect(VnfException.class); - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - instance.deleteVnf("12344", "CloudOwner", "234", "vnfname", msoRequest); - - } - - @Test - public void rollbackVnf() throws Exception { - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - VnfRollback vnfRollback = new VnfRollback(); - vnfRollback.setModelCustomizationUuid("1234"); - vnfRollback.setVfModuleStackId("2134"); - vnfRollback.setVnfId("123"); - vnfRollback.setModelCustomizationUuid("1234"); - - instance.rollbackVnf(vnfRollback); - } - - @Test - public void rollbackVnf_Created() throws Exception { - expectedException.expect(VnfException.class); - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - VnfRollback vnfRollback = new VnfRollback(); - vnfRollback.setModelCustomizationUuid("1234"); - vnfRollback.setVfModuleStackId("2134"); - vnfRollback.setVnfId("123"); - vnfRollback.setModelCustomizationUuid("1234"); - vnfRollback.setVnfCreated(true); - - instance.rollbackVnf(vnfRollback); - } - - @Test - public void createVfModuleVnfException() throws Exception { - expectedException.expect(VnfException.class); - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - instance.createVfModule("123", "CloudOwner", "123", "vf", "v1", "", "module-005", "", "create", "3245", "234", - "123", new HashMap<>(), true, true, true, msoRequest, new Holder<>(), new Holder<>(), new Holder<>()); - } - - @Test - public void createVfModule_ModelCustUuidIsNull() throws Exception { - expectedException.expect(VnfException.class); - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - instance.createVfModule("123", "CloudOwner", "123", "vf", "v1", "", "module-005", "", "create", "3245", "234", - null, new HashMap<>(), true, true, true, msoRequest, new Holder<>(), new Holder<>(), new Holder<>()); - } - - @Test - public void createVfModule_CloudSiteIdNotFound() throws Exception { - expectedException.expect(VnfException.class); - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - instance.createVfModule("123", "CloudOwner", "123", "vf", "v1", "", "module-005", "", "create", "3245", "234", - "9b339a61-69ca-465f-86b8-1c72c582b8e8", new HashMap<>(), true, true, true, msoRequest, new Holder<>(), - new Holder<>(), new Holder<>()); - } - - @Test - public void createVfModule_MsoCloudifyManagerNotFound() throws Exception { - expectedException.expect(VnfException.class); - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - instance.createVfModule("mtn13", "CloudOwner", "123", "vf", "v1", "", "module-005", "", "create", "3245", "234", - "9b339a61-69ca-465f-86b8-1c72c582b8e8", new HashMap<>(), true, true, true, msoRequest, new Holder<>(), - new Holder<>(), new Holder<>()); - } - - @Test - public void createVfModule() throws Exception { - expectedException.expect(VnfException.class); - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/deployments/vfname")) - .willReturn(aResponse().withBody("{ \"id\": \"123\" }").withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/deployments/vfname/outputs")) - .willReturn(aResponse().withBody("{ \"deployment_id\": \"123\",\"outputs\":{\"abc\":\"abc\"} }") - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching("/v2.0/api/v3/executions?.*")).willReturn(aResponse() - .withBody("{ \"items\": {\"id\": \"123\",\"workflow_id\":\"install\",\"status\":\"terminated\" } } ") - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlPathEqualTo("/v2.0/api/v3/tokens")) - .willReturn(aResponse().withBodyFile("OpenstackResponse_Access.json").withStatus(HttpStatus.SC_OK))); - - instance.createVfModule("mtn13", "CloudOwner", "123", "vf", "v1", "", "vfname", "", "create", "3245", "234", - "9b339a61-69ca-465f-86b8-1c72c582b8e8", new HashMap<>(), true, true, true, msoRequest, new Holder<>(), - new Holder<>(), new Holder<>()); - } - - @Test - public void updateVfModuleVnfException() throws Exception { - expectedException.expect(VnfException.class); - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - instance.updateVfModule("123", "CloudOwner", "1234", "fw", "v2", "vnf1", "create", "123", "12", "233", "234", - new HashMap<>(), msoRequest, new Holder<>(), new Holder<>()); - } - - @Test - public void healthCheckVNFTest() { - instance.healthCheck(); - } - - @Test - public void createVnfTest() { - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - Map<String, Object> map = new HashMap<>(); - map.put("key1", "value1"); - try { - instance.createVnf("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "vSAMP12", "VFMOD", - "volumeGroupHeatStackId|1", map, Boolean.FALSE, Boolean.TRUE, Boolean.TRUE, msoRequest, - new Holder<>(), new Holder<>(), new Holder<>()); - } catch (Exception e) { - } - } - - @Test - public void updateVnfTest() { - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - Map<String, Object> map = new HashMap<>(); - - map.put("key1", "value1"); - try { - instance.updateVnf("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "vSAMP12", "VFMOD", - "volumeGroupHeatStackId|1", map, msoRequest, new Holder<>(), new Holder<>()); - } catch (Exception e) { - - } - } - - @Test - public void deleteVnfTest() { - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - try { - instance.deleteVnf("mdt1", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vSAMP12", msoRequest); - } catch (Exception e) { - - } - } - -} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfMulticloudAdapterImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfMulticloudAdapterImplTest.java deleted file mode 100644 index 3bf784c50b..0000000000 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfMulticloudAdapterImplTest.java +++ /dev/null @@ -1,231 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2018 Intel Corp. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.vnf; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.delete; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import java.util.HashMap; -import java.util.Map; -import javax.xml.ws.Holder; -import org.apache.http.HttpStatus; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.onap.so.adapters.vdu.VduModelInfo; -import org.onap.so.adapters.vnf.exceptions.VnfException; -import org.onap.so.cloud.CloudConfig; -import org.onap.so.entity.MsoRequest; -import org.onap.so.openstack.beans.StackInfo; -import org.onap.so.openstack.exceptions.MsoException; -import org.springframework.beans.factory.annotation.Autowired; - -public class MsoVnfMulticloudAdapterImplTest extends BaseRestTestUtils { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Autowired - private MsoVnfPluginAdapterImpl instance; - - @Autowired - private CloudConfig cloudConfig; - - private static final String UPDATE_STACK_RESPONSE = - "{\"template_type\": \"heat\", \"workload_id\": " + "\"workload-id\"}"; - private static final String GET_CREATE_STACK_RESPONSE = "{\"template_type\": \"heat\", \"workload_id\": " - + "\"workload-id\", \"workload_status\": \"CREATE_COMPLETE\"}"; - private static final String GET_UPDATE_STACK_RESPONSE = "{\"template_type\": \"heat\", \"workload_id\": " - + "\"workload-id\", \"workload_status\": \"UPDATE_COMPLETE\"}"; - - private static final String MULTICLOUD_CREATE_PATH = "/api/multicloud/v1/CloudOwner/MTN13/infra_workload"; - private static final String MULTICLOUD_UPDATE_PATH = - "/api/multicloud/v1/CloudOwner/MTN13/infra_workload/workload-id"; - private static final String MULTICLOUD_GET_PATH_BY_NAME = - "/api/multicloud/v1/CloudOwner/MTN13/infra_workload/vfname"; - private static final String MULTICLOUD_GET_PATH_BY_ID = - "/api/multicloud/v1/CloudOwner/MTN13/infra_workload/workload-id"; - - @Before - public void before() throws Exception { - super.orchestrator = "multicloud"; - super.cloudEndpoint = "/api/multicloud/v1/CloudOwner/MTN13/infra_workload"; - super.setUp(); - } - - @Test - public void createVfModule() throws Exception { - - Map<String, Object> stackInputs = new HashMap<>(); - stackInputs.put("oof_directives", "{}"); - stackInputs.put("sdnc_directives", "{}"); - stackInputs.put("user_directives", "{}"); - stackInputs.put("generic_vnf_id", "genVNFID"); - stackInputs.put("vf_module_id", "vfMODULEID"); - - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH_BY_NAME)).willReturn( - aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NOT_FOUND))); - - wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH_BY_ID)).inScenario("CREATE") - .whenScenarioStateIs("CREATING").willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBody(GET_CREATE_STACK_RESPONSE).withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH_BY_ID)).inScenario("CREATE") - .whenScenarioStateIs("UPDATING").willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBody(GET_UPDATE_STACK_RESPONSE).withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)).inScenario("CREATE") - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBodyFile("MulticloudResponse_Stack_Create.json").withStatus(HttpStatus.SC_CREATED)) - .willSetStateTo("CREATING")); - - wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_UPDATE_PATH)) - .inScenario("CREATE").willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBody(UPDATE_STACK_RESPONSE).withStatus(HttpStatus.SC_ACCEPTED)) - .willSetStateTo("UPDATING")); - - try { - instance.createVfModule("MTN13", "CloudOwner", "123", "vf", "v1", "genericVnfId", "vfname", "vfModuleId", - "create", null, "234", "9b339a61-69ca-465f-86b8-1c72c582b8e8", stackInputs, true, true, true, - msoRequest, new Holder<>(), new Holder<>(), new Holder<>()); - } catch (VnfException e) { - fail("createVfModule success expected, failed with exception: " + e.toString()); - } - wireMockServer.resetScenarios(); - } - - @Test - public void createVfModule2() throws Exception { - - Map<String, Object> stackInputs = new HashMap<>(); - stackInputs.put("oof_directives", "{}"); - stackInputs.put("sdnc_directives", "{}"); - stackInputs.put("user_directives", "{}"); - stackInputs.put("generic_vnf_id", "genVNFID"); - stackInputs.put("vf_module_id", "vfMODULEID"); - - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH_BY_NAME)).willReturn( - aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NOT_FOUND))); - - wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH_BY_ID)).inScenario("CREATE") - .whenScenarioStateIs("CREATING").willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBody(GET_CREATE_STACK_RESPONSE).withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlPathEqualTo(MULTICLOUD_GET_PATH_BY_ID)).inScenario("CREATE") - .whenScenarioStateIs("UPDATING").willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBody(GET_UPDATE_STACK_RESPONSE).withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)).inScenario("CREATE") - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBodyFile("MulticloudResponse_Stack_Create2.json").withStatus(HttpStatus.SC_CREATED)) - .willSetStateTo("CREATING")); - - wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_UPDATE_PATH)) - .inScenario("CREATE").willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBody(UPDATE_STACK_RESPONSE).withStatus(HttpStatus.SC_ACCEPTED)) - .willSetStateTo("UPDATING")); - - try { - instance.createVfModule("MTN13", "CloudOwner", "123", "vf", "v1", "genericVnfId", "vfname", "vfModuleId", - "create", null, "234", "9b339a61-69ca-465f-86b8-1c72c582b8e8", stackInputs, true, true, true, - msoRequest, new Holder<>(), new Holder<>(), new Holder<>()); - } catch (VnfException e) { - fail("createVfModule success expected, failed with exception: " + e.toString()); - } - wireMockServer.resetScenarios(); - } - - @Test - public void createVfModuleAlreadyExists() throws Exception { - - Map<String, Object> stackInputs = new HashMap<>(); - stackInputs.put("oof_directives", "{}"); - stackInputs.put("sdnc_directives", "{}"); - stackInputs.put("user_directives", "{}"); - stackInputs.put("generic_vnf_id", "genVNFID"); - stackInputs.put("vf_module_id", "vfMODULEID"); - - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - wireMockServer.stubFor( - get(urlEqualTo("/api/multicloud/v1/CloudOwner/MTN13/infra_workload?name=vfname")).willReturn(aResponse() - // .withHeader() - .withBodyFile("MulticloudGetStackExists.json").withStatus(HttpStatus.SC_OK))); - - try { - instance.createVfModule("MTN13", "CloudOwner", "123", "vf", "v1", "genericVnfId", "vfname", "vfModuleId", - "create", null, "234", "9b339a61-69ca-465f-86b8-1c72c582b8e8", stackInputs, true, true, true, - msoRequest, new Holder<>(), new Holder<>(), new Holder<>()); - } catch (VnfException e) { - assertTrue(e.toString().contains( - "Resource vfname already exists in owner/cloud/tenant CloudOwner/MTN13/123 with ID vfname/vfname")); - return; - } - fail("VnfAlreadyExists Exception expected!"); - } - - @Test - public void deleteVfModule() throws Exception { - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - wireMockServer.stubFor(get(urlPathEqualTo("/api/multicloud/v1/CloudOwner/MTN13/infra_workload/workload-id")) - .willReturn(aResponse().withBodyFile("MulticloudResponse_Stack.json").withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(delete(urlPathEqualTo("/api/multicloud/v1/CloudOwner/MTN13/infra_workload/workload-id")) - .willReturn(aResponse().withStatus(HttpStatus.SC_NO_CONTENT))); - - instance.deleteVfModule("MTN13", "CloudOwner", "123", "workload-id", "5aae1e49-805c-4f9f-bd78-055bf7451157", - "11420693-3f69-4c61-b3ee-9787c744e760", "customizationId", msoRequest, new Holder<>()); - } - - @Test - public void queryVfModule() throws Exception { - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - - wireMockServer.stubFor(get(urlPathEqualTo("/api/multicloud/v1/CloudOwner/MTN13/infra_workload/workload-id")) - .willReturn(aResponse().withBodyFile("MulticloudResponse_Stack.json").withStatus(HttpStatus.SC_OK))); - - instance.queryVnf("MTN13", "CloudOwner", "123", "workload-id", msoRequest, new Holder<>(), new Holder<>(), - new Holder<>(), new Holder<>()); - } - - // TODO Error Tests -} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImplTest.java deleted file mode 100644 index a68efbe130..0000000000 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfPluginAdapterImplTest.java +++ /dev/null @@ -1,166 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.vnf; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.delete; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStackVfModule_200; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStackVfModule_404; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackResponseAccess; -import java.util.HashMap; -import java.util.Map; -import javax.xml.ws.Holder; -import org.apache.http.HttpStatus; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.onap.so.adapters.vnf.exceptions.VnfException; -import org.onap.so.entity.MsoRequest; -import org.onap.so.openstack.beans.VnfRollback; -import org.springframework.beans.factory.annotation.Autowired; - -public class MsoVnfPluginAdapterImplTest extends BaseRestTestUtils { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Autowired - MsoVnfPluginAdapterImpl msoVnfPluginAdapter; - - String vnfName = "DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId"; - - @Test - public void createVfModule_ModelCustUuidIsNull() throws Exception { - expectedException.expect(VnfException.class); - MsoRequest msoRequest = getMsoRequest(); - Map<String, Object> map = new HashMap<>(); - map.put("key1", "value1"); - msoVnfPluginAdapter.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", - vnfName, "", "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId", null, map, Boolean.FALSE, - Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(), - new Holder<VnfRollback>()); - } - - @Test - public void createVfModule_ModelCustUuidIsNotFound() throws Exception { - expectedException.expect(VnfException.class); - MsoRequest msoRequest = getMsoRequest(); - Map<String, Object> map = new HashMap<>(); - map.put("key1", "value1"); - msoVnfPluginAdapter.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", - vnfName, "", "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId", - "88a6ca3ee0394ade9403f075db23167e", map, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, - new Holder<>(), new Holder<Map<String, String>>(), new Holder<VnfRollback>()); - } - - @Test - public void createVfModule_VduException() throws Exception { - expectedException.expect(VnfException.class); - MsoRequest msoRequest = getMsoRequest(); - Map<String, Object> map = new HashMap<>(); - map.put("key1", "value1"); - msoVnfPluginAdapter.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", - vnfName, "", "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId", - "9b339a61-69ca-465f-86b8-1c72c582b8e8", map, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, - new Holder<>(), new Holder<Map<String, String>>(), new Holder<VnfRollback>()); - } - - @Test - public void createVfModule_INSTANTIATED() throws Exception { - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - mockOpenStackGetStackVfModule_200(wireMockServer); - - MsoRequest msoRequest = getMsoRequest(); - Map<String, Object> map = new HashMap<>(); - map.put("key1", "value1"); - msoVnfPluginAdapter.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", - vnfName, "", "VFMOD", null, "baseVfHeatStackId", "9b339a61-69ca-465f-86b8-1c72c582b8e8", map, - Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), - new Holder<Map<String, String>>(), new Holder<VnfRollback>()); - } - - @Test - public void createVfModule_queryVduNotFoundWithVolumeGroupId() throws Exception { - expectedException.expect(VnfException.class); - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - MsoRequest msoRequest = getMsoRequest(); - Map<String, Object> map = new HashMap<>(); - map.put("key1", "value1"); - msoVnfPluginAdapter.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", - vnfName, "", "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId", - "9b339a61-69ca-465f-86b8-1c72c582b8e8", map, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, - new Holder<>(), new Holder<Map<String, String>>(), new Holder<VnfRollback>()); - } - - @Test - public void createVfModule_CreateVduException() throws Exception { - expectedException.expect(VnfException.class); - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - mockOpenStackGetStackVfModule_404(wireMockServer); - wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/volumeGroupHeatStackId")) - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK))); - MsoRequest msoRequest = getMsoRequest(); - Map<String, Object> map = new HashMap<>(); - map.put("key1", "value1"); - msoVnfPluginAdapter.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", - vnfName, "", "VFMOD", "volumeGroupHeatStackId", "baseVfHeatStackId", - "9b339a61-69ca-465f-86b8-1c72c582b8e8", map, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, - new Holder<>(), new Holder<Map<String, String>>(), new Holder<VnfRollback>()); - } - - @Test - public void deleteVfModule_QueryVduException() throws Exception { - expectedException.expect(VnfException.class); - MsoRequest msoRequest = getMsoRequest(); - msoVnfPluginAdapter.deleteVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vSAMP12", - "5aae1e49-805c-4f9f-bd78-055bf7451157", "11420693-3f69-4c61-b3ee-9787c744e760", "customizationId", - msoRequest, new Holder<Map<String, String>>()); - } - - @Test - public void deleteVfModule_DeleteVduException() throws Exception { - expectedException.expect(VnfException.class); - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - mockOpenStackGetStackVfModule_200(wireMockServer); - wireMockServer.stubFor(get(urlPathEqualTo("/mockPublicUrl/stacks/vSAMP12")) - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBodyFile("OpenstackResponse_Stack_Created_VfModule.json").withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(delete( - urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId")) - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); - MsoRequest msoRequest = getMsoRequest(); - msoVnfPluginAdapter.deleteVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vSAMP12", - "5aae1e49-805c-4f9f-bd78-055bf7451157", "11420693-3f69-4c61-b3ee-9787c744e760", "customizationId", - msoRequest, new Holder<Map<String, String>>()); - } - - private MsoRequest getMsoRequest() { - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId("12345"); - msoRequest.setServiceInstanceId("12345"); - return msoRequest; - } - -} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/QueryTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/QueryTest.java deleted file mode 100644 index 7e7c130e33..0000000000 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/QueryTest.java +++ /dev/null @@ -1,110 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.vnf; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.hasProperty; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; -import java.util.Map; -import javax.xml.ws.Holder; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.onap.so.adapters.vnf.exceptions.VnfException; -import org.onap.so.openstack.beans.HeatStatus; -import org.onap.so.openstack.beans.StackInfo; -import org.onap.so.openstack.beans.VnfStatus; -import org.onap.so.openstack.exceptions.MsoException; -import org.onap.so.openstack.exceptions.MsoOpenstackException; -import org.onap.so.openstack.utils.MsoHeatUtils; - -@RunWith(MockitoJUnitRunner.class) -public class QueryTest { - - @Mock - private MsoHeatUtils heat; - @InjectMocks - private MsoVnfAdapterImpl vnfAdapter = new MsoVnfAdapterImpl(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testQueryCreatedVnf() throws VnfException, MsoException { - StackInfo info = new StackInfo("stackName", HeatStatus.CREATED); - when(heat.queryStack(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(info); - String cloudId = "MT"; - String cloudOwner = "CloudOwner"; - String tenantId = "MSO_Test"; - String vnfName = "VNF_TEST1"; - Holder<Boolean> vnfExists = new Holder<>(); - Holder<String> vnfId = new Holder<>(); - Holder<VnfStatus> status = new Holder<>(); - Holder<Map<String, String>> outputs = new Holder<>(); - - vnfAdapter.queryVnf(cloudId, cloudOwner, tenantId, vnfName, null, vnfExists, vnfId, status, outputs); - - assertTrue(vnfExists.value); - } - - @Test - public void testQueryNotFoundVnf() throws VnfException, MsoException { - StackInfo info = new StackInfo("stackName", HeatStatus.NOTFOUND); - when(heat.queryStack(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(info); - String cloudId = "MT"; - String cloudOwner = "CloudOwner"; - String tenantId = "MSO_Test"; - String vnfName = "VNF_TEST1"; - Holder<Boolean> vnfExists = new Holder<>(); - Holder<String> vnfId = new Holder<>(); - Holder<VnfStatus> status = new Holder<>(); - Holder<Map<String, String>> outputs = new Holder<>(); - - vnfAdapter.queryVnf(cloudId, cloudOwner, tenantId, vnfName, null, vnfExists, vnfId, status, outputs); - - assertFalse(vnfExists.value); - } - - @Test() - // @Ignore // 1802 merge - public void testQueryVnfWithException() throws VnfException, MsoException { - String cloudId = "MT"; - String cloudOwner = "CloudOwner"; - String tenantId = "MSO_Test"; - String vnfName = "VNF_TEST1"; - Holder<Boolean> vnfExists = new Holder<>(); - Holder<String> vnfId = new Holder<>(); - Holder<VnfStatus> status = new Holder<>(); - Holder<Map<String, String>> outputs = new Holder<>(); - thrown.expect(VnfException.class); - thrown.expectCause(hasProperty("context", is("QueryVNF"))); - when(heat.queryStack(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) - .thenThrow(new MsoOpenstackException(1, "test messsage", "test detail")); - vnfAdapter.queryVnf(cloudId, cloudOwner, tenantId, vnfName, null, vnfExists, vnfId, status, outputs); - } -} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VnfAdapterRestTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VnfAdapterRestTest.java deleted file mode 100644 index 9655e90e46..0000000000 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VnfAdapterRestTest.java +++ /dev/null @@ -1,557 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.vnf; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.github.tomakehurst.wiremock.WireMockServer; -import org.apache.http.HttpStatus; -import org.json.JSONException; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.so.adapters.vnfrest.CreateVfModuleRequest; -import org.onap.so.adapters.vnfrest.CreateVfModuleResponse; -import org.onap.so.adapters.vnfrest.DeleteVfModuleRequest; -import org.onap.so.adapters.vnfrest.DeleteVfModuleResponse; -import org.onap.so.adapters.vnfrest.QueryVfModuleResponse; -import org.onap.so.adapters.vnfrest.RollbackVfModuleRequest; -import org.onap.so.adapters.vnfrest.RollbackVfModuleResponse; -import org.onap.so.adapters.vnfrest.UpdateVfModuleRequest; -import org.onap.so.adapters.vnfrest.UpdateVfModuleResponse; -import org.onap.so.adapters.vnfrest.VfModuleExceptionResponse; -import org.onap.so.adapters.vnfrest.VfModuleRollback; -import org.onap.so.client.policy.JettisonStyleMapperProvider; -import org.onap.so.entity.MsoRequest; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; -import java.io.File; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.patch; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; -import static com.shazam.shazamcrest.MatcherAssert.assertThat; -import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; -import static org.junit.Assert.assertEquals; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackDeletePublicUrlStackByNameAndID_204; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackDeleteStacks; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetPublicUrlStackByNameAndID_200; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStackVfModule_200; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStackVfModule_404; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStacksBaseStack_200; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStacksStackId_200; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStacksStackId_404; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStacksVUSP_404; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStacksVfModuleWithLocationHeader_200; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStacksVfModule_200; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStacksWithBody_200; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStacksWithBody_404; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStacks_404; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackPostStacks_200; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackPutStacks_200; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackResponseAccess; - -public class VnfAdapterRestTest extends BaseRestTestUtils { - - - @Autowired - private JettisonStyleMapperProvider jettisonTypeObjectMapper; - private static final String MESSAGE_ID = "62265093-277d-4388-9ba6-449838ade586-1517252396874"; - private static final String AAI_VNF_ID = "c93e0d34-5b63-45de-bbae-b0fe49dd3bd9"; - private static final String MSO_REQUEST_ID = "62265093-277d-4388-9ba6-449838ade586"; - private static final String MSO_SERVICE_INSTANCE_ID = "4147e06f-1b89-49c5-b21f-4faf8dc9805a"; - private static final String CLOUDSITE_ID = "mtn13"; - private static final String CLOUD_OWNER = "CloudOwner"; - private static final String TENANT_ID = "0422ffb57ba042c0800a29dc85ca70f8"; - private static final String VNF_TYPE = "MSOTADevInfra_vSAMP10a_Service/vSAMP10a 1"; - private static final String VNF_NAME = "MSO-DEV-VNF-1802-it3-pwt3-vSAMP10a-1XXX-Replace"; - private static final String VNF_VERSION = "1.0"; - private static final String VF_MODULE_ID = "1d48aaec-b7f3-4c24-ba4a-4e798ed3223c"; - private static final String VF_MODULE_NAME = "DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001"; - private static final String VF_MODULE_TYPE = "vSAMP10aDEV::PCM::module-2"; - private static final String MODEL_CUSTOMIZATION_UUID = "cb82ffd8-252a-11e7-93ae-92361f002671"; - private static final String BASE_VF_MODULE_ID = "3d7ff7b4-720b-4604-be0a-1974fc58ed96"; - // vfModuleParams specific variables - private static final String NETWORK_NAME = "Dev-vSAMP10a-ntwk-1802-pwt3-v6-Replace-1001"; - private static final String SERVER_NAME = "Dev-vSAMP10a-addon2-1802-pwt3-v6-Replace-1001"; - private static final String IMAGE = "ubuntu_14.04_IPv6"; - private static final String EXN_DIRECT_NET_FQDN = "direct"; - private static final String EXN_HSL_NET_FQDN = "hsl"; - private static final String AVAILABILITY_ZONE_0 = "nova"; - private static final String VF_MODULE_INDEX = "0"; - - @Test - public void testCreateVfModule() throws JSONException, JsonParseException, JsonMappingException, IOException { - - CreateVfModuleRequest request = populateCreateVfModuleRequest(); - - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - - mockOpenStackGetStackVfModule_404(wireMockServer); - - mockOpenStackPostStacks_200(wireMockServer); - - mockOpenStackGetStackVfModule_200(wireMockServer); - - mockUpdateRequestDb(wireMockServer, "62265093-277d-4388-9ba6-449838ade586"); - - headers.add("Accept", MediaType.APPLICATION_JSON); - HttpEntity<CreateVfModuleRequest> entity = new HttpEntity<CreateVfModuleRequest>(request, headers); - - ResponseEntity<CreateVfModuleResponse> response = - restTemplate.exchange(createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"), - HttpMethod.POST, entity, CreateVfModuleResponse.class); - - ResponseEntity<CreateVfModuleResponse> responseV2 = - restTemplate.exchange(createURLWithPort("/services/rest/v2/vnfs/" + AAI_VNF_ID + "/vf-modules"), - HttpMethod.POST, entity, CreateVfModuleResponse.class); - - CreateVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue( - new File("src/test/resources/__files/CreateVfModuleResponse.json"), CreateVfModuleResponse.class); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - assertThat(response.getBody(), sameBeanAs(expectedResponse)); - - assertEquals(Response.Status.OK.getStatusCode(), responseV2.getStatusCode().value()); - assertThat(responseV2.getBody(), sameBeanAs(expectedResponse)); - } - - @Test - public void testCreateVfModuleAsyncCall() throws Exception { - CreateVfModuleRequest request = populateCreateVfModuleRequest(); - request.setNotificationUrl(createURLWithPort("/mso/WorkflowMesssage")); - - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - mockOpenStackGetStackVfModule_404(wireMockServer); - mockOpenStackPostStacks_200(wireMockServer); - mockOpenStackGetStackVfModule_200(wireMockServer); - - headers.add("Accept", MediaType.APPLICATION_JSON); - HttpEntity<CreateVfModuleRequest> entity = new HttpEntity<CreateVfModuleRequest>(request, headers); - - ResponseEntity<CreateVfModuleResponse> response = - restTemplate.exchange(createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"), - HttpMethod.POST, entity, CreateVfModuleResponse.class); - - CreateVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue( - new File("src/test/resources/__files/CreateVfModuleResponse.json"), CreateVfModuleResponse.class); - - assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testCreateVfModuleWithEnableBridgeNull() - throws JSONException, JsonParseException, JsonMappingException, IOException { - - CreateVfModuleRequest request = new CreateVfModuleRequest(); - request.setBackout(true); - request.setSkipAAI(true); - request.setFailIfExists(false); - MsoRequest msoReq = new MsoRequest(); - boolean failIfExists = true; - Boolean enableBridge = null; - Map<String, Object> vfModuleParams = new HashMap<>(); - - - vfModuleParams.put("vf_module_id", VF_MODULE_ID); - vfModuleParams.put("vnf_id", AAI_VNF_ID); - vfModuleParams.put("network_name", NETWORK_NAME); - vfModuleParams.put("vnf_name", VNF_NAME); - vfModuleParams.put("environment_context", ""); - vfModuleParams.put("server_name", SERVER_NAME); - vfModuleParams.put("image", IMAGE); - vfModuleParams.put("workload_context", ""); - vfModuleParams.put("vf_module_index", VF_MODULE_INDEX); - vfModuleParams.put("vf_module_name", VF_MODULE_NAME); - vfModuleParams.put("availability_zone_0", AVAILABILITY_ZONE_0); - vfModuleParams.put("exn_direct_net_fqdn", EXN_DIRECT_NET_FQDN); - vfModuleParams.put("exn_hsl_net_fqdn", EXN_HSL_NET_FQDN); - - msoReq.setRequestId(MSO_REQUEST_ID); - msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID); - request.setMsoRequest(msoReq); - request.setCloudSiteId(CLOUDSITE_ID); - request.setTenantId(TENANT_ID); - request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID); - request.setVnfId(AAI_VNF_ID); - request.setVnfVersion(VNF_VERSION); - request.setVfModuleId(VF_MODULE_ID); - request.setVfModuleName(VF_MODULE_NAME); - request.setBaseVfModuleId(BASE_VF_MODULE_ID); - request.setFailIfExists(failIfExists); - request.setEnableBridge(enableBridge); - request.setVfModuleParams(vfModuleParams); - request.setMessageId(MESSAGE_ID); - - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - - mockOpenStackGetStackVfModule_404(wireMockServer); - - mockOpenStackPostStacks_200(wireMockServer); - - mockOpenStackGetStackVfModule_200(wireMockServer); - - mockUpdateRequestDb(wireMockServer, "62265093-277d-4388-9ba6-449838ade586"); - - - headers.add("Accept", MediaType.APPLICATION_JSON); - HttpEntity<CreateVfModuleRequest> entity = new HttpEntity<CreateVfModuleRequest>(request, headers); - - ResponseEntity<CreateVfModuleResponse> response = - restTemplate.exchange(createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"), - HttpMethod.POST, entity, CreateVfModuleResponse.class); - - CreateVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue( - new File("src/test/resources/__files/CreateVfModuleResponse.json"), CreateVfModuleResponse.class); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - assertThat(response.getBody(), sameBeanAs(expectedResponse)); - } - - @Test - public void testCreateVfModuleFail() throws IOException { - - CreateVfModuleRequest request = new CreateVfModuleRequest(); - request.setBackout(true); - request.setSkipAAI(true); - request.setFailIfExists(false); - MsoRequest msoReq = new MsoRequest(); - boolean failIfExists = true; - boolean enableBridge = false; - Map<String, Object> vfModuleParams = new HashMap<>(); - - vfModuleParams.put("vf_module_id", VF_MODULE_ID); - vfModuleParams.put("vnf_id", AAI_VNF_ID); - vfModuleParams.put("network_name", NETWORK_NAME); - vfModuleParams.put("vnf_name", VNF_NAME); - vfModuleParams.put("environment_context", ""); - vfModuleParams.put("server_name", SERVER_NAME); - vfModuleParams.put("image", IMAGE); - vfModuleParams.put("workload_context", ""); - vfModuleParams.put("vf_module_index", VF_MODULE_INDEX); - vfModuleParams.put("vf_module_name", VF_MODULE_NAME); - vfModuleParams.put("availability_zone_0", AVAILABILITY_ZONE_0); - vfModuleParams.put("exn_direct_net_fqdn", EXN_DIRECT_NET_FQDN); - vfModuleParams.put("exn_hsl_net_fqdn", EXN_HSL_NET_FQDN); - - msoReq.setRequestId(MSO_REQUEST_ID); - msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID); - request.setMsoRequest(msoReq); - request.setCloudSiteId(CLOUDSITE_ID); - request.setTenantId(TENANT_ID); - request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID); - request.setVnfId(AAI_VNF_ID); - request.setVnfType(VNF_TYPE); - request.setVnfVersion(VNF_VERSION); - request.setVfModuleId(VF_MODULE_ID); - request.setVfModuleName(VF_MODULE_NAME); - request.setVfModuleType(VF_MODULE_TYPE); - request.setBaseVfModuleStackId(BASE_VF_MODULE_ID); - request.setFailIfExists(failIfExists); - request.setEnableBridge(enableBridge); - request.setVfModuleParams(vfModuleParams); - request.setMessageId(MESSAGE_ID); - - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - - mockOpenStackGetStackVfModule_404(wireMockServer); - - mockOpenStackGetStacks_404(wireMockServer); - - mockOpenStackPostStacks_200(wireMockServer); - - mockOpenStackGetStackVfModule_200(wireMockServer); - - headers.add("Accept", MediaType.APPLICATION_JSON); - HttpEntity<CreateVfModuleRequest> entity = new HttpEntity<CreateVfModuleRequest>(request, headers); - - ResponseEntity<VfModuleExceptionResponse> response = - restTemplate.exchange(createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"), - HttpMethod.POST, entity, VfModuleExceptionResponse.class); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - - mockOpenStackGetStacksWithBody_200(wireMockServer, "DELETE_IN_PROGRESS"); - - response = restTemplate.exchange(createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"), - HttpMethod.POST, entity, VfModuleExceptionResponse.class); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - - mockOpenStackGetStacksWithBody_200(wireMockServer, "DELETE_FAILED"); - - response = restTemplate.exchange(createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"), - HttpMethod.POST, entity, VfModuleExceptionResponse.class); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - - mockOpenStackGetStacksWithBody_200(wireMockServer, "UPDATE_COMPLETE"); - - response = restTemplate.exchange(createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"), - HttpMethod.POST, entity, VfModuleExceptionResponse.class); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - - mockOpenStackGetStacksWithBody_404(wireMockServer); - - response = restTemplate.exchange(createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules"), - HttpMethod.POST, entity, VfModuleExceptionResponse.class); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - - } - - @Test - public void testDeleteVfModule() throws IOException { - - DeleteVfModuleRequest request = new DeleteVfModuleRequest(); - MsoRequest msoRequest = new MsoRequest(); - String vfModuleStackId = "stackId"; - - msoRequest.setRequestId(MSO_REQUEST_ID); - msoRequest.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID); - request.setCloudSiteId(CLOUDSITE_ID); - request.setTenantId(TENANT_ID); - request.setVfModuleId(VF_MODULE_ID); - request.setVfModuleStackId(vfModuleStackId); - request.setVnfId(AAI_VNF_ID); - request.setMsoRequest(msoRequest); - - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - - mockOpenStackPostStacks_200(wireMockServer); - - mockOpenStackGetStacksStackId_404(wireMockServer); - - mockOpenStackGetPublicUrlStackByNameAndID_200(wireMockServer, wireMockPort); - - mockOpenStackDeletePublicUrlStackByNameAndID_204(wireMockServer); - - mockUpdateRequestDb(wireMockServer, "62265093-277d-4388-9ba6-449838ade586"); - - headers.add("Accept", MediaType.APPLICATION_JSON); - HttpEntity<DeleteVfModuleRequest> entity = new HttpEntity<DeleteVfModuleRequest>(request, headers); - - ResponseEntity<DeleteVfModuleResponse> response = restTemplate.exchange( - createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_ID), - HttpMethod.DELETE, entity, DeleteVfModuleResponse.class); - - ResponseEntity<DeleteVfModuleResponse> responseV2 = restTemplate.exchange( - createURLWithPort("/services/rest/v2/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_ID), - HttpMethod.DELETE, entity, DeleteVfModuleResponse.class); - - - DeleteVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue( - new File("src/test/resources/__files/DeleteVfModuleResponse.json"), DeleteVfModuleResponse.class); - - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - assertThat(response.getBody(), sameBeanAs(expectedResponse)); - - assertEquals(Response.Status.OK.getStatusCode(), responseV2.getStatusCode().value()); - assertThat(responseV2.getBody(), sameBeanAs(expectedResponse)); - } - - @Test - public void testUpdateVfModule() throws IOException { - - UpdateVfModuleRequest request = new UpdateVfModuleRequest(); - MsoRequest msoRequest = new MsoRequest(); - String vfModuleStackId = "vfModuleStackId"; - Boolean failIfExists = false; - Boolean backout = false; - msoRequest.setRequestId(MSO_REQUEST_ID); - msoRequest.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID); - - Map<String, Object> vfModuleParams = new HashMap<>(); - - vfModuleParams.put("exn_direct_net_fqdn", EXN_DIRECT_NET_FQDN); - vfModuleParams.put("exn_hsl_net_fqdn", EXN_HSL_NET_FQDN); - - Map<String, String> vfModuleOutputs = new HashMap<String, String>(); - - vfModuleOutputs.put("output name", "output value"); - - request.setBackout(backout); - request.setCloudSiteId(CLOUDSITE_ID); - request.setFailIfExists(failIfExists); - request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID); - request.setMsoRequest(msoRequest); - request.setTenantId(TENANT_ID); - request.setVfModuleId(VF_MODULE_ID); - request.setVfModuleName(VF_MODULE_NAME); - request.setVfModuleStackId(vfModuleStackId); - request.setBackout(backout); - request.setVfModuleParams(vfModuleParams); - - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - - mockOpenStackGetStacksVfModuleWithLocationHeader_200(wireMockServer, wireMockPort); - - mockOpenStackGetStacksVfModule_200(wireMockServer, wireMockPort); - - mockOpenStackGetStacksBaseStack_200(wireMockServer, wireMockPort); - - mockOpenStackPutStacks_200(wireMockServer); - - UpdateVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue( - new File("src/test/resources/__files/UpdateVfModuleResponse.json"), UpdateVfModuleResponse.class); - expectedResponse.setVfModuleOutputs(vfModuleOutputs); - - headers.add("Accept", MediaType.APPLICATION_JSON); - HttpEntity<UpdateVfModuleRequest> entity = new HttpEntity<UpdateVfModuleRequest>(request, headers); - - ResponseEntity<UpdateVfModuleResponse> response = restTemplate.exchange( - createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_TYPE), - HttpMethod.PUT, entity, UpdateVfModuleResponse.class); - - ResponseEntity<UpdateVfModuleResponse> responseV2 = restTemplate.exchange( - createURLWithPort("/services/rest/v2/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_TYPE), - HttpMethod.PUT, entity, UpdateVfModuleResponse.class); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - assertThat(response.getBody(), sameBeanAs(expectedResponse)); - - assertEquals(Response.Status.OK.getStatusCode(), responseV2.getStatusCode().value()); - assertThat(responseV2.getBody(), sameBeanAs(expectedResponse)); - - } - - @Test - public void testRollbackVfModule() throws IOException { - - - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId(MSO_REQUEST_ID); - msoRequest.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID); - - VfModuleRollback vfModuleRollback = new VfModuleRollback(AAI_VNF_ID, VF_MODULE_ID, "StackId", false, TENANT_ID, - CLOUD_OWNER, CLOUDSITE_ID, msoRequest, "messageId"); - - RollbackVfModuleRequest request = new RollbackVfModuleRequest(); - request.setVfModuleRollback(vfModuleRollback); - - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - - mockOpenStackGetStacksStackId_200(wireMockServer, wireMockPort); - - mockOpenStackDeleteStacks(wireMockServer); - - mockOpenStackGetStacksVUSP_404(wireMockServer); - - headers.add("Accept", MediaType.APPLICATION_JSON); - HttpEntity<RollbackVfModuleRequest> entity = new HttpEntity<RollbackVfModuleRequest>(request, headers); - - ResponseEntity<RollbackVfModuleResponse> response = restTemplate.exchange( - createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_ID + "/rollback"), - HttpMethod.DELETE, entity, RollbackVfModuleResponse.class); - - RollbackVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue( - new File("src/test/resources/__files/RollbackVfModuleResponse.json"), RollbackVfModuleResponse.class); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - assertThat(response.getBody(), sameBeanAs(expectedResponse)); - - } - - @Ignore - @Test - public void testQueryVfModule() throws IOException { - - String testUrl = createURLWithPort("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_ID); - String testUri = UriBuilder.fromPath("/services/rest/v1/vnfs/" + AAI_VNF_ID + "/vf-modules/" + VF_MODULE_ID) - .host("localhost").port(wireMockPort).scheme("http") - // .queryParam("cloudSiteId", CLOUDSITE_ID).queryParam("tenantId", TENANT_ID) - .build().toString(); - System.out.println(testUri); - - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - - - headers.add("Accept", MediaType.APPLICATION_JSON); - // HttpEntity entity = new HttpEntity(null, headers); - ResponseEntity<QueryVfModuleResponse> response = - restTemplate.getForEntity(testUri, QueryVfModuleResponse.class); - // System.out.println(response); - - QueryVfModuleResponse expectedResponse = jettisonTypeObjectMapper.getMapper().readValue( - new File("src/test/resources/__files/QueryVfModuleResponse.json"), QueryVfModuleResponse.class); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - assertThat(response.getBody(), sameBeanAs(expectedResponse)); - } - - private CreateVfModuleRequest populateCreateVfModuleRequest() { - CreateVfModuleRequest request = new CreateVfModuleRequest(); - request.setBackout(true); - request.setSkipAAI(true); - request.setFailIfExists(false); - MsoRequest msoReq = new MsoRequest(); - boolean failIfExists = true; - boolean enableBridge = false; - Map<String, Object> vfModuleParams = new HashMap<>(); - - vfModuleParams.put("vf_module_id", VF_MODULE_ID); - vfModuleParams.put("vnf_id", AAI_VNF_ID); - vfModuleParams.put("network_name", NETWORK_NAME); - vfModuleParams.put("vnf_name", VNF_NAME); - vfModuleParams.put("environment_context", ""); - vfModuleParams.put("server_name", SERVER_NAME); - vfModuleParams.put("image", IMAGE); - vfModuleParams.put("workload_context", ""); - vfModuleParams.put("vf_module_index", VF_MODULE_INDEX); - vfModuleParams.put("vf_module_name", VF_MODULE_NAME); - vfModuleParams.put("availability_zone_0", AVAILABILITY_ZONE_0); - vfModuleParams.put("exn_direct_net_fqdn", EXN_DIRECT_NET_FQDN); - vfModuleParams.put("exn_hsl_net_fqdn", EXN_HSL_NET_FQDN); - - msoReq.setRequestId(MSO_REQUEST_ID); - msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID); - request.setMsoRequest(msoReq); - request.setCloudSiteId(CLOUDSITE_ID); - request.setTenantId(TENANT_ID); - request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID); - request.setVnfId(AAI_VNF_ID); - request.setVnfType(VNF_TYPE); - request.setVnfVersion(VNF_VERSION); - request.setVfModuleId(VF_MODULE_ID); - request.setVfModuleName(VF_MODULE_NAME); - request.setVfModuleType(VF_MODULE_TYPE); - request.setBaseVfModuleId(BASE_VF_MODULE_ID); - request.setFailIfExists(failIfExists); - request.setEnableBridge(enableBridge); - request.setVfModuleParams(vfModuleParams); - request.setMessageId(MESSAGE_ID); - - return request; - } - - public static void mockUpdateRequestDb(WireMockServer wireMockServer, String requestId) throws IOException { - wireMockServer.stubFor(patch(urlPathEqualTo("/infraActiveRequests/" + requestId)) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK))); - } -} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeAdapterRestTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeAdapterRestTest.java deleted file mode 100644 index c2e2b567f1..0000000000 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeAdapterRestTest.java +++ /dev/null @@ -1,194 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.vnf; - -import org.apache.http.HttpStatus; -import org.junit.Test; -import org.onap.so.adapters.vnfrest.CreateVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.CreateVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.DeleteVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.DeleteVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.QueryVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.RollbackVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.RollbackVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.UpdateVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.UpdateVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.VolumeGroupExceptionResponse; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; -import java.io.IOException; -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.patch; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; -import static org.junit.Assert.assertEquals; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStackVfModule_200; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStackWithBody_200; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStacksWithBody_200; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackPostStacks_200; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackPutStack; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackResponseAccess; - -public class VolumeAdapterRestTest extends VolumeGroupAdapterCommon { - - @Test - public void testCreateVNFVolumes() throws IOException { - - wireMockServer.stubFor(patch(urlPathEqualTo("/infraActiveRequests/62265093-277d-4388-9ba6-449838ade586")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK))); - - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - mockOpenStackPostStacks_200(wireMockServer); - mockOpenStackGetStackVfModule_200(wireMockServer); - CreateVolumeGroupRequest request = buildCreateVfModuleRequest(); - - HttpEntity<CreateVolumeGroupRequest> entity = new HttpEntity<>(request, headers); - ResponseEntity<CreateVolumeGroupResponse> response = - restTemplate.exchange(createURLWithPort("/services/rest/v1/volume-groups"), HttpMethod.POST, entity, - CreateVolumeGroupResponse.class); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testCreateVNFVolumesAsync() throws IOException { - - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - mockOpenStackPostStacks_200(wireMockServer); - mockOpenStackGetStackVfModule_200(wireMockServer); - CreateVolumeGroupRequest request = buildCreateVfModuleRequest(); - request.setNotificationUrl("http://localhost:8080"); - - HttpEntity<CreateVolumeGroupRequest> entity = new HttpEntity<>(request, headers); - ResponseEntity<CreateVolumeGroupResponse> response = - restTemplate.exchange(createURLWithPort("/services/rest/v1/volume-groups"), HttpMethod.POST, entity, - CreateVolumeGroupResponse.class); - assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testDeleteVNFVolumes() throws IOException { - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - DeleteVolumeGroupRequest request = buildDeleteVolumeGroupRequest(); - HttpEntity<DeleteVolumeGroupRequest> entity = new HttpEntity<>(request, headers); - ResponseEntity<DeleteVolumeGroupResponse> response = - restTemplate.exchange(createURLWithPort("/services/rest/v1/volume-groups/" + VOLUME_GROUP_ID), - HttpMethod.DELETE, entity, DeleteVolumeGroupResponse.class); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testDeleteVNFVolumesAsync() throws IOException { - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - DeleteVolumeGroupRequest request = buildDeleteVolumeGroupRequest(); - request.setNotificationUrl("http://localhost:8080"); - HttpEntity<DeleteVolumeGroupRequest> entity = new HttpEntity<>(request, headers); - ResponseEntity<DeleteVolumeGroupResponse> response = - restTemplate.exchange(createURLWithPort("/services/rest/v1/volume-groups/" + VOLUME_GROUP_ID), - HttpMethod.DELETE, entity, DeleteVolumeGroupResponse.class); - assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testRollbackVNFVolumes() throws IOException { - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - RollbackVolumeGroupRequest request = buildRollbackVolumeGroupRequest(); - HttpEntity<RollbackVolumeGroupRequest> entity = new HttpEntity<>(request, headers); - ResponseEntity<RollbackVolumeGroupResponse> response = restTemplate.exchange( - createURLWithPort("/services/rest/v1/volume-groups/" + VOLUME_GROUP_ID + "/rollback"), - HttpMethod.DELETE, entity, RollbackVolumeGroupResponse.class); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testRollbackVNFVolumesAsync() throws IOException { - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - RollbackVolumeGroupRequest request = buildRollbackVolumeGroupRequest(); - request.setNotificationUrl("http://localhost:8080"); - HttpEntity<RollbackVolumeGroupRequest> entity = new HttpEntity<>(request, headers); - ResponseEntity<RollbackVolumeGroupResponse> response = restTemplate.exchange( - createURLWithPort("/services/rest/v1/volume-groups/" + VOLUME_GROUP_ID + "/rollback"), - HttpMethod.DELETE, entity, RollbackVolumeGroupResponse.class); - assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testQueryVNFVolumes() throws IOException { - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - mockOpenStackGetStacksWithBody_200(wireMockServer, "UPDATE_COMPLETE"); - javax.ws.rs.core.UriBuilder builder = UriBuilder.fromPath("/services/rest/v1/volume-groups/" + VOLUME_GROUP_ID); - builder.queryParam("cloudSiteId", CLOUDSITE_ID).queryParam("tenantId", TENANT_ID) - .queryParam("volumeGroupStackId", VOUME_GROUP_NAME).queryParam("skipAAI", true) - .queryParam("msoRequest.requestId", MSO_REQUEST_ID) - .queryParam("msoRequest.serviceInstanceId", MSO_SERVICE_INSTANCE_ID); - - ResponseEntity<QueryVolumeGroupResponse> response = restTemplate.exchange( - createURLWithPort(builder.build().toString()), HttpMethod.GET, null, QueryVolumeGroupResponse.class); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testQueryVNFVolumesError() throws IOException { - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - mockOpenStackGetStacksWithBody_200(wireMockServer, "UPDATE_COMPLETE"); - javax.ws.rs.core.UriBuilder builder = UriBuilder.fromPath("/services/rest/v1/volume-groups/" + VOLUME_GROUP_ID); - builder.queryParam("tenantId", TENANT_ID).queryParam("volumeGroupStackId", VOUME_GROUP_NAME) - .queryParam("skipAAI", true).queryParam("msoRequest.requestId", MSO_REQUEST_ID) - .queryParam("msoRequest.serviceInstanceId", MSO_SERVICE_INSTANCE_ID); - - ResponseEntity<VolumeGroupExceptionResponse> response = - restTemplate.exchange(createURLWithPort(builder.build().toString()), HttpMethod.GET, null, - VolumeGroupExceptionResponse.class); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testUpdateVNFVolumes() throws IOException { - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - mockOpenStackGetStacksWithBody_200(wireMockServer, "CREATE_COMPLETE"); - mockOpenStackPutStack(wireMockServer, VOUME_GROUP_NAME + "/stackId", 200); - mockOpenStackGetStackWithBody_200(wireMockServer, "UPDATE_COMPLETE"); - UpdateVolumeGroupRequest request = buildUpdateVolumeGroupRequest(); - HttpEntity<UpdateVolumeGroupRequest> entity = new HttpEntity<>(request, headers); - ResponseEntity<UpdateVolumeGroupResponse> response = - restTemplate.exchange(createURLWithPort("/services/rest/v1/volume-groups/" + VOLUME_GROUP_ID), - HttpMethod.PUT, entity, UpdateVolumeGroupResponse.class); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testUpdateVNFVolumesAsync() throws IOException { - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - mockOpenStackGetStacksWithBody_200(wireMockServer, "CREATE_COMPLETE"); - mockOpenStackPutStack(wireMockServer, VOUME_GROUP_NAME + "/stackId", 200); - mockOpenStackGetStackWithBody_200(wireMockServer, "UPDATE_COMPLETE"); - UpdateVolumeGroupRequest request = buildUpdateVolumeGroupRequest(); - request.setNotificationUrl("http://localhost:8080"); - HttpEntity<UpdateVolumeGroupRequest> entity = new HttpEntity<>(request, headers); - ResponseEntity<UpdateVolumeGroupResponse> response = - restTemplate.exchange(createURLWithPort("/services/rest/v1/volume-groups/" + VOLUME_GROUP_ID), - HttpMethod.PUT, entity, UpdateVolumeGroupResponse.class); - assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); - } - - -} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2Test.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2Test.java deleted file mode 100644 index 6fd9f02cfe..0000000000 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2Test.java +++ /dev/null @@ -1,190 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.vnf; - -import org.apache.http.HttpStatus; -import org.junit.Test; -import org.onap.so.adapters.vnfrest.CreateVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.CreateVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.DeleteVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.DeleteVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.QueryVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.RollbackVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.RollbackVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.UpdateVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.UpdateVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.VolumeGroupExceptionResponse; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; -import java.io.IOException; -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.patch; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; -import static org.junit.Assert.assertEquals; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStackVfModule_200; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStackWithBody_200; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackGetStacksWithBody_200; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackPostStacks_200; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackPutStack; -import static org.onap.so.bpmn.mock.StubOpenStack.mockOpenStackResponseAccess; - -public class VolumeAdapterRestV2Test extends VolumeGroupAdapterCommon { - - @Test - public void testCreateVNFVolumes() throws IOException { - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - mockOpenStackPostStacks_200(wireMockServer); - mockOpenStackGetStackVfModule_200(wireMockServer); - wireMockServer.stubFor(patch(urlPathEqualTo("/infraActiveRequests/62265093-277d-4388-9ba6-449838ade586")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK))); - - CreateVolumeGroupRequest request = buildCreateVfModuleRequest(); - - HttpEntity<CreateVolumeGroupRequest> entity = new HttpEntity<>(request, headers); - ResponseEntity<CreateVolumeGroupResponse> response = - restTemplate.exchange(createURLWithPort("/services/rest/v2/volume-groups"), HttpMethod.POST, entity, - CreateVolumeGroupResponse.class); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testCreateVNFVolumesAsync() throws IOException { - - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - mockOpenStackPostStacks_200(wireMockServer); - mockOpenStackGetStackVfModule_200(wireMockServer); - CreateVolumeGroupRequest request = buildCreateVfModuleRequest(); - request.setNotificationUrl("http://localhost:8080"); - HttpEntity<CreateVolumeGroupRequest> entity = new HttpEntity<>(request, headers); - ResponseEntity<CreateVolumeGroupResponse> response = - restTemplate.exchange(createURLWithPort("/services/rest/v2/volume-groups"), HttpMethod.POST, entity, - CreateVolumeGroupResponse.class); - assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testDeleteVNFVolumes() throws IOException { - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - DeleteVolumeGroupRequest request = buildDeleteVolumeGroupRequest(); - HttpEntity<DeleteVolumeGroupRequest> entity = new HttpEntity<>(request, headers); - ResponseEntity<DeleteVolumeGroupResponse> response = - restTemplate.exchange(createURLWithPort("/services/rest/v2/volume-groups/" + VOLUME_GROUP_ID), - HttpMethod.DELETE, entity, DeleteVolumeGroupResponse.class); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testDeleteVNFVolumesAsync() throws IOException { - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - DeleteVolumeGroupRequest request = buildDeleteVolumeGroupRequest(); - request.setNotificationUrl("http://localhost:8080"); - HttpEntity<DeleteVolumeGroupRequest> entity = new HttpEntity<>(request, headers); - ResponseEntity<DeleteVolumeGroupResponse> response = - restTemplate.exchange(createURLWithPort("/services/rest/v2/volume-groups/" + VOLUME_GROUP_ID), - HttpMethod.DELETE, entity, DeleteVolumeGroupResponse.class); - assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testRollbackVNFVolumes() throws IOException { - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - RollbackVolumeGroupRequest request = buildRollbackVolumeGroupRequest(); - HttpEntity<RollbackVolumeGroupRequest> entity = new HttpEntity<>(request, headers); - ResponseEntity<RollbackVolumeGroupResponse> response = restTemplate.exchange( - createURLWithPort("/services/rest/v2/volume-groups/" + VOLUME_GROUP_ID + "/rollback"), - HttpMethod.DELETE, entity, RollbackVolumeGroupResponse.class); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testRollbackVNFVolumesAsync() throws IOException { - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - RollbackVolumeGroupRequest request = buildRollbackVolumeGroupRequest(); - request.setNotificationUrl("http://localhost:8080"); - HttpEntity<RollbackVolumeGroupRequest> entity = new HttpEntity<>(request, headers); - ResponseEntity<RollbackVolumeGroupResponse> response = restTemplate.exchange( - createURLWithPort("/services/rest/v2/volume-groups/" + VOLUME_GROUP_ID + "/rollback"), - HttpMethod.DELETE, entity, RollbackVolumeGroupResponse.class); - assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testQueryVNFVolumes() throws IOException { - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - mockOpenStackGetStacksWithBody_200(wireMockServer, "UPDATE_COMPLETE"); - javax.ws.rs.core.UriBuilder builder = UriBuilder.fromPath("/services/rest/v2/volume-groups/" + VOLUME_GROUP_ID); - builder.queryParam("cloudSiteId", CLOUDSITE_ID).queryParam("tenantId", TENANT_ID) - .queryParam("volumeGroupStackId", VOUME_GROUP_NAME).queryParam("skipAAI", true) - .queryParam("msoRequest.requestId", MSO_REQUEST_ID) - .queryParam("msoRequest.serviceInstanceId", MSO_SERVICE_INSTANCE_ID); - - ResponseEntity<QueryVolumeGroupResponse> response = restTemplate.exchange( - createURLWithPort(builder.build().toString()), HttpMethod.GET, null, QueryVolumeGroupResponse.class); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testQueryVNFVolumesError() throws IOException { - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - mockOpenStackGetStacksWithBody_200(wireMockServer, "UPDATE_COMPLETE"); - javax.ws.rs.core.UriBuilder builder = UriBuilder.fromPath("/services/rest/v2/volume-groups/" + VOLUME_GROUP_ID); - builder.queryParam("tenantId", TENANT_ID).queryParam("volumeGroupStackId", VOUME_GROUP_NAME) - .queryParam("skipAAI", true).queryParam("msoRequest.requestId", MSO_REQUEST_ID) - .queryParam("msoRequest.serviceInstanceId", MSO_SERVICE_INSTANCE_ID); - - ResponseEntity<VolumeGroupExceptionResponse> response = - restTemplate.exchange(createURLWithPort(builder.build().toString()), HttpMethod.GET, null, - VolumeGroupExceptionResponse.class); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testUpdateVNFVolumes() throws IOException { - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - mockOpenStackGetStacksWithBody_200(wireMockServer, "CREATE_COMPLETE"); - mockOpenStackPutStack(wireMockServer, VOUME_GROUP_NAME + "/stackId", 200); - mockOpenStackGetStackWithBody_200(wireMockServer, "UPDATE_COMPLETE"); - UpdateVolumeGroupRequest request = buildUpdateVolumeGroupRequest(); - HttpEntity<UpdateVolumeGroupRequest> entity = new HttpEntity<>(request, headers); - ResponseEntity<UpdateVolumeGroupResponse> response = - restTemplate.exchange(createURLWithPort("/services/rest/v2/volume-groups/" + VOLUME_GROUP_ID), - HttpMethod.PUT, entity, UpdateVolumeGroupResponse.class); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void testUpdateVNFVolumesAsync() throws IOException { - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - mockOpenStackGetStacksWithBody_200(wireMockServer, "CREATE_COMPLETE"); - mockOpenStackPutStack(wireMockServer, VOUME_GROUP_NAME + "/stackId", 200); - mockOpenStackGetStackWithBody_200(wireMockServer, "UPDATE_COMPLETE"); - UpdateVolumeGroupRequest request = buildUpdateVolumeGroupRequest(); - request.setNotificationUrl("http://localhost:8080"); - HttpEntity<UpdateVolumeGroupRequest> entity = new HttpEntity<>(request, headers); - ResponseEntity<UpdateVolumeGroupResponse> response = - restTemplate.exchange(createURLWithPort("/services/rest/v2/volume-groups/" + VOLUME_GROUP_ID), - HttpMethod.PUT, entity, UpdateVolumeGroupResponse.class); - assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); - } -} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeGroupAdapterCommon.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeGroupAdapterCommon.java deleted file mode 100644 index 14fa1df6c9..0000000000 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/VolumeGroupAdapterCommon.java +++ /dev/null @@ -1,129 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.vnf; - -import org.onap.so.adapters.vnfrest.CreateVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.DeleteVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.RollbackVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.UpdateVolumeGroupRequest; -import org.onap.so.adapters.vnfrest.VolumeGroupRollback; -import org.onap.so.entity.MsoRequest; -import java.util.HashMap; -import java.util.Map; - -public class VolumeGroupAdapterCommon extends BaseRestTestUtils { - - - - protected static final String MSO_REQUEST_ID = "62265093-277d-4388-9ba6-449838ade586"; - protected static final String MSO_SERVICE_INSTANCE_ID = "4147e06f-1b89-49c5-b21f-4faf8dc9805a"; - protected static final String CLOUDSITE_ID = "mtn13"; - protected static final String TENANT_ID = "0422ffb57ba042c0800a29dc85ca70f8"; - protected static final String VOUME_GROUP_NAME = "DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001"; - protected static final String VOLUME_GROUP_ID = "0422ffb57ba042c0800a29dc85ca70v1"; - protected static final String VNF_TYPE = "TestVnfType"; - protected static final String VNF_VERSION = "1.0"; - protected static final String VF_MODULE_TYPE = "TestModule-0"; - protected static final String MODEL_CUSTOMIZATION_UUID = "9b339a61-69ca-465f-86b8-1c72c582b8e8"; - - protected UpdateVolumeGroupRequest buildUpdateVolumeGroupRequest() { - UpdateVolumeGroupRequest request = new UpdateVolumeGroupRequest(); - request.setCloudSiteId(CLOUDSITE_ID); - request.setTenantId(TENANT_ID); - request.setVolumeGroupId(VOLUME_GROUP_ID); - request.setVnfType(VNF_TYPE); - request.setVnfVersion(VNF_VERSION); - request.setVfModuleType(VF_MODULE_TYPE); - request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID); - request.setSkipAAI(true); - request.setVolumeGroupStackId(VOUME_GROUP_NAME); - Map<String, Object> volumeGroupParams = getVolumeGroupParamsMap(); - request.setVolumeGroupParams(volumeGroupParams); - MsoRequest msoReq = getMsoRequest(); - request.setMsoRequest(msoReq); - return request; - } - - protected RollbackVolumeGroupRequest buildRollbackVolumeGroupRequest() { - RollbackVolumeGroupRequest request = new RollbackVolumeGroupRequest(); - VolumeGroupRollback volumeGroupRollback = new VolumeGroupRollback(); - volumeGroupRollback.setCloudSiteId(CLOUDSITE_ID); - volumeGroupRollback.setMessageId(MSO_REQUEST_ID); - volumeGroupRollback.setTenantId(TENANT_ID); - MsoRequest msoReq = getMsoRequest(); - volumeGroupRollback.setVolumeGroupCreated(true); - volumeGroupRollback.setVolumeGroupId(VOLUME_GROUP_ID); - volumeGroupRollback.setVolumeGroupStackId(VOLUME_GROUP_ID); - volumeGroupRollback.setMsoRequest(msoReq); - request.setVolumeGroupRollback(volumeGroupRollback); - return request; - } - - protected DeleteVolumeGroupRequest buildDeleteVolumeGroupRequest() { - DeleteVolumeGroupRequest request = new DeleteVolumeGroupRequest(); - request.setCloudSiteId(CLOUDSITE_ID); - request.setTenantId(TENANT_ID); - request.setVolumeGroupStackId("testStackId"); - request.setVolumeGroupId(VOLUME_GROUP_ID); - MsoRequest msoReq = getMsoRequest(); - request.setMsoRequest(msoReq); - return request; - } - - protected CreateVolumeGroupRequest buildCreateVfModuleRequest() { - CreateVolumeGroupRequest request = new CreateVolumeGroupRequest(); - request.setCloudSiteId(CLOUDSITE_ID); - request.setTenantId(TENANT_ID); - request.setVolumeGroupName(VOUME_GROUP_NAME); - request.setVolumeGroupId(VOLUME_GROUP_ID); - request.setVnfType(VNF_TYPE); - request.setVnfVersion(VNF_VERSION); - request.setVfModuleType(VF_MODULE_TYPE); - request.setModelCustomizationUuid(MODEL_CUSTOMIZATION_UUID); - request.setSkipAAI(true); - request.setFailIfExists(false); - request.setFailIfExists(true); - request.setEnableBridge(false); - request.setSuppressBackout(true); - Map<String, Object> volumeGroupParams = getVolumeGroupParamsMap(); - request.setVolumeGroupParams(volumeGroupParams); - MsoRequest msoReq = getMsoRequest(); - request.setMsoRequest(msoReq); - - return request; - } - - private Map<String, Object> getVolumeGroupParamsMap() { - Map<String, Object> volumeGroupParams = new HashMap<>(); - volumeGroupParams.put("fsb_volume_type_0", "volume_type"); - volumeGroupParams.put("fsb_volume_image_name_1", "vol_img_1"); - volumeGroupParams.put("fsb_volume_image_name_0", "vol_img_0"); - volumeGroupParams.put("fsb_volume_size_0", "100"); - return volumeGroupParams; - } - - private MsoRequest getMsoRequest() { - MsoRequest msoReq = new MsoRequest(); - msoReq.setRequestId(MSO_REQUEST_ID); - msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID); - return msoReq; - } -} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy deleted file mode 100644 index e8f842471c..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy +++ /dev/null @@ -1,458 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.bpmn.common.scripts - -import org.onap.so.logger.LoggingAnchor -import org.onap.so.client.HttpClientFactory -import org.onap.logging.filter.base.ErrorCode - -import javax.ws.rs.core.Response -import org.apache.commons.lang3.* -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.delegate.DelegateExecution -import org.onap.so.bpmn.core.UrnPropertiesReader -import org.onap.so.client.HttpClient -import org.onap.so.logger.MessageEnum -import org.slf4j.Logger -import org.slf4j.LoggerFactory -import org.onap.logging.filter.base.ONAPComponents; -import java.util.UUID -import org.onap.so.utils.Components - - -@Deprecated //Use vnfAdapterRestV2 -class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { - private static final Logger logger = LoggerFactory.getLogger( VnfAdapterRestV1.class); - - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - // VNF Response Processing - public void preProcessRequest (DelegateExecution execution) { - def method = getClass().getSimpleName() + '.preProcessRequest(' + - 'execution=' + execution.getId() + - ')' - logger.trace('Entered ' + method) - - def prefix="VNFREST_" - execution.setVariable("prefix", prefix) - setSuccessIndicator(execution, false) - - try { - String request = validateRequest(execution, "mso-request-id") - - // Get the request type (the name of the root element) from the request - - Node root = new XmlParser().parseText(request) - String requestType = root.name() - execution.setVariable(prefix + 'requestType', requestType) - logger.debug(getProcessKey(execution) + ': ' + prefix + 'requestType = ' + requestType) - - logger.debug('VnfAdapterRestV1, request: ' + request) - // Get the messageId from the request - - String messageId = getChildText(root, 'messageId') - - if ('rollbackVolumeGroupRequest'.equals(requestType)) { - messageId = getMessageIdForVolumeGroupRollback(root) - } - - if (messageId == null || messageId.isEmpty()) { - String msg = getProcessKey(execution) + ': no messageId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - execution.setVariable('VNFAResponse_CORRELATOR', messageId) - logger.debug(getProcessKey(execution) + ': VNFAResponse_CORRELATOR = ' + messageId) - - // Get the notificationUrl from the request - - String notificationUrl = getChildText(root, 'notificationUrl') - - if (notificationUrl == null || notificationUrl.isEmpty()) { - String msg = getProcessKey(execution) + ': no notificationUrl in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - execution.setVariable(prefix + 'notificationUrl', notificationUrl) - logger.debug(getProcessKey(execution) + ': ' + prefix + 'notificationUrl = ' + notificationUrl) - - // Determine the VnfAdapter endpoint - - String vnfAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.vnf.rest.endpoint", execution) - - if (vnfAdapterEndpoint == null || vnfAdapterEndpoint.isEmpty()) { - String msg = getProcessKey(execution) + ': mso:adapters:vnf:rest:endpoint URN mapping is not defined' - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - while (vnfAdapterEndpoint.endsWith('/')) { - vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, vnfAdapterEndpoint.length()-1) - } - - String vnfAdapterMethod = null - String vnfAdapterUrl = null - String vnfAdapterRequest = request - - if ('createVfModuleRequest'.equals(requestType)) { - String vnfId = getChildText(root, 'vnfId') - - if (vnfId == null || vnfId.isEmpty()) { - String msg = getProcessKey(execution) + ': no vnfId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - vnfAdapterMethod = 'POST' - vnfAdapterUrl = vnfAdapterEndpoint + '/' + URLEncoder.encode(vnfId, 'UTF-8') + '/vf-modules' - - } else if ('updateVfModuleRequest'.equals(requestType)) { - String vnfId = getChildText(root, 'vnfId') - - if (vnfId == null || vnfId.isEmpty()) { - String msg = getProcessKey(execution) + ': no vnfId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - String vfModuleId = getChildText(root, 'vfModuleId') - - if (vfModuleId == null || vfModuleId.isEmpty()) { - String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - vnfAdapterMethod = 'PUT' - vnfAdapterUrl = vnfAdapterEndpoint + '/' + URLEncoder.encode(vnfId, 'UTF-8') + - '/vf-modules/' + URLEncoder.encode(vfModuleId, 'UTF-8') - - } else if ('deleteVfModuleRequest'.equals(requestType)) { - String vnfId = getChildText(root, 'vnfId') - - if (vnfId == null || vnfId.isEmpty()) { - String msg = getProcessKey(execution) + ': no vnfId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - String vfModuleId = getChildText(root, 'vfModuleId') - - if (vfModuleId == null || vfModuleId.isEmpty()) { - String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - vnfAdapterMethod = 'DELETE' - vnfAdapterUrl = vnfAdapterEndpoint + '/' + URLEncoder.encode(vnfId, 'UTF-8') + - '/vf-modules/' + URLEncoder.encode(vfModuleId, 'UTF-8') - - } else if ('rollbackVfModuleRequest'.equals(requestType)) { - Node vfModuleRollbackNode = getChild(root, 'vfModuleRollback') - - if (vfModuleRollbackNode == null) { - String msg = getProcessKey(execution) + ': no vfModuleRollback in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - String vnfId = getChildText(vfModuleRollbackNode, 'vnfId') - - if (vnfId == null || vnfId.isEmpty()) { - String msg = getProcessKey(execution) + ': no vnfId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - String vfModuleId = getChildText(vfModuleRollbackNode, 'vfModuleId') - - if (vfModuleId == null || vfModuleId.isEmpty()) { - String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - vnfAdapterMethod = 'DELETE' - vnfAdapterUrl = vnfAdapterEndpoint + '/' + URLEncoder.encode(vnfId, 'UTF-8') + - '/vf-modules/' + URLEncoder.encode(vfModuleId, 'UTF-8') + '/rollback' - - } else if ('createVolumeGroupRequest'.equals(requestType)) { - vnfAdapterMethod = 'POST' - if (vnfAdapterEndpoint.endsWith('v1/vnfs')) { - vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, (vnfAdapterEndpoint.length()-'/vnfs'.length())) - } - vnfAdapterUrl = vnfAdapterEndpoint + '/volume-groups' - - } else if ('updateVolumeGroupRequest'.equals(requestType)) { - String volumeGroupId = getChildText(root, 'volumeGroupId') - - if (volumeGroupId == null || volumeGroupId.isEmpty()) { - String msg = getProcessKey(execution) + ': no volumeGroupId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - vnfAdapterMethod = 'PUT' - if (vnfAdapterEndpoint.endsWith('v1/vnfs')) { - vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, (vnfAdapterEndpoint.length()-'/vnfs'.length())) - } - vnfAdapterUrl = vnfAdapterEndpoint + '/volume-groups/' + URLEncoder.encode(volumeGroupId, 'UTF-8') - - } else if ('deleteVolumeGroupRequest'.equals(requestType)) { - String volumeGroupId = getChildText(root, 'volumeGroupId') - - if (volumeGroupId == null || volumeGroupId.isEmpty()) { - String msg = getProcessKey(execution) + ': no volumeGroupId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - vnfAdapterMethod = 'DELETE' - if (vnfAdapterEndpoint.endsWith('v1/vnfs')) { - vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, (vnfAdapterEndpoint.length()-'/vnfs'.length())) - } - vnfAdapterUrl = vnfAdapterEndpoint + '/volume-groups/' + URLEncoder.encode(volumeGroupId, 'UTF-8') - - } else if ('rollbackVolumeGroupRequest'.equals(requestType)) { - String volumeGroupId = getVolumeGroupIdFromRollbackRequest(root) - - if (volumeGroupId == null || volumeGroupId.isEmpty()) { - String msg = getProcessKey(execution) + ': no volumeGroupId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - vnfAdapterMethod = 'DELETE' - if (vnfAdapterEndpoint.endsWith('v1/vnfs')) { - vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, (vnfAdapterEndpoint.length()-'/vnfs'.length())) - } - vnfAdapterUrl = vnfAdapterEndpoint + '/volume-groups/' + URLEncoder.encode(volumeGroupId, 'UTF-8') + '/rollback' - - } else { - String msg = getProcessKey(execution) + ': Unsupported request type: ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - execution.setVariable(prefix + 'vnfAdapterMethod', vnfAdapterMethod) - logger.debug(getProcessKey(execution) + ': ' + prefix + 'vnfAdapterMethod = ' + vnfAdapterMethod) - execution.setVariable(prefix + 'vnfAdapterUrl', vnfAdapterUrl) - logger.debug(getProcessKey(execution) + ': ' + prefix + 'vnfAdapterUrl = ' + vnfAdapterUrl) - execution.setVariable(prefix + 'vnfAdapterRequest', vnfAdapterRequest) - logger.debug(getProcessKey(execution) + ': ' + prefix + 'vnfAdapterRequest = \n' + vnfAdapterRequest) - - // Get the Basic Auth credentials for the VnfAdapter - - String basicAuthValue = UrnPropertiesReader.getVariable("mso.adapters.po.auth", execution) - - if (basicAuthValue == null || basicAuthValue.isEmpty()) { - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined", "BPMN", - ErrorCode.UnknownError.getValue()); - } else { - try { - def encodedString = utils.getBasicAuth(basicAuthValue, UrnPropertiesReader.getVariable("mso.msoKey", execution)) - execution.setVariable(prefix + 'basicAuthHeaderValue', encodedString) - } catch (IOException ex) { - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - getProcessKey(execution) + ": Unable to encode BasicAuth credentials for VnfAdapter", - "BPMN", ErrorCode.UnknownError.getValue(), ex); - } - } - - } catch (BpmnError e) { - logger.debug(" Rethrowing MSOWorkflowException") - throw e - } catch (Exception e) { - String msg = 'Caught exception in ' + method + ": " + e - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - logger.debug(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - } - - public String getVolumeGroupIdFromRollbackRequest(Node root) { - return root.'volumeGroupRollback'.'volumeGroupId'.text() - } - - public String getMessageIdForVolumeGroupRollback(Node root) { - return root.'volumeGroupRollback'.'messageId'.text() - } - - /** - * This method is used instead of an HTTP Connector task because the - * connector does not allow DELETE with a body. - */ - public void sendRequestToVnfAdapter(DelegateExecution execution) { - def method = getClass().getSimpleName() + '.sendRequestToVnfAdapter(' + - 'execution=' + execution.getId() + - ')' - logger.trace('Entered ' + method) - - String prefix = execution.getVariable('prefix') - - try { - String vnfAdapterMethod = execution.getVariable(prefix + 'vnfAdapterMethod') - String vnfAdapterUrl = execution.getVariable(prefix + 'vnfAdapterUrl') - String vnfAdapterRequest = execution.getVariable(prefix + 'vnfAdapterRequest') - - URL url = new URL(vnfAdapterUrl); - - HttpClient httpClient = new HttpClientFactory().newXmlClient(url, ONAPComponents.VNF_ADAPTER) - httpClient.addAdditionalHeader("Authorization", execution.getVariable(prefix + "basicAuthHeaderValue")) - - httpClient.addAdditionalHeader("X-ONAP-RequestID", execution.getVariable("mso-request-id")) - httpClient.addAdditionalHeader("X-ONAP-InvocationID", UUID.randomUUID().toString()) - httpClient.addAdditionalHeader("X-ONAP-PartnerName", "SO-VNFAdapter") - Response response; - - if ("GET".equals(vnfAdapterMethod)) { - response = httpClient.get() - } else if ("PUT".equals(vnfAdapterMethod)) { - response = httpClient.put(vnfAdapterRequest) - } else if ("POST".equals(vnfAdapterMethod)) { - response = httpClient.post(vnfAdapterRequest) - } else if ("DELETE".equals(vnfAdapterMethod)) { - response = httpClient.delete(vnfAdapterRequest) - } else { - String msg = 'Unsupported HTTP method "' + vnfAdapterMethod + '" in ' + method + ": " + e - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - execution.setVariable(prefix + "vnfAdapterStatusCode", response.getStatus()) - if(response.hasEntity()){ - execution.setVariable(prefix + "vnfAdapterResponse", response.readEntity(String.class)) - } - } catch (BpmnError e) { - throw e - } catch (Exception e) { - String msg = 'Caught exception in ' + method + ": " + e - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - } - - public void processCallback(DelegateExecution execution){ - def method = getClass().getSimpleName() + '.processCallback(' + - 'execution=' + execution.getId() + - ')' - logger.trace('Entered ' + method) - - String callback = execution.getVariable('VNFAResponse_MESSAGE') - - try { - logger.debug(getProcessKey(execution) + ": received callback:\n" + callback) - - // The XML callback is available to the calling flow in any case, - // even if a WorkflowException is generated. - execution.setVariable(getProcessKey(execution) + 'Response', callback) - // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead. - execution.setVariable("WorkflowResponse", callback) - - callback = utils.removeXmlPreamble(callback) - - Node root = new XmlParser().parseText(callback) - if (root.name().endsWith('Exception')) { - vnfAdapterWorkflowException(execution, callback) - } - } catch (Exception e) { - logger.debug("Error encountered within VnfAdapterRest ProcessCallback method: {}", e.getMessage(), e) - exceptionUtil.buildAndThrowWorkflowException(execution, 7020, "Error encountered within VnfAdapterRest ProcessCallback method", ONAPComponents.SO) - } - } - - /** - * Tries to parse the response as XML to extract the information to create - * a WorkflowException. If the response cannot be parsed, a more generic - * WorkflowException is created. - */ - public void vnfAdapterWorkflowException(DelegateExecution execution, Object response) { - try { - Node root = new XmlParser().parseText(response) - String category = getChildText(root, "category") - category = category == null || category.isEmpty() ? "" : " category='" + category + "'" - String message = getChildText(root, "message") - message = message == null || message.isEmpty() ? "" : " message='" + message + "'" - String rolledBack = getChildText(root, "rolledBack") - rolledBack = rolledBack == null || rolledBack.isEmpty() ? "" : " rolledBack='" + rolledBack + "'" - exceptionUtil.buildWorkflowException(execution, 7020, "Received " + root.name() + - " from VnfAdapter:" + category + message + rolledBack, Components.OPENSTACK); - } catch (Exception e) { - response = response == null || String.valueOf(response).isEmpty() ? "NONE" : response - exceptionUtil.buildWorkflowException(execution, 7020, "Received error from VnfAdapter: " + response, Components.OPENSTACK) - } - } - - /** - * Gets the named child of the specified node. - * @param node the node - * @param name the child name - * @return the child node, or null if no such child exists - */ - private Node getChild(Node node, String name) { - for (Node child : node.children()) { - if (child.name() == name) { - return child - } - } - return null - } - - /** - * Gets the text of the named child of the specified node. - * @param node the node - * @param name the child name - * @return the child node text, or null if no such child exists - */ - private String getChildText(Node node, String name) { - Node child = getChild(node, name) - return child == null ? null : child.text() - } - - public Logger getLogger() { - return logger; - } -} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterUtils.groovy deleted file mode 100644 index 91b29d3867..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterUtils.groovy +++ /dev/null @@ -1,97 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.bpmn.common.scripts - -import org.onap.so.logger.LoggingAnchor -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.delegate.DelegateExecution; -import org.onap.so.bpmn.core.WorkflowException -import org.onap.logging.filter.base.ErrorCode -import org.onap.so.logger.MessageEnum -import org.slf4j.Logger -import org.slf4j.LoggerFactory - - - -class VnfAdapterUtils { - private static final Logger logger = LoggerFactory.getLogger( VnfAdapterUtils.class); - - - private AbstractServiceTaskProcessor taskProcessor - - public VnfAdapterUtils(AbstractServiceTaskProcessor taskProcessor) { - this.taskProcessor = taskProcessor - } - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - public void validateVnfResponse(DelegateExecution execution, String responseVar, String responseCodeVar, String errorResponseVar) { - def method = getClass().getSimpleName() + '.validateVnfResponse(' + - 'execution=' + execution.getId() + - ', responseVar=' + responseVar + - ', responseCodeVar=' + responseCodeVar + - ', errorResponseVar=' + errorResponseVar + - ')' - logger.trace('Entered ' + method) - - try { - def prefix = execution.getVariable('prefix') - - def response = execution.getVariable(responseVar) - def responseCode = execution.getVariable(responseCodeVar) - def errorResponse = execution.getVariable(errorResponseVar) - - // The following if statement never appears to be true as any VNF Adapter error seems to be stored in 'errorResponse'. - // Also, the value is stored as a WorkflowException object, not a String. Added the else if to provide the proper - // functionality but leaving the original code in case it is hit under some circumstances. - if (response.contains("WorkflowException")) { - execution.setVariable(prefix + "ErrorResponse", response) - //execution.setVariable(prefix + "ResponseCode", responseCode) - logger.debug(" Sub Vnf flow Error WorkflowException Response - " + "\n" + response) - throw new BpmnError("MSOWorkflowException") - } else if (errorResponse != null && errorResponse instanceof WorkflowException) { - // Not sure the variables with the associated prefix are still used - execution.setVariable(prefix + "ErrorResponse", errorResponse.getErrorMessage()) - execution.setVariable(prefix + "ResponseCode", errorResponse.getErrorCode()) - logger.debug("Sub Vnf flow Error WorkflowException " + prefix + "ErrorResponse" + " - " + errorResponse.getErrorMessage()) - // this is the important part to ensure we hit the Fallout Handler - throw new BpmnError("MSOWorkflowException") - } else if (errorResponse != null && errorResponse instanceof WorkflowException) { - // Not sure the variables with the associated prefix are still used - execution.setVariable(prefix + "ErrorResponse", errorResponse.getErrorMessage()) - execution.setVariable(prefix + "ResponseCode", errorResponse.getErrorCode()) - logger.debug("Sub Vnf flow Error WorkflowException " + prefix + "ErrorResponse" + " - " + errorResponse.getErrorMessage()) - // this is the important part to ensure we hit the Fallout Handler - throw new BpmnError("MSOWorkflowException") - } - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - 'Caught exception in ' + method, "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - exceptionUtil.buildAndThrowWorkflowException(execution, 5000, 'Internal Error- Unable to validate VNF Response ' + e.getMessage()) - } - } - -} diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/VnfAdapterRestV1.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/VnfAdapterRestV1.bpmn deleted file mode 100644 index db93df9f09..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/VnfAdapterRestV1.bpmn +++ /dev/null @@ -1,441 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd" id="_GraPIIyxEeWmdMDkx6Uftw" exporter="camunda modeler" exporterVersion="2.7.0" targetNamespace="http://camunda.org/schema/1.0/bpmn"> - <bpmn2:process id="vnfAdapterRestV1" name="vnfAdapterRestV1" isExecutable="true"> - <bpmn2:scriptTask id="ScriptTask_2" name="Log Response" scriptFormat="groovy"> - <bpmn2:incoming>SequenceFlow_3</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_14</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* -def vnfAdapterRestV1 = new VnfAdapterRestV1() -def statusCode = execution.getVariable('VNFREST_vnfAdapterStatusCode') -String response = String.valueOf(execution.getVariable('VNFREST_vnfAdapterResponse')) -def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') -def processKey = vnfAdapterRestV1.getProcessKey(execution) -vnfAdapterRestV1.getLogger().debug("{} received response from VnfAdapter: statusCode= {} response={}", processKey, statusCode, (response.isEmpty() ? "" : "\n" + response))]]></bpmn2:script> - </bpmn2:scriptTask> - <bpmn2:scriptTask id="ScriptTask_3" name="Workflow Exception (no connection)"> - <bpmn2:incoming>SequenceFlow_17</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_35</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* -def exceptionUtil = new ExceptionUtil() -exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Failed to communicate with VnfAdapter")]]></bpmn2:script> - </bpmn2:scriptTask> - <bpmn2:scriptTask id="ScriptTask_4" name="Workflow Exception (bad response)" scriptFormat="groovy"> - <bpmn2:incoming>SequenceFlow_23</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_36</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* - -String res = execution.getVariable(VNFREST_vnfAdapterResponse) - -def vnfAdapterRestV1 = new VnfAdapterRestV1() -vnfAdapterRestV1.vnfAdapterWorkflowException(execution, res)]]></bpmn2:script> - </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_14" name="" sourceRef="ScriptTask_2" targetRef="ExclusiveGateway_1"/> - <bpmn2:exclusiveGateway id="ExclusiveGateway_1" default="SequenceFlow_23"> - <bpmn2:incoming>SequenceFlow_14</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_17</bpmn2:outgoing> - <bpmn2:outgoing>SequenceFlow_23</bpmn2:outgoing> - <bpmn2:outgoing>SequenceFlow_24</bpmn2:outgoing> - </bpmn2:exclusiveGateway> - <bpmn2:sequenceFlow id="SequenceFlow_17" name="404" sourceRef="ExclusiveGateway_1" targetRef="ScriptTask_3"> - <bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression"><![CDATA[#{execution.getVariable("VNFREST_vnfAdapterStatusCode") == '404'}]]></bpmn2:conditionExpression> - </bpmn2:sequenceFlow> - <bpmn2:sequenceFlow id="SequenceFlow_23" name="other" sourceRef="ExclusiveGateway_1" targetRef="ScriptTask_4"/> - <bpmn2:sequenceFlow id="SequenceFlow_24" name="2xx" sourceRef="ExclusiveGateway_1" targetRef="waitForAsyncMessage"> - <bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression"><![CDATA[#{execution.getVariable("VNFREST_vnfAdapterStatusCode") == '200' || execution.getVariable("VNFREST_vnfAdapterStatusCode") == '202'}]]></bpmn2:conditionExpression> - </bpmn2:sequenceFlow> - <bpmn2:boundaryEvent id="BoundaryEvent_1" name="Timeout" attachedToRef="waitForAsyncMessage"> - <bpmn2:outgoing>SequenceFlow_27</bpmn2:outgoing> - <bpmn2:timerEventDefinition id="TimerEventDefinition_1"> - <bpmn2:timeDuration xsi:type="bpmn2:tFormalExpression"><![CDATA[${UrnPropertiesReader.getVariable("mso.po.timeout", execution)}]]></bpmn2:timeDuration> - </bpmn2:timerEventDefinition> - </bpmn2:boundaryEvent> - <bpmn2:subProcess id="waitForAsyncMessage" name="Wait for Callback"> - <bpmn2:incoming>SequenceFlow_24</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_28</bpmn2:outgoing> - <bpmn2:intermediateCatchEvent id="IntermediateCatchEvent_1" name="Catch Event"> - <bpmn2:incoming>SequenceFlow_25</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_26</bpmn2:outgoing> - <bpmn2:messageEventDefinition id="MessageEventDefinition_1" messageRef="Message_1"/> - </bpmn2:intermediateCatchEvent> - <bpmn2:sequenceFlow id="SequenceFlow_26" name="" sourceRef="IntermediateCatchEvent_1" targetRef="EndEvent_2"/> - <bpmn2:startEvent id="StartEvent_3"> - <bpmn2:outgoing>SequenceFlow_25</bpmn2:outgoing> - </bpmn2:startEvent> - <bpmn2:sequenceFlow id="SequenceFlow_25" name="" sourceRef="StartEvent_3" targetRef="IntermediateCatchEvent_1"/> - <bpmn2:endEvent id="EndEvent_2"> - <bpmn2:incoming>SequenceFlow_26</bpmn2:incoming> - </bpmn2:endEvent> - </bpmn2:subProcess> - <bpmn2:sequenceFlow id="SequenceFlow_27" name="" sourceRef="BoundaryEvent_1" targetRef="ScriptTask_5"/> - <bpmn2:scriptTask id="ScriptTask_5" name="Workflow Exception (timeout)" scriptFormat="groovy"> - <bpmn2:incoming>SequenceFlow_27</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_34</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* -def exceptionUtil = new ExceptionUtil() -exceptionUtil.buildAndThrowWorkflowException(execution, 7010, "VnfAdapter Callback Timeout Error")]]></bpmn2:script> - </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_28" name="" sourceRef="waitForAsyncMessage" targetRef="ScriptTask_6"/> - <bpmn2:scriptTask id="ScriptTask_6" name="Process Callback" scriptFormat="groovy"> - <bpmn2:incoming>SequenceFlow_28</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_33</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* -def vnfAdapterRestV1 = new VnfAdapterRestV1() -vnfAdapterRestV1.processCallback(execution) -]]></bpmn2:script> - </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_33" name="" sourceRef="ScriptTask_6" targetRef="ExclusiveGateway_2"/> - <bpmn2:sequenceFlow id="SequenceFlow_34" name="" sourceRef="ScriptTask_5" targetRef="EndEvent_8"/> - <bpmn2:endEvent id="EndEvent_8"> - <bpmn2:incoming>SequenceFlow_34</bpmn2:incoming> - <bpmn2:errorEventDefinition id="_ErrorEventDefinition_21" errorRef="Error_1"/> - </bpmn2:endEvent> - <bpmn2:sequenceFlow id="SequenceFlow_35" name="" sourceRef="ScriptTask_3" targetRef="EndEvent_9"/> - <bpmn2:endEvent id="EndEvent_9"> - <bpmn2:incoming>SequenceFlow_35</bpmn2:incoming> - <bpmn2:errorEventDefinition id="_ErrorEventDefinition_22" errorRef="Error_1"/> - </bpmn2:endEvent> - <bpmn2:endEvent id="EndEvent_10"> - <bpmn2:incoming>SequenceFlow_36</bpmn2:incoming> - <bpmn2:errorEventDefinition id="_ErrorEventDefinition_23" errorRef="Error_1"/> - </bpmn2:endEvent> - <bpmn2:sequenceFlow id="SequenceFlow_36" name="" sourceRef="ScriptTask_4" targetRef="EndEvent_10"/> - <bpmn2:endEvent id="EndEvent_7"> - <bpmn2:incoming>SequenceFlow_32</bpmn2:incoming> - <bpmn2:errorEventDefinition id="_ErrorEventDefinition_20" errorRef="Error_1"/> - </bpmn2:endEvent> - <bpmn2:exclusiveGateway id="ExclusiveGateway_2" name="Callback
Exception?" default="SequenceFlow_31"> - <bpmn2:incoming>SequenceFlow_33</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_31</bpmn2:outgoing> - <bpmn2:outgoing>SequenceFlow_32</bpmn2:outgoing> - </bpmn2:exclusiveGateway> - <bpmn2:sequenceFlow id="SequenceFlow_31" name="no" sourceRef="ExclusiveGateway_2" targetRef="ScriptTask_setSuccess"/> - <bpmn2:sequenceFlow id="SequenceFlow_32" name="yes" sourceRef="ExclusiveGateway_2" targetRef="EndEvent_7"> - <bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression"><![CDATA[#{execution.getVariable("WorkflowException") != null}]]></bpmn2:conditionExpression> - </bpmn2:sequenceFlow> - <bpmn2:scriptTask id="ScriptTask_setSuccess" name="Set Success Indicator" scriptFormat="groovy"> - <bpmn2:incoming>SequenceFlow_31</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_1</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* -def vnfAdapterRestV1 = new VnfAdapterRestV1() -vnfAdapterRestV1.setSuccessIndicator(execution, true)]]></bpmn2:script> - </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_1" name="" sourceRef="ScriptTask_setSuccess" targetRef="EndEvent_6"/> - <bpmn2:endEvent id="EndEvent_6" name="End Flow"> - <bpmn2:incoming>SequenceFlow_1</bpmn2:incoming> - </bpmn2:endEvent> - <bpmn2:scriptTask id="ScriptTask_7" name="Send Request to Vnf Adapter" scriptFormat="groovy"> - <bpmn2:incoming>SequenceFlow_2</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_3</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* -def vnfAdapterRestV1 = new VnfAdapterRestV1() -vnfAdapterRestV1.sendRequestToVnfAdapter(execution)]]></bpmn2:script> - </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_3" name="" sourceRef="ScriptTask_7" targetRef="ScriptTask_2"/> - <bpmn2:subProcess id="SubProcess_1" name="Error Handling Sub Process" triggeredByEvent="true"> - <bpmn2:scriptTask id="ScriptTask_8" name="Process Error" scriptFormat="groovy"> - <bpmn2:incoming>SequenceFlow_4</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_5</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* -def exUtil = new ExceptionUtil() -exUtil.processSubflowsBPMNException(execution) -]]></bpmn2:script> - </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_5" name="" sourceRef="ScriptTask_8" targetRef="EndEvent_1"/> - <bpmn2:endEvent id="EndEvent_1"> - <bpmn2:incoming>SequenceFlow_5</bpmn2:incoming> - </bpmn2:endEvent> - <bpmn2:startEvent id="StartEvent_2"> - <bpmn2:outgoing>SequenceFlow_4</bpmn2:outgoing> - <bpmn2:errorEventDefinition id="_ErrorEventDefinition_89"/> - </bpmn2:startEvent> - <bpmn2:sequenceFlow id="SequenceFlow_4" name="" sourceRef="StartEvent_2" targetRef="ScriptTask_8"/> - </bpmn2:subProcess> - <bpmn2:scriptTask id="ScriptTask_1" name="Pre-Process Request" scriptFormat="groovy"> - <bpmn2:incoming>SequenceFlow_9</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_2</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* -def vnfAdapterRestV1 = new VnfAdapterRestV1() -vnfAdapterRestV1.preProcessRequest(execution) -]]></bpmn2:script> - </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_2" name="" sourceRef="ScriptTask_1" targetRef="ScriptTask_7"/> - <bpmn2:startEvent id="StartEvent_1" name="Start"> - <bpmn2:outgoing>SequenceFlow_9</bpmn2:outgoing> - </bpmn2:startEvent> - <bpmn2:sequenceFlow id="SequenceFlow_9" name="" sourceRef="StartEvent_1" targetRef="ScriptTask_1"/> - </bpmn2:process> - <bpmn2:error id="Error_1" errorCode="MSOWorkflowException" name="MSO Workflow Exception"/> - <bpmn2:message id="Message_1" name="WorkflowMessage"/> - <bpmndi:BPMNDiagram id="BPMNDiagram_1"> - <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="vnfAdapterRestV1"> - <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_56" bpmnElement="ScriptTask_1"> - <dc:Bounds height="80.0" width="100.0" x="204.0" y="148.0"/> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_SubProcess_14" bpmnElement="waitForAsyncMessage" isExpanded="true"> - <dc:Bounds height="154.0" width="265.0" x="744.0" y="275.0"/> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_58" bpmnElement="ScriptTask_6"> - <dc:Bounds height="80.0" width="100.0" x="1046.0" y="311.0"/> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_59" bpmnElement="ScriptTask_5"> - <dc:Bounds height="80.0" width="100.0" x="827.0" y="492.0"/> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_BoundaryEvent_24" bpmnElement="BoundaryEvent_1"> - <dc:Bounds height="36.0" width="36.0" x="859.0" y="411.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="22.0" width="52.0" x="894.0" y="441.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_IntermediateCatchEvent_20" bpmnElement="IntermediateCatchEvent_1"> - <dc:Bounds height="36.0" width="36.0" x="863.0" y="330.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="22.0" width="76.0" x="843.0" y="371.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_78" bpmnElement="ScriptTask_4"> - <dc:Bounds height="80.0" width="97.0" x="744.0" y="148.0"/> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_79" bpmnElement="ScriptTask_2"> - <dc:Bounds height="80.0" width="100.0" x="492.0" y="148.0"/> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_StartEvent_54" bpmnElement="StartEvent_1"> - <dc:Bounds height="36.0" width="36.0" x="84.0" y="170.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="22.0" width="34.0" x="85.0" y="211.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_168" bpmnElement="ScriptTask_3"> - <dc:Bounds height="80.0" width="97.0" x="744.0" y="24.0"/> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_2" bpmnElement="SequenceFlow_9" sourceElement="_BPMNShape_StartEvent_54" targetElement="_BPMNShape_ScriptTask_56"> - <di:waypoint xsi:type="dc:Point" x="120.0" y="188.0"/> - <di:waypoint xsi:type="dc:Point" x="204.0" y="188.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="130.0" y="188.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_ExclusiveGateway_105" bpmnElement="ExclusiveGateway_1" isMarkerVisible="true"> - <dc:Bounds height="50.0" width="50.0" x="624.0" y="162.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="0.0" width="0.0" x="649.0" y="217.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_18" bpmnElement="SequenceFlow_14" sourceElement="_BPMNShape_ScriptTask_79" targetElement="_BPMNShape_ExclusiveGateway_105"> - <di:waypoint xsi:type="dc:Point" x="592.0" y="188.0"/> - <di:waypoint xsi:type="dc:Point" x="624.0" y="187.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="611.0" y="187.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_19" bpmnElement="SequenceFlow_17" sourceElement="_BPMNShape_ExclusiveGateway_105" targetElement="_BPMNShape_ScriptTask_168"> - <di:waypoint xsi:type="dc:Point" x="649.0" y="162.0"/> - <di:waypoint xsi:type="dc:Point" x="649.0" y="64.0"/> - <di:waypoint xsi:type="dc:Point" x="744.0" y="64.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="22.0" width="27.0" x="688.0" y="64.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_20" bpmnElement="SequenceFlow_23" sourceElement="_BPMNShape_ExclusiveGateway_105" targetElement="_BPMNShape_ScriptTask_78"> - <di:waypoint xsi:type="dc:Point" x="674.0" y="187.0"/> - <di:waypoint xsi:type="dc:Point" x="709.0" y="187.0"/> - <di:waypoint xsi:type="dc:Point" x="709.0" y="188.0"/> - <di:waypoint xsi:type="dc:Point" x="744.0" y="188.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="22.0" width="35.0" x="684.0" y="188.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_25" bpmnElement="SequenceFlow_24" sourceElement="_BPMNShape_ExclusiveGateway_105" targetElement="_BPMNShape_SubProcess_14"> - <di:waypoint xsi:type="dc:Point" x="649.0" y="212.0"/> - <di:waypoint xsi:type="dc:Point" x="649.0" y="353.0"/> - <di:waypoint xsi:type="dc:Point" x="708.0" y="353.0"/> - <di:waypoint xsi:type="dc:Point" x="744.0" y="353.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="22.0" width="27.0" x="688.0" y="328.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_StartEvent_55" bpmnElement="StartEvent_3"> - <dc:Bounds height="36.0" width="36.0" x="768.0" y="330.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="0.0" width="0.0" x="786.0" y="371.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_27" bpmnElement="SequenceFlow_25" sourceElement="_BPMNShape_StartEvent_55" targetElement="_BPMNShape_IntermediateCatchEvent_20"> - <di:waypoint xsi:type="dc:Point" x="804.0" y="348.0"/> - <di:waypoint xsi:type="dc:Point" x="863.0" y="348.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="833.0" y="348.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_EndEvent_156" bpmnElement="EndEvent_2"> - <dc:Bounds height="36.0" width="36.0" x="948.0" y="330.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="0.0" width="0.0" x="966.0" y="371.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_28" bpmnElement="SequenceFlow_26" sourceElement="_BPMNShape_IntermediateCatchEvent_20" targetElement="_BPMNShape_EndEvent_156"> - <di:waypoint xsi:type="dc:Point" x="899.0" y="348.0"/> - <di:waypoint xsi:type="dc:Point" x="929.0" y="348.0"/> - <di:waypoint xsi:type="dc:Point" x="929.0" y="347.0"/> - <di:waypoint xsi:type="dc:Point" x="948.0" y="348.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="926.0" y="348.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_29" bpmnElement="SequenceFlow_27" sourceElement="_BPMNShape_BoundaryEvent_24" targetElement="_BPMNShape_ScriptTask_59"> - <di:waypoint xsi:type="dc:Point" x="877.0" y="447.0"/> - <di:waypoint xsi:type="dc:Point" x="877.0" y="492.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="874.0" y="472.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_30" bpmnElement="SequenceFlow_28" sourceElement="_BPMNShape_SubProcess_14" targetElement="_BPMNShape_ScriptTask_58"> - <di:waypoint xsi:type="dc:Point" x="1008.0" y="351.0"/> - <di:waypoint xsi:type="dc:Point" x="1046.0" y="351.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="1023.0" y="351.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_ExclusiveGateway_106" bpmnElement="ExclusiveGateway_2" isMarkerVisible="true"> - <dc:Bounds height="50.0" width="50.0" x="1188.0" y="325.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="38.0" width="71.0" x="1179.0" y="288.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_EndEvent_158" bpmnElement="EndEvent_6"> - <dc:Bounds height="36.0" width="36.0" x="1463.0" y="333.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="22.0" width="60.0" x="1451.0" y="374.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_33" bpmnElement="SequenceFlow_31" sourceElement="_BPMNShape_ExclusiveGateway_106" targetElement="_BPMNShape_ScriptTask_236"> - <di:waypoint xsi:type="dc:Point" x="1238.0" y="350.0"/> - <di:waypoint xsi:type="dc:Point" x="1308.0" y="350.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="22.0" width="20.0" x="1248.0" y="350.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_EndEvent_159" bpmnElement="EndEvent_7"> - <dc:Bounds height="36.0" width="36.0" x="1196.0" y="426.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="0.0" width="0.0" x="1214.0" y="467.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_34" bpmnElement="SequenceFlow_32" sourceElement="_BPMNShape_ExclusiveGateway_106" targetElement="_BPMNShape_EndEvent_159"> - <di:waypoint xsi:type="dc:Point" x="1213.0" y="375.0"/> - <di:waypoint xsi:type="dc:Point" x="1213.0" y="392.0"/> - <di:waypoint xsi:type="dc:Point" x="1214.0" y="392.0"/> - <di:waypoint xsi:type="dc:Point" x="1214.0" y="426.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="22.0" width="27.0" x="1223.0" y="390.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_35" bpmnElement="SequenceFlow_33" sourceElement="_BPMNShape_ScriptTask_58" targetElement="_BPMNShape_ExclusiveGateway_106"> - <di:waypoint xsi:type="dc:Point" x="1146.0" y="351.0"/> - <di:waypoint xsi:type="dc:Point" x="1173.0" y="351.0"/> - <di:waypoint xsi:type="dc:Point" x="1173.0" y="350.0"/> - <di:waypoint xsi:type="dc:Point" x="1188.0" y="350.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="1170.0" y="350.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_EndEvent_160" bpmnElement="EndEvent_8"> - <dc:Bounds height="36.0" width="36.0" x="974.0" y="514.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="0.0" width="0.0" x="992.0" y="555.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_36" bpmnElement="SequenceFlow_34" sourceElement="_BPMNShape_ScriptTask_59" targetElement="_BPMNShape_EndEvent_160"> - <di:waypoint xsi:type="dc:Point" x="927.0" y="532.0"/> - <di:waypoint xsi:type="dc:Point" x="974.0" y="532.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="951.0" y="532.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_EndEvent_161" bpmnElement="EndEvent_9"> - <dc:Bounds height="36.0" width="36.0" x="891.0" y="46.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="0.0" width="0.0" x="909.0" y="87.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_37" bpmnElement="SequenceFlow_35" sourceElement="_BPMNShape_ScriptTask_168" targetElement="_BPMNShape_EndEvent_161"> - <di:waypoint xsi:type="dc:Point" x="840.0" y="64.0"/> - <di:waypoint xsi:type="dc:Point" x="891.0" y="64.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="865.0" y="64.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_EndEvent_162" bpmnElement="EndEvent_10"> - <dc:Bounds height="36.0" width="36.0" x="892.0" y="170.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="0.0" width="0.0" x="910.0" y="211.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_38" bpmnElement="SequenceFlow_36" sourceElement="_BPMNShape_ScriptTask_78" targetElement="_BPMNShape_EndEvent_162"> - <di:waypoint xsi:type="dc:Point" x="840.0" y="188.0"/> - <di:waypoint xsi:type="dc:Point" x="892.0" y="188.0"/> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_236" bpmnElement="ScriptTask_setSuccess"> - <dc:Bounds height="83.0" width="97.0" x="1308.0" y="309.0"/> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_1" bpmnElement="SequenceFlow_1" sourceElement="_BPMNShape_ScriptTask_236" targetElement="_BPMNShape_EndEvent_158"> - <di:waypoint xsi:type="dc:Point" x="1404.0" y="350.0"/> - <di:waypoint xsi:type="dc:Point" x="1422.0" y="350.0"/> - <di:waypoint xsi:type="dc:Point" x="1422.0" y="351.0"/> - <di:waypoint xsi:type="dc:Point" x="1463.0" y="351.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="1419.0" y="351.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_237" bpmnElement="ScriptTask_7"> - <dc:Bounds height="83.0" width="97.0" x="360.0" y="146.0"/> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_3" bpmnElement="SequenceFlow_2" sourceElement="_BPMNShape_ScriptTask_56" targetElement="_BPMNShape_ScriptTask_237"> - <di:waypoint xsi:type="dc:Point" x="304.0" y="188.0"/> - <di:waypoint xsi:type="dc:Point" x="344.0" y="188.0"/> - <di:waypoint xsi:type="dc:Point" x="344.0" y="187.0"/> - <di:waypoint xsi:type="dc:Point" x="360.0" y="187.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="317.0" y="188.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_4" bpmnElement="SequenceFlow_3" sourceElement="_BPMNShape_ScriptTask_237" targetElement="_BPMNShape_ScriptTask_79"> - <di:waypoint xsi:type="dc:Point" x="456.0" y="187.0"/> - <di:waypoint xsi:type="dc:Point" x="474.0" y="187.0"/> - <di:waypoint xsi:type="dc:Point" x="474.0" y="188.0"/> - <di:waypoint xsi:type="dc:Point" x="492.0" y="188.0"/> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_SubProcess_24" bpmnElement="SubProcess_1" isExpanded="true"> - <dc:Bounds height="181.0" width="382.0" x="180.0" y="532.0"/> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_StartEvent_66" bpmnElement="StartEvent_2"> - <dc:Bounds height="36.0" width="36.0" x="225.0" y="605.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="0.0" width="0.0" x="243.0" y="646.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_EndEvent_207" bpmnElement="EndEvent_1"> - <dc:Bounds height="36.0" width="36.0" x="477.0" y="605.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="0.0" width="0.0" x="495.0" y="646.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_266" bpmnElement="ScriptTask_8"> - <dc:Bounds height="83.0" width="97.0" x="323.0" y="581.0"/> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_5" bpmnElement="SequenceFlow_4" sourceElement="_BPMNShape_StartEvent_66" targetElement="_BPMNShape_ScriptTask_266"> - <di:waypoint xsi:type="dc:Point" x="261.0" y="623.0"/> - <di:waypoint xsi:type="dc:Point" x="323.0" y="622.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="273.0" y="623.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_6" bpmnElement="SequenceFlow_5" sourceElement="_BPMNShape_ScriptTask_266" targetElement="_BPMNShape_EndEvent_207"> - <di:waypoint xsi:type="dc:Point" x="419.0" y="622.0"/> - <di:waypoint xsi:type="dc:Point" x="477.0" y="623.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="445.0" y="623.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - </bpmndi:BPMNPlane> - </bpmndi:BPMNDiagram> -</bpmn2:definitions>
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1Test.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1Test.groovy deleted file mode 100644 index 75ddca5e98..0000000000 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1Test.groovy +++ /dev/null @@ -1,135 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.bpmn.common.scripts - -import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.MockitoAnnotations -import org.mockito.internal.debugging.MockitoDebuggerImpl -import org.mockito.runners.MockitoJUnitRunner -import org.onap.so.bpmn.mock.FileUtil - -import static org.mockito.Mockito.* -import static org.junit.Assert.*; - -@RunWith(MockitoJUnitRunner.class) -public class VnfAdapterRestV1Test { - - @Before - public void init() - { - MockitoAnnotations.initMocks(this) - } - - - @Test - public void testPreProcessRequest() { - - String sdncAdapterWorkflowRequest = FileUtil.readResourceFile("__files/vnfAdapterMocks/vnfadapter_request.xml"); - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("prefix")).thenReturn("VNFREST_") - when(mockExecution.getVariable("mso-request-id")).thenReturn("testMsoRequestId") - when(mockExecution.getVariable("VNFREST_Request")).thenReturn(sdncAdapterWorkflowRequest) - when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C") - when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - - when(mockExecution.getVariable("mso.adapters.vnf.rest.endpoint")).thenReturn("http://localhost:18080/vnfs/rest/v1/vnfs") - - when(mockExecution.getVariable("mso.adapters.sdnc.timeout")).thenReturn("PT5M") - - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("testProcessKey")).thenReturn("testProcessKey") - - - VnfAdapterRestV1 vnfAdapterRestV1 = new VnfAdapterRestV1() - vnfAdapterRestV1.preProcessRequest(mockExecution) - - MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() - //debugger.printInvocations(mockExecution) - - - verify(mockExecution).setVariable("prefix","VNFREST_") - - verify(mockExecution).setVariable("VNFREST_SuccessIndicator",false) - verify(mockExecution).setVariable("VNFREST_requestType","createVfModuleRequest") - verify(mockExecution).setVariable("VNFAResponse_CORRELATOR","8892cffa-3514-45d4-b2b0-0fde9a96e323-1511813289000") - verify(mockExecution).setVariable("VNFREST_vnfAdapterMethod","POST") - verify(mockExecution).setVariable("VNFREST_notificationUrl","http://localhost:18080/mso/WorkflowMessage/VNFAResponse/8892cffa-3514-45d4-b2b0-0fde9a96e323-1511813289000") - verify(mockExecution).setVariable("VNFREST_vnfAdapterUrl","http://localhost:18080/vnfs/rest/v1/vnfs/6d2e2469-8708-47c3-a0d4-73fa28a8a50b/vf-modules") - - } - - String rollbackReq = """ -<rollbackVolumeGroupRequest> - <volumeGroupRollback> - <volumeGroupId>8a07b246-155e-4b08-b56e-76e98a3c2d66</volumeGroupId> - <volumeGroupStackId>phmaz401me6-vpevre-VOLUMEGROUP/dbd560b6-b03f-4a17-92e7-8942459a60c1</volumeGroupStackId> - <cloudSiteId>mtrnj1b</cloudSiteId> - <cloudOwnerId>CloudOwner</cloudOwnerId> - <tenantId>cfb5e0a790374c9a98a1c0d2044206a7</tenantId> - <volumeGroupCreated>true</volumeGroupCreated> - <msoRequest> - <requestId>1e1a72ca-7300-4ac4-b718-30351f3b6845</requestId> - <serviceInstanceId>15eb2c68-f771-4030-b185-cff179fdad44</serviceInstanceId> - </msoRequest> - <messageId>683ca1ac-2145-4a00-9484-20d48bd701aa</messageId> - </volumeGroupRollback> - <skipAAI>true</skipAAI> - <notificationUrl>http://localhost:8080/mso/WorkflowMessage/VNFAResponse/683ca1ac-2145-4a00-9484-20d48bd701aa</notificationUrl> -</rollbackVolumeGroupRequest> -""" - - @Test - public void testGetVolumeGroupId() { - Node root = new XmlParser().parseText(rollbackReq) - VnfAdapterRestV1 vnfAdapterRestV1 = new VnfAdapterRestV1() - def volGrpId = vnfAdapterRestV1.getVolumeGroupIdFromRollbackRequest(root) - assertEquals('8a07b246-155e-4b08-b56e-76e98a3c2d66', volGrpId) - } - - - @Test - public void testGetMessageId() { - Node root = new XmlParser().parseText(rollbackReq) - - VnfAdapterRestV1 p = new VnfAdapterRestV1() - def messageId = p.getMessageIdForVolumeGroupRollback(root) - assertEquals('683ca1ac-2145-4a00-9484-20d48bd701aa', messageId) - } - - @Test - public void testProcessCallback() { - - String sdncAdapterWorkflowRequest = FileUtil.readResourceFile("__files/vnfAdapterMocks/vnfAdapterCallback.xml"); - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - - when(mockExecution.getVariable("VNFAResponse_MESSAGE")).thenReturn(sdncAdapterWorkflowRequest) - when(mockExecution.getVariable("testProcessKey")).thenReturn("testProcessKey") - - VnfAdapterRestV1 vnfAdapterRestV1 = new VnfAdapterRestV1() - vnfAdapterRestV1.processCallback(mockExecution) - - verify(mockExecution).setVariable("testProcessKeyResponse" ,sdncAdapterWorkflowRequest) - - } -} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClient.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClient.java index f4e4ce8cb1..acb2e452da 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClient.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClient.java @@ -24,7 +24,6 @@ import org.onap.so.adapters.vnfrest.CreateVolumeGroupRequest; import org.onap.so.adapters.vnfrest.CreateVolumeGroupResponse; import org.onap.so.adapters.vnfrest.DeleteVolumeGroupRequest; import org.onap.so.adapters.vnfrest.DeleteVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.QueryVolumeGroupResponse; import org.onap.so.adapters.vnfrest.RollbackVolumeGroupRequest; import org.onap.so.adapters.vnfrest.RollbackVolumeGroupResponse; import org.onap.so.adapters.vnfrest.UpdateVolumeGroupRequest; @@ -41,8 +40,4 @@ public interface VnfVolumeAdapterClient { UpdateVolumeGroupResponse updateVNFVolumes(String aaiVolumeGroupId, UpdateVolumeGroupRequest req) throws VnfAdapterClientException; - - QueryVolumeGroupResponse queryVNFVolumes(String aaiVolumeGroupId, String cloudSiteId, String tenantId, - String volumeGroupStackId, Boolean skipAAI, String requestId, String serviceInstanceId) - throws VnfAdapterClientException; } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClientImpl.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClientImpl.java index c5e8bf7416..073b752348 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClientImpl.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/VnfVolumeAdapterClientImpl.java @@ -27,7 +27,6 @@ import org.onap.so.adapters.vnfrest.CreateVolumeGroupRequest; import org.onap.so.adapters.vnfrest.CreateVolumeGroupResponse; import org.onap.so.adapters.vnfrest.DeleteVolumeGroupRequest; import org.onap.so.adapters.vnfrest.DeleteVolumeGroupResponse; -import org.onap.so.adapters.vnfrest.QueryVolumeGroupResponse; import org.onap.so.adapters.vnfrest.RollbackVolumeGroupRequest; import org.onap.so.adapters.vnfrest.RollbackVolumeGroupResponse; import org.onap.so.adapters.vnfrest.UpdateVolumeGroupRequest; @@ -93,20 +92,6 @@ public class VnfVolumeAdapterClientImpl implements VnfVolumeAdapterClient { } } - @Override - public QueryVolumeGroupResponse queryVNFVolumes(String aaiVolumeGroupId, String cloudSiteId, String tenantId, - String volumeGroupStackId, Boolean skipAAI, String requestId, String serviceInstanceId) - throws VnfAdapterClientException { - try { - String path = buildQueryPath(aaiVolumeGroupId, cloudSiteId, tenantId, volumeGroupStackId, skipAAI, - requestId, serviceInstanceId); - return this.getAdapterRestClient(path).get(QueryVolumeGroupResponse.class).get(); - } catch (InternalServerErrorException e) { - logger.error("InternalServerErrorException in queryVNFVolumes", e); - throw new VnfAdapterClientException(e.getMessage()); - } - } - protected String buildQueryPath(String aaiVolumeGroupId, String cloudSiteId, String tenantId, String volumeGroupStackId, Boolean skipAAI, String requestId, String serviceInstanceId) { javax.ws.rs.core.UriBuilder builder = this.getUri("/" + aaiVolumeGroupId); |