diff options
Diffstat (limited to 'mso-api-handlers/mso-api-handler-infra/src/main/java')
24 files changed, 1273 insertions, 481 deletions
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java index 6013677684..897e2a5fc8 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java @@ -44,5 +44,7 @@ public enum Action implements Actions{ scaleInstance, deactivateAndCloudDelete, scaleOut, - recreateInstance + recreateInstance, + addMembers, + removeMembers } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Constants.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Constants.java index fe105a7637..d824696147 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Constants.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Constants.java @@ -49,4 +49,6 @@ public class Constants { public final static String VNF_REQUEST_SCOPE = "vnf"; public final static String SERVICE_INSTANCE_PATH = "/serviceInstances"; public final static String SERVICE_INSTANTIATION_PATH = "/serviceInstantiation"; + public final static String ORCHESTRATION_REQUESTS_PATH = "/orchestrationRequests"; + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java index 2a6764831d..be1131ed78 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java @@ -60,7 +60,7 @@ import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.db.request.beans.OperationStatus; import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.logger.MessageEnum; -import org.onap.so.logger.MsoAlarmLogger; + import org.onap.so.logger.MsoLogger; import org.onap.so.serviceinstancebeans.ModelInfo; import org.onap.so.serviceinstancebeans.ModelType; @@ -87,7 +87,7 @@ public class E2EServiceInstances { private HashMap<String, String> instanceIdMap = new HashMap<>(); private static final MsoLogger msoLogger = MsoLogger .getMsoLogger(MsoLogger.Catalog.APIH, E2EServiceInstances.class); - private static final MsoAlarmLogger alarmLogger = new MsoAlarmLogger(); + private static final String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA"; private static final String END_OF_THE_TRANSACTION = "End of the transaction, the final response is: "; @@ -286,9 +286,7 @@ public class E2EServiceInstances { workflowUrl, null); Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), - ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - alarmLogger.sendAlarm("MsoConfigurationError", MsoAlarmLogger.CRITICAL, - Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL)); + ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine",e); msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, @@ -341,9 +339,7 @@ public class E2EServiceInstances { HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version); - alarmLogger.sendAlarm("MsoDatabaseAccessError", - MsoAlarmLogger.CRITICAL, Messages.errors - .get(ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB)); + msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while communciate with Request DB"); @@ -423,9 +419,7 @@ public class E2EServiceInstances { HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - alarmLogger.sendAlarm("MsoDatabaseAccessError", - MsoAlarmLogger.CRITICAL, Messages.errors - .get(ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB)); + msoRequest.createErrorRequestRecord(Status.FAILED, requestId, "Exception while communciate with Catalog DB", action, ModelType.service.name(), requestJSON); msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, @@ -498,10 +492,7 @@ public class E2EServiceInstances { HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - alarmLogger.sendAlarm("MsoConfigurationError", - MsoAlarmLogger.CRITICAL, - Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL)); - msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, + msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine"); @@ -593,8 +584,7 @@ public class E2EServiceInstances { Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - alarmLogger.sendAlarm("MsoDatabaseAccessError", MsoAlarmLogger.CRITICAL, - Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB)); + msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while communciate with DB"); @@ -654,8 +644,7 @@ public class E2EServiceInstances { Response getBPMNResp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - alarmLogger.sendAlarm("MsoConfigurationError", MsoAlarmLogger.CRITICAL, - Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL)); + msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine"); msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, @@ -739,9 +728,7 @@ public class E2EServiceInstances { Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - alarmLogger.sendAlarm("MsoDatabaseAccessError", MsoAlarmLogger.CRITICAL, - Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB)); - + msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while communciate with DB"); msoLogger.debug(END_OF_THE_TRANSACTION + response.getEntity()); @@ -798,8 +785,7 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - alarmLogger.sendAlarm("MsoConfigurationError", MsoAlarmLogger.CRITICAL, - Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL)); + msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine"); msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, @@ -873,9 +859,7 @@ public class E2EServiceInstances { HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - alarmLogger.sendAlarm("MsoDatabaseAccessError", - MsoAlarmLogger.CRITICAL, Messages.errors - .get(ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB)); + msoRequest.createErrorRequestRecord(Status.FAILED, requestId, "No communication to catalog DB " + e.getMessage(), action, ModelType.service.name(), requestJSON); msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, @@ -947,9 +931,7 @@ public class E2EServiceInstances { HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - alarmLogger.sendAlarm("MsoConfigurationError", - MsoAlarmLogger.CRITICAL, - Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL)); + msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java index 7a8035ac63..862e9a668f 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java @@ -20,6 +20,13 @@ package org.onap.so.apihandlerinfra; + +import java.net.URI; +import java.util.Collections; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +import javax.annotation.PostConstruct; import javax.transaction.Transactional; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; @@ -29,42 +36,190 @@ import javax.ws.rs.QueryParam; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import java.util.UUID; import org.apache.http.HttpStatus; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; -import org.onap.so.utils.UUIDChecker; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Component; - +import org.springframework.web.client.RestTemplate; +import org.springframework.http.HttpMethod; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; - @Component @Path("/globalhealthcheck") @Api(value="/globalhealthcheck",description="APIH Infra Global Health Check") public class GlobalHealthcheckHandler { + private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH, GlobalHealthcheckHandler.class); + private static final String CONTEXTPATH_PROPERTY = "management.context-path"; + private static final String PROPERTY_DOMAIN = "mso.health.endpoints"; + private static final String CATALOGDB_PROPERTY = PROPERTY_DOMAIN+".catalogdb"; + private static final String REQUESTDB_PROPERTY = PROPERTY_DOMAIN+".requestdb"; + private static final String SDNC_PROPERTY = PROPERTY_DOMAIN+".sdnc"; + private static final String OPENSTACK_PROPERTY = PROPERTY_DOMAIN+".openstack"; + private static final String BPMN_PROPERTY = PROPERTY_DOMAIN+".bpmn"; + private static final String ASDC_PROPERTY = PROPERTY_DOMAIN+".asdc"; + private static final String REQUESTDBATTSVC_PROPERTY = PROPERTY_DOMAIN+".requestdbattsvc"; + private static final String DEFAULT_PROPERTY_VALUE = ""; + + // e.g. /manage + private String actuatorContextPath; + private String endpointCatalogdb; + private String endpointRequestdb; + private String endpointSdnc; + private String endpointOpenstack; + private String endpointBpmn; + private String endpointAsdc; + private String endpointRequestdbAttsvc; + + @Autowired + private Environment env; - private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH,GlobalHealthcheckHandler.class); - private static final String CHECK_HTML = "<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>Health Check</title></head><body>Application ready</body></html>"; + @Autowired + private RestTemplate restTemplate; + private final String health = "/health"; - public static final Response HEALTH_CHECK_RESPONSE = Response.status (HttpStatus.SC_OK) - .entity (CHECK_HTML) - .build (); + + @PostConstruct + protected void init() { + actuatorContextPath = env.getProperty(CONTEXTPATH_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); + endpointCatalogdb = env.getProperty(CATALOGDB_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); + endpointRequestdb = env.getProperty(REQUESTDB_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); + endpointSdnc = env.getProperty(SDNC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); + endpointOpenstack = env.getProperty(OPENSTACK_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); + endpointBpmn = env.getProperty(BPMN_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); + endpointAsdc = env.getProperty(ASDC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); + endpointRequestdbAttsvc = env.getProperty(REQUESTDBATTSVC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); + } @GET - @Produces("text/html") + @Produces("application/json") @ApiOperation(value="Performing global health check",response=Response.class) @Transactional public Response globalHealthcheck (@DefaultValue("true") @QueryParam("enableBpmn") boolean enableBpmn, @Context ContainerRequestContext requestContext) { - long startTime = System.currentTimeMillis (); - MsoLogger.setServiceName ("GlobalHealthcheck"); - // Generated RequestId - String requestId = requestContext.getProperty("requestId").toString(); - MsoLogger.setLogContext(requestId, null); - msoLogger.info(MessageEnum.APIH_GENERATED_REQUEST_ID, requestId, "", ""); + Response HEALTH_CHECK_RESPONSE = null; + // Build internal response object + HealthcheckResponse rsp = new HealthcheckResponse(); + + try{ + long startTime = System.currentTimeMillis (); + MsoLogger.setServiceName ("GlobalHealthcheck"); + // Generated RequestId + String requestId = requestContext.getProperty("requestId").toString(); + MsoLogger.setLogContext(requestId, null); + msoLogger.info(MessageEnum.APIH_GENERATED_REQUEST_ID, requestId, "", ""); + + // set APIH status, this is the main entry point + rsp.setApih(HealthcheckStatus.UP.toString()); + // set BPMN + rsp.setBpmn(querySubsystemHealth(MsoSubsystems.BPMN)); + // set SDNCAdapter + rsp.setSdncAdapter(querySubsystemHealth(MsoSubsystems.SDNC)); + // set ASDCController + rsp.setAsdcController(querySubsystemHealth(MsoSubsystems.ASDC)); + // set CatalogDbAdapter + rsp.setCatalogdbAdapter(querySubsystemHealth(MsoSubsystems.CATALOGDB)); + // set RequestDbAdapter + rsp.setRequestdbAdapter(querySubsystemHealth(MsoSubsystems.REQUESTDB)); + // set OpenStackAdapter + rsp.setOpenstackAdapter(querySubsystemHealth(MsoSubsystems.OPENSTACK)); + // set RequestDbAdapterAttSvc + rsp.setRequestdbAdapterAttsvc(querySubsystemHealth(MsoSubsystems.REQUESTDBATT)); + // set Message + rsp.setMessage(String.format("HttpStatus: %s", HttpStatus.SC_OK)); + msoLogger.info(rsp.toString(), "", ""); + + HEALTH_CHECK_RESPONSE = Response.status (HttpStatus.SC_OK) + .entity (rsp) + .build (); + + }catch (Exception ex){ + msoLogger.error(ex); + rsp.setMessage(ex.getMessage()); + HEALTH_CHECK_RESPONSE = Response.status (HttpStatus.SC_INTERNAL_SERVER_ERROR) + .entity (rsp) + .build (); + } + return HEALTH_CHECK_RESPONSE; - } + } + + protected HttpEntity<String> buildHttpEntityForRequest(){ + HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + headers.set("Content-Type", "application/json"); + HttpEntity<String> entity = new HttpEntity<>("parameters", headers); + return entity; + } + + protected String querySubsystemHealth(MsoSubsystems subsystem){ + try{ + // get port number for the subsystem + String ept = getEndpointUrlForSubsystemEnum(subsystem); + + // build final endpoint url + UriBuilder builder = UriBuilder.fromPath(ept).path(actuatorContextPath).path(health); + URI uri = builder.build(); + msoLogger.info("Calculated URL: "+uri.toString(), "", ""); + + ResponseEntity<SubsystemHealthcheckResponse> result = + restTemplate.exchange(uri, HttpMethod.GET, buildHttpEntityForRequest(), SubsystemHealthcheckResponse.class); + + return processResponseFromSubsystem(result,subsystem); + + }catch(Exception ex){ + msoLogger.error("Exception occured in GlobalHealthcheckHandler.querySubsystemHealth() "+ ex); + return HealthcheckStatus.DOWN.toString(); + } + } + protected String processResponseFromSubsystem(ResponseEntity<SubsystemHealthcheckResponse> result, MsoSubsystems subsystem){ + if(result == null || result.getStatusCodeValue() != HttpStatus.SC_OK){ + msoLogger.error(String.format("Globalhealthcheck: checking subsystem: %s failed ! result object is: %s", + subsystem, + result == null? "NULL": result)); + return HealthcheckStatus.DOWN.toString(); + } + + SubsystemHealthcheckResponse body = result.getBody(); + + String status = body.getStatus(); + if("UP".equalsIgnoreCase(status)){ + return HealthcheckStatus.UP.toString(); + }else{ + msoLogger.error(subsystem + ", query health endpoint did not return UP status!"); + return HealthcheckStatus.DOWN.toString(); + } + } + + + protected String getEndpointUrlForSubsystemEnum(MsoSubsystems subsystem){ + switch (subsystem){ + case SDNC: + return this.endpointSdnc; + case ASDC: + return this.endpointAsdc; + case BPMN: + return this.endpointBpmn; + case CATALOGDB: + return this.endpointCatalogdb; + case OPENSTACK: + return this.endpointOpenstack; + case REQUESTDB: + return this.endpointRequestdb; + case REQUESTDBATT: + return this.endpointRequestdbAttsvc; + default: + return ""; + } + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java new file mode 100644 index 0000000000..8f0bbc4e1f --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java @@ -0,0 +1,121 @@ +/*- + * ============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.apihandlerinfra; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +public class HealthcheckResponse { + private String apih; + private String bpmn; + private String sdncAdapter; + private String asdcController; + private String catalogdbAdapter; + private String requestdbAdapter; + private String openstackAdapter; + private String requestdbAdapterAttsvc; + private String message = ""; + + public String getApih() { + return apih; + } + + public void setApih(String apih) { + this.apih = apih; + } + + public String getBpmn() { + return bpmn; + } + + public void setBpmn(String bpmn) { + this.bpmn = bpmn; + } + + public String getSdncAdapter() { + return sdncAdapter; + } + + public void setSdncAdapter(String sdncAdapter) { + this.sdncAdapter = sdncAdapter; + } + + public String getAsdcController() { + return asdcController; + } + + public void setAsdcController(String asdcController) { + this.asdcController = asdcController; + } + + public String getCatalogdbAdapter() { + return catalogdbAdapter; + } + + public void setCatalogdbAdapter(String catalogdbAdapter) { + this.catalogdbAdapter = catalogdbAdapter; + } + + public String getRequestdbAdapter() { + return requestdbAdapter; + } + + public void setRequestdbAdapter(String requestdbAdapter) { + this.requestdbAdapter = requestdbAdapter; + } + + public String getOpenstackAdapter() { + return openstackAdapter; + } + + public void setOpenstackAdapter(String openstackAdapter) { + this.openstackAdapter = openstackAdapter; + } + + public String getRequestdbAdapterAttsvc() { + return requestdbAdapterAttsvc; + } + + public void setRequestdbAdapterAttsvc(String requestdbAdapterAttsvc) { + this.requestdbAdapterAttsvc = requestdbAdapterAttsvc; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public String toString() { + return new ToStringBuilder(this). + append("apih", this.apih). + append("pbmn", this.bpmn). + append("sdncAdapter", this.sdncAdapter). + append("asdcController", this.asdcController). + append("catalogdbAdapter", this.catalogdbAdapter). + append("requestdbAdapter", this.requestdbAdapter). + append("openstackAdapter", this.openstackAdapter). + append("requestdbAdapterAttsvc", this.requestdbAdapterAttsvc). + append("message", this.message). + toString(); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckStatus.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckStatus.java new file mode 100644 index 0000000000..89c4e0efda --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckStatus.java @@ -0,0 +1,34 @@ +/*- + * ============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.apihandlerinfra; + +public enum HealthcheckStatus { + UP("UP"), DOWN("DOWN"); + + private String status; + private HealthcheckStatus(String status) { + this.status = status; + } + + @Override + public String toString(){ + return status; + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java index dcfe40aa51..81a197c85c 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java @@ -44,7 +44,7 @@ import org.onap.so.apihandler.common.ResponseHandler; import org.onap.so.apihandlerinfra.exceptions.ApiException; import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; -import org.onap.so.apihandlerinfra.logging.AlarmLoggerInfo; + import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.apihandlerinfra.tasksbeans.TaskRequestReference; import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest; @@ -53,7 +53,7 @@ import org.onap.so.apihandlerinfra.tasksbeans.Variables; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.exceptions.ValidationException; import org.onap.so.logger.MessageEnum; -import org.onap.so.logger.MsoAlarmLogger; + import org.onap.so.logger.MsoLogger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -69,7 +69,7 @@ import io.swagger.annotations.ApiOperation; @Component public class ManualTasks { private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH, ManualTasks.class); - private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger (); + @org.springframework.beans.factory.annotation.Value("${mso.camunda.rest.task.uri}") private String taskUri; @@ -178,12 +178,11 @@ public class ManualTasks { } catch (Exception e) { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.AvailabilityError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - AlarmLoggerInfo alarmLoggerInfo = new AlarmLoggerInfo.Builder("MsoConfigurationError", MsoAlarmLogger.CRITICAL, Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_BPEL)).build(); BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), - HttpStatus.SC_BAD_GATEWAY,ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).alarmInfo(alarmLoggerInfo).build(); + HttpStatus.SC_BAD_GATEWAY,ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build(); throw bpmnFailureException; } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java index 753e712d71..7f602323e1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java @@ -23,12 +23,14 @@ package org.onap.so.apihandlerinfra; import java.io.IOException; import java.io.StringWriter; +import java.net.URL; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Optional; import java.util.StringTokenizer; import javax.ws.rs.core.MultivaluedMap; @@ -42,6 +44,7 @@ import javax.xml.transform.stream.StreamResult; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest; +import org.onap.so.apihandlerinfra.validation.MembersValidation; import org.onap.so.apihandlerinfra.validation.ApplyUpdatedConfigValidation; import org.onap.so.apihandlerinfra.validation.CloudConfigurationValidation; import org.onap.so.apihandlerinfra.validation.ConfigurationParametersValidation; @@ -65,6 +68,7 @@ import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.db.request.data.repository.InfraActiveRequestsRepository; import org.onap.so.exceptions.ValidationException; +import org.onap.so.logger.LogConstants; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; import org.onap.so.serviceinstancebeans.CloudConfiguration; @@ -80,6 +84,7 @@ import org.onap.so.serviceinstancebeans.RequestParameters; import org.onap.so.serviceinstancebeans.Service; import org.onap.so.serviceinstancebeans.ServiceException; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.w3c.dom.Document; @@ -157,7 +162,7 @@ public class MsoRequest { public void parse (ServiceInstancesRequest sir, HashMap<String,String> instanceIdMap, Actions action, String version, String originalRequestJSON, int reqVersion, Boolean aLaCarteFlag) throws ValidationException, IOException { - msoLogger.debug ("Validating the Service Instance request"); + msoLogger.debug ("Validating the Service Instance request"); List<ValidationRule> rules = new ArrayList<>(); msoLogger.debug ("Incoming version is: " + version + " coverting to int: " + reqVersion); RequestParameters requestParameters = sir.getRequestDetails().getRequestParameters(); @@ -170,6 +175,8 @@ public class MsoRequest { rules.add(new InPlaceSoftwareUpdateValidation()); }else if(reqVersion >= 6 && action == Action.applyUpdatedConfig){ rules.add(new ApplyUpdatedConfigValidation()); + }else if(action == Action.addMembers || action == Action.removeMembers){ + rules.add(new MembersValidation()); }else{ rules.add(new RequestScopeValidation()); rules.add(new RequestParametersValidation()); @@ -260,107 +267,114 @@ public class MsoRequest { if (null == servInsReq) { servInsReq = new ServiceInstancesRequest (); } - String networkType = ""; String vnfType = ""; aq.setRequestId (requestId); aq.setRequestAction(action.toString()); aq.setAction(action.toString()); + aq.setRequestUrl(MDC.get(LogConstants.HTTP_URL)); Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis()); aq.setStartTime (startTimeStamp); - RequestInfo requestInfo =servInsReq.getRequestDetails().getRequestInfo(); - if (requestInfo != null) { - - if(requestInfo.getSource() != null){ - aq.setSource(requestInfo.getSource()); - } - if(requestInfo.getCallbackUrl() != null){ - aq.setCallBackUrl(requestInfo.getCallbackUrl()); - } - if(requestInfo.getCorrelator() != null){ - aq.setCorrelator(requestInfo.getCorrelator()); - } - - if(requestInfo.getRequestorId() != null) { - aq.setRequestorId(requestInfo.getRequestorId()); - } - } - - if (servInsReq.getRequestDetails().getModelInfo() != null || (action == Action.inPlaceSoftwareUpdate || action == Action.applyUpdatedConfig)) { + if(requestScope.equals(ModelType.instanceGroup.name()) && action == Action.deleteInstance){ aq.setRequestScope(requestScope); - } - - if (servInsReq.getRequestDetails().getCloudConfiguration() != null) { - CloudConfiguration cloudConfiguration = servInsReq.getRequestDetails().getCloudConfiguration(); - if(cloudConfiguration.getLcpCloudRegionId() != null) { - aq.setAicCloudRegion(cloudConfiguration.getLcpCloudRegionId()); - } - - if(cloudConfiguration.getTenantId() != null) { - aq.setTenantId(cloudConfiguration.getTenantId()); - } - - } - - if(servInsReq.getServiceInstanceId() != null){ - aq.setServiceInstanceId(servInsReq.getServiceInstanceId()); - } - - if(servInsReq.getVnfInstanceId() != null){ - aq.setVnfId(servInsReq.getVnfInstanceId()); - } - - if(ModelType.service.name().equalsIgnoreCase(requestScope)){ - if(servInsReq.getRequestDetails().getRequestInfo().getInstanceName() != null){ - aq.setServiceInstanceName(requestInfo.getInstanceName()); - } - } - - if(ModelType.network.name().equalsIgnoreCase(requestScope)){ - aq.setNetworkName(servInsReq.getRequestDetails().getRequestInfo().getInstanceName()); - aq.setNetworkType(networkType); - aq.setNetworkId(servInsReq.getNetworkInstanceId()); - } - - if(ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)){ - aq.setVolumeGroupId(servInsReq.getVolumeGroupInstanceId()); - aq.setVolumeGroupName(servInsReq.getRequestDetails().getRequestInfo().getInstanceName()); - aq.setVnfType(vnfType); - - } - - if(ModelType.vfModule.name().equalsIgnoreCase(requestScope)){ - aq.setVfModuleName(requestInfo.getInstanceName()); - aq.setVfModuleModelName(servInsReq.getRequestDetails().getModelInfo().getModelName()); - aq.setVfModuleId(servInsReq.getVfModuleInstanceId()); - aq.setVolumeGroupId(servInsReq.getVolumeGroupInstanceId()); - aq.setVnfType(vnfType); - - } - - if(ModelType.configuration.name().equalsIgnoreCase(requestScope)) { - aq.setConfigurationId(servInsReq.getConfigurationId()); - aq.setConfigurationName(requestInfo.getInstanceName()); - } - - if(ModelType.vnf.name().equalsIgnoreCase(requestScope)){ - aq.setVnfName(requestInfo.getInstanceName()); - if (null != servInsReq.getRequestDetails()) { - RelatedInstanceList[] instanceList = servInsReq.getRequestDetails().getRelatedInstanceList(); - - if (instanceList != null) { - - for(RelatedInstanceList relatedInstanceList : instanceList){ - - RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); - if(relatedInstance.getModelInfo().getModelType().equals(ModelType.service)){ - aq.setVnfType(vnfType); + }else{ + RequestInfo requestInfo =servInsReq.getRequestDetails().getRequestInfo(); + if (requestInfo != null) { + + if(requestInfo.getSource() != null){ + aq.setSource(requestInfo.getSource()); + } + if(requestInfo.getCallbackUrl() != null){ + aq.setCallBackUrl(requestInfo.getCallbackUrl()); + } + if(requestInfo.getCorrelator() != null){ + aq.setCorrelator(requestInfo.getCorrelator()); + } + + if(requestInfo.getRequestorId() != null) { + aq.setRequestorId(requestInfo.getRequestorId()); + } + } + + if (servInsReq.getRequestDetails().getModelInfo() != null || (action == Action.inPlaceSoftwareUpdate || action == Action.applyUpdatedConfig)) { + aq.setRequestScope(requestScope); + } + + if (servInsReq.getRequestDetails().getCloudConfiguration() != null) { + CloudConfiguration cloudConfiguration = servInsReq.getRequestDetails().getCloudConfiguration(); + if(cloudConfiguration.getLcpCloudRegionId() != null) { + aq.setAicCloudRegion(cloudConfiguration.getLcpCloudRegionId()); + } + + if(cloudConfiguration.getTenantId() != null) { + aq.setTenantId(cloudConfiguration.getTenantId()); + } + + } + + if(servInsReq.getServiceInstanceId() != null){ + aq.setServiceInstanceId(servInsReq.getServiceInstanceId()); + } + + if(servInsReq.getVnfInstanceId() != null){ + aq.setVnfId(servInsReq.getVnfInstanceId()); + } + + if(ModelType.service.name().equalsIgnoreCase(requestScope)){ + if(servInsReq.getRequestDetails().getRequestInfo().getInstanceName() != null){ + aq.setServiceInstanceName(requestInfo.getInstanceName()); + } + } + + if(ModelType.network.name().equalsIgnoreCase(requestScope)){ + aq.setNetworkName(servInsReq.getRequestDetails().getRequestInfo().getInstanceName()); + aq.setNetworkType(networkType); + aq.setNetworkId(servInsReq.getNetworkInstanceId()); + } + + if(ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)){ + aq.setVolumeGroupId(servInsReq.getVolumeGroupInstanceId()); + aq.setVolumeGroupName(servInsReq.getRequestDetails().getRequestInfo().getInstanceName()); + aq.setVnfType(vnfType); + + } + + if(ModelType.vfModule.name().equalsIgnoreCase(requestScope)){ + aq.setVfModuleName(requestInfo.getInstanceName()); + aq.setVfModuleModelName(servInsReq.getRequestDetails().getModelInfo().getModelName()); + aq.setVfModuleId(servInsReq.getVfModuleInstanceId()); + aq.setVolumeGroupId(servInsReq.getVolumeGroupInstanceId()); + aq.setVnfType(vnfType); + + } + + if(ModelType.configuration.name().equalsIgnoreCase(requestScope)) { + aq.setConfigurationId(servInsReq.getConfigurationId()); + aq.setConfigurationName(requestInfo.getInstanceName()); + } + if(requestScope.equalsIgnoreCase(ModelType.instanceGroup.name())){ + aq.setInstanceGroupId(servInsReq.getInstanceGroupId()); + aq.setInstanceGroupName(requestInfo.getInstanceName()); + } + if(ModelType.vnf.name().equalsIgnoreCase(requestScope)){ + aq.setVnfName(requestInfo.getInstanceName()); + if (null != servInsReq.getRequestDetails()) { + RelatedInstanceList[] instanceList = servInsReq.getRequestDetails().getRelatedInstanceList(); + + if (instanceList != null) { + + for(RelatedInstanceList relatedInstanceList : instanceList){ + + RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); + if(relatedInstance.getModelInfo().getModelType().equals(ModelType.service)){ + aq.setVnfType(vnfType); + } } } } - } + } } aq.setRequestBody (originalRequestJSON); @@ -386,6 +400,7 @@ public class MsoRequest { aq.setRequestId (requestId); aq.setRequestAction(action.name()); aq.setAction(action.name()); + aq.setRequestUrl(MDC.get(LogConstants.HTTP_URL)); Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis()); @@ -429,6 +444,7 @@ public class MsoRequest { request.setRequestBody(requestJSON); Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis()); request.setEndTime(endTimeStamp); + request.setRequestUrl(MDC.get(LogConstants.HTTP_URL)); requestsDbClient.save(request); } catch (Exception e) { msoLogger.error(MessageEnum.APIH_DB_UPDATE_EXC, e.getMessage(), "", "", MsoLogger.ErrorCode.DataError, "Exception when updating record in DB"); @@ -742,4 +758,23 @@ public class MsoRequest { return vnfType; } + + public Optional<URL> buildSelfLinkUrl(String url, String requestId) { + Optional<URL> selfLinkUrl = Optional.empty(); + String version = ""; + try { + URL aUrl = new URL(url); + String aPath = aUrl.getPath(); + if (aPath.indexOf("/v") == -1) { + version = aPath.substring(aPath.indexOf("/V"), aPath.indexOf("/V")+4); + } else { + version = aPath.substring(aPath.indexOf("/v"), aPath.indexOf("/v")+4); + } + String selfLinkPath = Constants.ORCHESTRATION_REQUESTS_PATH.concat(version).concat(requestId); + selfLinkUrl = Optional.of(new URL(aUrl.getProtocol(), aUrl.getHost(), aUrl.getPort(), selfLinkPath)); + } catch (Exception e) { + selfLinkUrl = Optional.empty(); // ignore + } + return selfLinkUrl; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java new file mode 100644 index 0000000000..cfdce473a4 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java @@ -0,0 +1,42 @@ +/*- + * ============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.apihandlerinfra; + +public enum MsoSubsystems { + APIH ("API Handler"), + ASDC ("ASDC Controller"), + BPMN ("BPMN Infra"), + CATALOGDB ("CatalogDb Adapter"), + OPENSTACK ("Openstack Adapter"), + REQUESTDB ("RequestDB Adapter"), + REQUESTDBATT ("RequestDB Adapter ATT Svc"), + SDNC ("SDNC Adapter"); + private String subsystem; + private MsoSubsystems(String subsystem){ + this.subsystem = subsystem; + } + + @Override + public String toString(){ + return subsystem; + } + +} + diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java index 50d2639b2d..b65b82a87d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java @@ -46,14 +46,14 @@ import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandlerinfra.exceptions.ApiException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; -import org.onap.so.apihandlerinfra.logging.AlarmLoggerInfo; + import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.beans.RequestProcessingData; import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.exceptions.ValidationException; import org.onap.so.logger.MessageEnum; -import org.onap.so.logger.MsoAlarmLogger; + import org.onap.so.logger.MsoLogger; import org.onap.so.serviceinstancebeans.GetOrchestrationListResponse; import org.onap.so.serviceinstancebeans.GetOrchestrationResponse; @@ -108,12 +108,13 @@ public class OrchestrationRequests { } catch (Exception e) { msoLogger.error(e); ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, MsoLogger.ErrorCode.AvailabilityError).build(); - AlarmLoggerInfo alarmLoggerInfo = new AlarmLoggerInfo.Builder("MsoDatabaseAccessError", MsoAlarmLogger.CRITICAL, Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB)).build(); + ValidateException validateException = new ValidateException.Builder("Exception while communciate with Request DB - Infra Request Lookup", - HttpStatus.SC_NOT_FOUND,ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e).errorInfo(errorLoggerInfo).alarmInfo(alarmLoggerInfo).build(); + HttpStatus.SC_NOT_FOUND,ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e).errorInfo(errorLoggerInfo).build(); + throw validateException; @@ -270,6 +271,10 @@ public class OrchestrationRequests { request.setRequestId(iar.getRequestId()); request.setRequestScope(iar.getRequestScope()); request.setRequestType(iar.getRequestAction()); + String rollbackStatusMessage = iar.getRollbackStatusMessage(); + String flowStatusMessage = iar.getFlowStatus(); + String retryStatusMessage = iar.getRetryStatusMessage(); + InstanceReferences ir = new InstanceReferences(); if(iar.getNetworkId() != null) @@ -294,6 +299,11 @@ public class OrchestrationRequests { ir.setVolumeGroupInstanceName(iar.getVolumeGroupName()); if(iar.getRequestorId() != null) ir.setRequestorId(iar.getRequestorId()); + if(iar.getInstanceGroupId() != null) + ir.setInstanceGroupId(iar.getInstanceGroupId()); + if(iar.getInstanceGroupName() != null) + ir.setInstanceGroupName(iar.getInstanceGroupName()); + request.setInstanceReferences(ir); @@ -323,15 +333,42 @@ public class OrchestrationRequests { String startTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getStartTime()) + " GMT"; request.setStartTime(startTimeStamp); } - + if(iar.getEndTime() != null){ + String endTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getEndTime()) + " GMT"; + request.setFinishTime(endTimeStamp); + } + String statusMessages = null; RequestStatus status = new RequestStatus(); if(iar.getStatusMessage() != null){ - status.setStatusMessage(iar.getStatusMessage()); + statusMessages = "STATUS: " + iar.getStatusMessage(); } - - if(iar.getEndTime() != null){ - String endTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getEndTime()) + " GMT"; - status.setFinishTime(endTimeStamp); + if(flowStatusMessage != null){ + if(statusMessages != null){ + statusMessages = statusMessages + " " + "FLOW STATUS: " + flowStatusMessage; + }else{ + statusMessages = "FLOW STATUS: " + flowStatusMessage; + } + } + if(retryStatusMessage != null){ + if(statusMessages != null){ + statusMessages = statusMessages + " " + "RETRY STATUS: " + retryStatusMessage; + }else{ + statusMessages = "RETRY STATUS: " + retryStatusMessage; + } + } + if(rollbackStatusMessage != null){ + if(statusMessages != null){ + statusMessages = statusMessages + " " + "ROLLBACK STATUS: " + rollbackStatusMessage; + }else{ + statusMessages = "ROLLBACK STATUS: " + rollbackStatusMessage; + } + } + if(statusMessages != null){ + status.setStatusMessage(statusMessages); + } + if(iar.getModifyTime() != null){ + String timeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getModifyTime()) + " GMT"; + status.setTimeStamp(timeStamp); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java index 04a707c4ad..66b04b6fdb 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java @@ -32,6 +32,7 @@ import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.apihandler.camundabeans.CamundaResponse; import org.onap.so.apihandler.common.CommonConstants; import org.onap.so.apihandler.common.ErrorNumbers; @@ -43,6 +44,7 @@ import org.onap.so.apihandler.common.ResponseHandler; import org.onap.so.apihandlerinfra.exceptions.ApiException; import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; import org.onap.so.apihandlerinfra.exceptions.ClientConnectionException; +import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException; import org.onap.so.apihandlerinfra.exceptions.RecipeNotFoundException; import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; @@ -62,6 +64,7 @@ import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.exceptions.ValidationException; +import org.onap.so.logger.LogConstants; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; import org.onap.so.serviceinstancebeans.CloudConfiguration; @@ -79,9 +82,19 @@ import org.onap.so.serviceinstancebeans.ServiceInstancesResponse; import org.onap.so.serviceinstancebeans.VfModules; import org.onap.so.serviceinstancebeans.Vnfs; import org.onap.so.utils.UUIDChecker; +import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.RestTemplate; +import org.camunda.bpm.engine.history.HistoricProcessInstance; +import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity; import javax.transaction.Transactional; import javax.ws.rs.Consumes; @@ -94,8 +107,10 @@ import javax.ws.rs.Produces; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import java.io.IOException; +import java.net.URL; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; @@ -131,6 +146,9 @@ public class ServiceInstances { @Autowired private MsoRequest msoRequest; + @Autowired + private RestTemplate restTemplate; + @POST @Path("/{version:[vV][5-7]}/serviceInstances") @Consumes(MediaType.APPLICATION_JSON) @@ -611,12 +629,77 @@ public class ServiceInstances { instanceIdMap.put("networkInstanceId", networkInstanceId); return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); } + + @POST + @Path("/{version:[vV][7]}/instanceGroups") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value="Create instanceGroups",response=Response.class) + @Transactional + public Response createInstanceGroups(String request, @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = getRequestId(requestContext); + return serviceInstances(request, Action.createInstance, null, version, requestId, getRequestUri(requestContext)); + } + + @DELETE + @Path("/{version:[vV][7]}/instanceGroups/{instanceGroupId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value="Delete instanceGroup",response=Response.class) + @Transactional + public Response deleteInstanceGroups(@PathParam("version") String version, @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put(CommonConstants.INSTANCE_GROUP_ID, instanceGroupId); + return deleteInstanceGroups(Action.deleteInstance, instanceIdMap, version, requestId, getRequestUri(requestContext), requestContext); + } + + @POST + @Path("/{version:[vV][7]}/instanceGroups/{instanceGroupId}/addMembers") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value="Add instanceGroup members",response=Response.class) + @Transactional + public Response addInstanceGroupMembers(String request, @PathParam("version") String version, @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put(CommonConstants.INSTANCE_GROUP_ID, instanceGroupId); + return serviceInstances(request, Action.addMembers, instanceIdMap, version, requestId, getRequestUri(requestContext)); + } + + @POST + @Path("/{version:[vV][7]}/instanceGroups/{instanceGroupId}/removeMembers") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value="Remove instanceGroup members",response=Response.class) + @Transactional + public Response removeInstanceGroupMembers(String request, @PathParam("version") String version, @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put(CommonConstants.INSTANCE_GROUP_ID, instanceGroupId); + return serviceInstances(request, Action.removeMembers, instanceIdMap, version, requestId, getRequestUri(requestContext)); + } public String getRequestUri(ContainerRequestContext context){ String requestUri = context.getUriInfo().getPath(); + String httpUrl = MDC.get(LogConstants.URI_BASE).concat(requestUri); + MDC.put(LogConstants.HTTP_URL, httpUrl); requestUri = requestUri.substring(requestUri.indexOf("/serviceInstantiation/") + 22); return requestUri; } + + public void validateHeaders(ContainerRequestContext context) throws ValidationException{ + MultivaluedMap<String, String> headers = context.getHeaders(); + if(!headers.containsKey(ONAPLogConstants.Headers.REQUEST_ID)){ + throw new ValidationException(ONAPLogConstants.Headers.REQUEST_ID + " header", true); + } + if(!headers.containsKey(ONAPLogConstants.Headers.PARTNER_NAME)){ + throw new ValidationException(ONAPLogConstants.Headers.PARTNER_NAME + " header", true); + } + if(!headers.containsKey(MsoLogger.REQUESTOR_ID)){ + throw new ValidationException(MsoLogger.REQUESTOR_ID + " header", true); + } + } public Response serviceInstances(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri) throws ApiException { String serviceInstanceId = (instanceIdMap ==null)? null:instanceIdMap.get("serviceInstanceId"); @@ -624,10 +707,10 @@ public class ServiceInstances { long startTime = System.currentTimeMillis (); ServiceInstancesRequest sir = null; String apiVersion = version.substring(1); - + sir = convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, requestId, requestUri); String requestScope = deriveRequestScope(action, sir, requestUri); - InfraActiveRequests currentActiveReq = msoRequest.createRequestObject (sir, action, requestId, Status.PENDING, requestJSON, requestScope); + InfraActiveRequests currentActiveReq = msoRequest.createRequestObject (sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); if(sir.getRequestDetails().getRequestParameters() != null){ aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte(); } @@ -640,7 +723,6 @@ public class ServiceInstances { String vnfType = msoRequest.getVnfType(sir,requestScope,action,requestVersion); String networkType = msoRequest.getNetworkType(sir,requestScope); String sdcServiceModelVersion = msoRequest.getSDCServiceModelVersion(sir); - String serviceInstanceType = msoRequest.getServiceInstanceType(sir,requestScope); String vfModuleType = msoRequest.getVfModuleType(sir,requestScope,action,requestVersion); if(requestScope.equalsIgnoreCase(ModelType.vnf.name()) && vnfType != null){ @@ -650,11 +732,15 @@ public class ServiceInstances { } InfraActiveRequests dup = null; - + boolean inProgress = false; dup = duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName,requestScope, currentActiveReq); - if (dup != null) { + if(dup != null){ + inProgress = camundaHistoryCheck(dup, currentActiveReq); + } + + if (dup != null && inProgress) { buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, msoRequest, instanceName, requestScope, dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); @@ -667,11 +753,13 @@ public class ServiceInstances { Boolean isBaseVfModule = false; RecipeLookupResult recipeLookupResult = getServiceInstanceOrchestrationURI(sir, action, alaCarteFlag, currentActiveReq); - + String serviceInstanceType = getServiceType(requestScope, sir, alaCarteFlag); ModelType modelType; ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) { modelType = ModelType.vnf; + }else if(action == Action.addMembers || action == Action.removeMembers){ + modelType = ModelType.instanceGroup; }else { modelType =modelInfo.getModelType(); } @@ -719,7 +807,7 @@ public class ServiceInstances { String volumeGroupId = ""; String networkId = ""; String correlationId = ""; - + String instanceGroupId = null; if(sir.getServiceInstanceId () != null){ serviceInstanceId = sir.getServiceInstanceId (); } @@ -739,6 +827,9 @@ public class ServiceInstances { if(sir.getNetworkInstanceId () != null){ networkId = sir.getNetworkInstanceId (); } + if(sir.getInstanceGroupId() != null){ + instanceGroupId = sir.getInstanceGroupId(); + } correlationId = getCorrelationId(sir); @@ -750,15 +841,104 @@ public class ServiceInstances { .errorInfo(errorLoggerInfo).build(); } - if(!requestScope.equalsIgnoreCase(ModelType.service.name())){ + if(!requestScope.equalsIgnoreCase(ModelType.service.name()) && action != Action.recreateInstance){ aLaCarte = true; }else if(aLaCarte == null){ aLaCarte = false; } - return postBPELRequest(currentActiveReq,action, requestId, startTime, requestJSON, recipeLookupResult.getOrchestrationURI(), recipeLookupResult.getRecipeTimeout(), - isBaseVfModule, serviceInstanceId, correlationId, vnfId, vfModuleId, volumeGroupId, networkId, null, - serviceInstanceType,vnfType, vfModuleType,networkType, apiVersion, aLaCarte, requestUri, null, requestScope, sir); + RequestClientParameter requestClientParameter = null; + try { + requestClientParameter = new RequestClientParameter.Builder() + .setRequestId(requestId) + .setBaseVfModule(isBaseVfModule) + .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) + .setRequestAction(action.toString()) + .setServiceInstanceId(serviceInstanceId) + .setCorrelationId(correlationId) + .setVnfId(vnfId) + .setVfModuleId(vfModuleId) + .setVolumeGroupId(volumeGroupId) + .setNetworkId(networkId) + .setServiceType(serviceInstanceType) + .setVnfType(vnfType) + .setVfModuleType(vfModuleType) + .setNetworkType(networkType) + .setRequestDetails(mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action)) + .setApiVersion(apiVersion) + .setALaCarte(aLaCarte) + .setRequestUri(requestUri) + .setInstanceGroupId(instanceGroupId).build(); + } catch (IOException e) { + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, MsoLogger.ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER) + .errorInfo(errorLoggerInfo).build(); + } + return postBPELRequest(currentActiveReq, requestClientParameter, recipeLookupResult.getOrchestrationURI(), requestScope); + } + public Response deleteInstanceGroups(Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri, ContainerRequestContext requestContext) throws ApiException { + String instanceGroupId = instanceIdMap.get(CommonConstants.INSTANCE_GROUP_ID); + Boolean aLaCarte = true; + long startTime = System.currentTimeMillis (); + String apiVersion = version.substring(1); + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + sir.setInstanceGroupId(instanceGroupId); + + String requestScope = ModelType.instanceGroup.toString(); + InfraActiveRequests currentActiveReq = msoRequest.createRequestObject (sir, action, requestId, Status.IN_PROGRESS, null, requestScope); + setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); + try { + validateHeaders(requestContext); + } catch (ValidationException e) { + msoLogger.error(e); + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, MsoLogger.ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) + .errorInfo(errorLoggerInfo).build(); + updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + throw validateException; + } + + InfraActiveRequests dup = duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, requestScope, currentActiveReq); + boolean inProgress = false; + + if(dup != null){ + inProgress = camundaHistoryCheck(dup, currentActiveReq); + } + + if (dup != null && inProgress) { + buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, msoRequest, null, requestScope, dup); + } + + ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); + + RequestReferences referencesResponse = new RequestReferences(); + + referencesResponse.setRequestId(requestId); + + serviceResponse.setRequestReferences(referencesResponse); + Boolean isBaseVfModule = false; + + RecipeLookupResult recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180); + + try{ + infraActiveRequestsClient.save(currentActiveReq); + }catch(Exception e){ + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, MsoLogger.ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e) + .errorInfo(errorLoggerInfo).build(); + } + + RequestClientParameter requestClientParameter = new RequestClientParameter.Builder() + .setRequestId(requestId) + .setBaseVfModule(isBaseVfModule) + .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) + .setRequestAction(action.toString()) + .setApiVersion(apiVersion) + .setALaCarte(aLaCarte) + .setRequestUri(requestUri) + .setInstanceGroupId(instanceGroupId).build(); + + return postBPELRequest(currentActiveReq, requestClientParameter, recipeLookupResult.getOrchestrationURI(), requestScope); } private String getCorrelationId(ServiceInstancesRequest sir) { @@ -772,6 +952,8 @@ public class ServiceInstances { private String deriveRequestScope(Actions action, ServiceInstancesRequest sir, String requestUri) { if(action == Action.inPlaceSoftwareUpdate || action == Action.applyUpdatedConfig){ return (ModelType.vnf.name()); + }else if(action == Action.addMembers || action == Action.removeMembers){ + return(ModelType.instanceGroup.toString()); }else{ String requestScope; if(sir.getRequestDetails().getModelInfo().getModelType() == null){ @@ -799,38 +981,12 @@ public class ServiceInstances { } return requestScope; } - private Response postBPELRequest(InfraActiveRequests currentActiveReq, Actions action, String requestId, long startTime, String msoRawRequest, - String orchestrationUri, int timeOut, Boolean isBaseVfModule, - String serviceInstanceId, String correlationId, String vnfId, String vfModuleId, String volumeGroupId, String networkId, - String configurationId, String serviceInstanceType, String vnfType, String vfModuleType, String networkType, - String apiVersion, boolean aLaCarte, String requestUri, String paramXsd, String requestScope, ServiceInstancesRequest sir) throws ApiException { + private Response postBPELRequest(InfraActiveRequests currentActiveReq, RequestClientParameter requestClientParameter, String orchestrationUri, String requestScope)throws ApiException { RequestClient requestClient = null; HttpResponse response = null; try { requestClient = reqClientFactory.getRequestClient (orchestrationUri); - response = requestClient.post(new RequestClientParameter.Builder() - .setRequestId(requestId) - .setBaseVfModule(isBaseVfModule) - .setRecipeTimeout(timeOut) - .setRequestAction(action.toString()) - .setServiceInstanceId(serviceInstanceId) - .setCorrelationId(correlationId) - .setVnfId(vnfId) - .setVfModuleId(vfModuleId) - .setVolumeGroupId(volumeGroupId) - .setNetworkId(networkId) - .setConfigurationId(configurationId) - .setServiceType(serviceInstanceType) - .setVnfType(vnfType) - .setVfModuleType(vfModuleType) - .setNetworkType(networkType) - .setRequestDetails(mapJSONtoMSOStyle(msoRawRequest, sir, aLaCarte, action)) - .setApiVersion(apiVersion) - .setALaCarte(aLaCarte) - .setRecipeParamXsd(paramXsd) - .setRequestUri(requestUri).build()); - - + response = requestClient.post(requestClientParameter); } catch (Exception e) { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.AvailabilityError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); @@ -874,6 +1030,13 @@ public class ServiceInstances { try { ObjectMapper mapper = new ObjectMapper(); jsonResponse = mapper.readValue(camundaResp.getResponse(), ServiceInstancesResponse.class); + jsonResponse.getRequestReferences().setRequestId(requestClientParameter.getRequestId()); + Optional<URL> selfLinkUrl = msoRequest.buildSelfLinkUrl(currentActiveReq.getRequestUrl(), requestClientParameter.getRequestId()); + if(selfLinkUrl.isPresent()){ + jsonResponse.getRequestReferences().setRequestSelfLink(selfLinkUrl.get()); + } else { + jsonResponse.getRequestReferences().setRequestSelfLink(null); + } } catch (IOException e) { msoLogger.error(e); ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, MsoLogger.ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); @@ -881,19 +1044,8 @@ public class ServiceInstances { .errorInfo(errorLoggerInfo).build(); updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); throw validateException; - } - - currentActiveReq.setRequestStatus(Status.IN_PROGRESS.name()); - setInstanceId(currentActiveReq, requestScope, jsonResponse.getRequestReferences().getInstanceId(), new HashMap<>()); - - try{ - infraActiveRequestsClient.save(currentActiveReq); - }catch(Exception e){ - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, MsoLogger.ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e) - .errorInfo(errorLoggerInfo).build(); - } - return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestId, jsonResponse, apiVersion); + } + return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestClientParameter.getRequestId(), jsonResponse, requestClientParameter.getApiVersion()); } } @@ -936,6 +1088,8 @@ public class ServiceInstances { currentActiveReq.setNetworkId(instanceId); } else if(ModelType.configuration.name().equalsIgnoreCase(requestScope)) { currentActiveReq.setConfigurationId(instanceId); + }else if(ModelType.instanceGroup.toString().equalsIgnoreCase(requestScope)){ + currentActiveReq.setInstanceGroupId(instanceId); } } else if(instanceIdMap != null && !instanceIdMap.isEmpty()) { if(instanceIdMap.get("serviceInstanceId") != null){ @@ -956,21 +1110,27 @@ public class ServiceInstances { if(instanceIdMap.get("configurationInstanceId") != null){ currentActiveReq.setConfigurationId(instanceIdMap.get("configurationInstanceId")); } + if(instanceIdMap.get("InstanceGroupInstanceId") != null){ + currentActiveReq.setInstanceGroupId(instanceIdMap.get("InstanceGroupInstanceId")); + } } } protected String mapJSONtoMSOStyle(String msoRawRequest, ServiceInstancesRequest serviceInstRequest, boolean isAlaCarte, Actions action) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); - ServiceInstancesRequest sir = mapper.readValue(msoRawRequest, ServiceInstancesRequest.class); - if( !isAlaCarte && Action.createInstance.equals(action) && serviceInstRequest != null && - serviceInstRequest.getRequestDetails() != null && - serviceInstRequest.getRequestDetails().getRequestParameters() != null) { - sir.getRequestDetails().setCloudConfiguration(serviceInstRequest.getRequestDetails().getCloudConfiguration()); - sir.getRequestDetails().getRequestParameters().setUserParams(serviceInstRequest.getRequestDetails().getRequestParameters().getUserParams()); + if(msoRawRequest != null){ + ServiceInstancesRequest sir = mapper.readValue(msoRawRequest, ServiceInstancesRequest.class); + if( !isAlaCarte && Action.createInstance.equals(action) && serviceInstRequest != null && + serviceInstRequest.getRequestDetails() != null && + serviceInstRequest.getRequestDetails().getRequestParameters() != null) { + sir.getRequestDetails().setCloudConfiguration(serviceInstRequest.getRequestDetails().getCloudConfiguration()); + sir.getRequestDetails().getRequestParameters().setUserParams(serviceInstRequest.getRequestDetails().getRequestParameters().getUserParams()); + } + msoLogger.debug("Value as string: " + mapper.writeValueAsString(sir)); + return mapper.writeValueAsString(sir); } - msoLogger.debug("Value as string: " + mapper.writeValueAsString(sir)); - return mapper.writeValueAsString(sir); + return null; } private void buildErrorOnDuplicateRecord(InfraActiveRequests currentActiveReq, Actions action, HashMap<String, String> instanceIdMap, long startTime, MsoRequest msoRequest, @@ -1012,6 +1172,42 @@ public class ServiceInstances { } return dup; } + protected boolean camundaHistoryCheck(InfraActiveRequests duplicateRecord, InfraActiveRequests currentActiveReq) throws RequestDbFailureException, ContactCamundaException{ + String requestId = duplicateRecord.getRequestId(); + String path = env.getProperty("mso.camunda.rest.history.uri") + requestId; + String targetUrl = env.getProperty("mso.camundaURL") + path; + HttpHeaders headers = setHeaders(env.getProperty("mso.camundaAuth")); + HttpEntity<?> requestEntity = new HttpEntity<>(headers); + ResponseEntity<List<HistoricProcessInstanceEntity>> response = null; + try{ + response = restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>(){}); + }catch(HttpStatusCodeException e){ + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, MsoLogger.ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ContactCamundaException contactCamundaException= new ContactCamundaException.Builder(requestId, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e) + .errorInfo(errorLoggerInfo).build(); + updateStatus(currentActiveReq, Status.FAILED, contactCamundaException.getMessage()); + throw contactCamundaException; + } + if(response.getBody().isEmpty()){ + updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed"); + } + for(HistoricProcessInstance instance : response.getBody()){ + if(instance.getState().equals("ACTIVE")){ + return true; + }else{ + updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed"); + } + } + return false; + } + private HttpHeaders setHeaders(String auth) { + HttpHeaders headers = new HttpHeaders(); + List<org.springframework.http.MediaType> acceptableMediaTypes = new ArrayList<>(); + acceptableMediaTypes.add(org.springframework.http.MediaType.APPLICATION_JSON); + headers.setAccept(acceptableMediaTypes); + headers.add(HttpHeaders.AUTHORIZATION, auth); + return headers; + } private ServiceInstancesRequest convertJsonToServiceInstanceRequest(String requestJSON, Actions action, long startTime, ServiceInstancesRequest sir, MsoRequest msoRequest, String requestId, String requestUri) throws ApiException { @@ -1058,7 +1254,9 @@ public class ServiceInstances { if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) { recipeLookupResult = getDefaultVnfUri(sir, action); - } else if (modelInfo.getModelType().equals(ModelType.service)) { + }else if(action == Action.addMembers || action == Action.removeMembers){ + recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180); + }else if (modelInfo.getModelType().equals(ModelType.service)) { try { recipeLookupResult = getServiceURI(sir, action,alaCarteFlag); } catch (IOException e) { @@ -1100,7 +1298,9 @@ public class ServiceInstances { updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); throw validateException; - } + } + }else if(modelInfo.getModelType().equals(ModelType.instanceGroup)){ + recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180); } if (recipeLookupResult == null) { @@ -1534,14 +1734,14 @@ public class ServiceInstances { NetworkResourceCustomization networkResourceCustomization = catalogDbClient.getNetworkResourceCustomizationByModelCustomizationUUID(modelInfo.getModelCustomizationId()); if(networkResourceCustomization != null){ NetworkResource networkResource = networkResourceCustomization.getNetworkResource(); - if(networkResource!=null){ - if(modelInfo.getModelVersionId() == null) { - modelInfo.setModelVersionId(networkResource.getModelUUID()); - } - recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(networkResource.getModelName(), action.toString()); - }else{ - throw new ValidationException("no catalog entry found"); + if(networkResource!=null){ + if(modelInfo.getModelVersionId() == null) { + modelInfo.setModelVersionId(networkResource.getModelUUID()); } + recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(networkResource.getModelName(), action.toString()); + }else{ + throw new ValidationException("no catalog entry found"); + } }else if(action != Action.deleteInstance){ throw new ValidationException("modelCustomizationId for networkResourceCustomization lookup", true); } @@ -1597,6 +1797,7 @@ public class ServiceInstances { String serviceInstanceId = (instanceIdMap ==null)? null:instanceIdMap.get("serviceInstanceId"); Boolean aLaCarte = null; String apiVersion = version.substring(1); + boolean inProgress = false; long startTime = System.currentTimeMillis (); ServiceInstancesRequest sir = null; @@ -1614,8 +1815,12 @@ public class ServiceInstances { InfraActiveRequests dup = null; dup = duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName,requestScope, currentActiveReq); + + if(dup != null){ + inProgress = camundaHistoryCheck(dup, currentActiveReq); + } - if (instanceIdMap != null && dup != null) { + if (instanceIdMap != null && dup != null && inProgress) { buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, msoRequest, instanceName, requestScope, dup); } @@ -1670,12 +1875,30 @@ public class ServiceInstances { }else if(aLaCarte == null){ aLaCarte = false; } - - return postBPELRequest(currentActiveReq,action, requestId, startTime, requestJSON, orchestrationUri, Integer.parseInt(timeOut), false, - serviceInstanceId, correlationId, null, null, null, null, configurationId, null, null, null, null, apiVersion, aLaCarte, requestUri, null, requestScope, null); + RequestClientParameter requestClientParameter = null; + try { + requestClientParameter = new RequestClientParameter.Builder() + .setRequestId(requestId) + .setBaseVfModule(false) + .setRecipeTimeout(Integer.parseInt(timeOut)) + .setRequestAction(action.toString()) + .setServiceInstanceId(serviceInstanceId) + .setCorrelationId(correlationId) + .setConfigurationId(configurationId) + .setRequestDetails(mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action)) + .setApiVersion(apiVersion) + .setALaCarte(aLaCarte) + .setRequestUri(requestUri).build(); + } catch (IOException e) { + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, MsoLogger.ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER) + .errorInfo(errorLoggerInfo).build(); + } + + return postBPELRequest(currentActiveReq, requestClientParameter, orchestrationUri, requestScope); } - public String getRequestId(ContainerRequestContext requestContext) throws ValidateException { + public String getRequestId(ContainerRequestContext requestContext) throws ValidateException { String requestId = null; if (requestContext.getProperty("requestId") != null) { requestId = requestContext.getProperty("requestId").toString(); @@ -1706,4 +1929,30 @@ public class ServiceInstances { } } } + protected String getServiceType(String requestScope, ServiceInstancesRequest sir, Boolean aLaCarteFlag){ + String serviceType = null; + if(requestScope.equalsIgnoreCase(ModelType.service.toString())){ + String defaultServiceModelName = getDefaultModel(sir); + org.onap.so.db.catalog.beans.Service serviceRecord; + if(aLaCarteFlag){ + serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName); + if(serviceRecord != null){ + serviceType = serviceRecord.getServiceType(); + } + }else{ + serviceRecord = catalogDbClient.getServiceByID(sir.getRequestDetails().getModelInfo().getModelVersionId()); + if(serviceRecord != null){ + serviceType = serviceRecord.getServiceType(); + }else{ + serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName); + if(serviceRecord != null){ + serviceType = serviceRecord.getServiceType(); + } + } + } + }else{ + serviceType = msoRequest.getServiceInstanceType(sir, requestScope); + } + return serviceType; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SubsystemHealthcheckResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SubsystemHealthcheckResponse.java new file mode 100644 index 0000000000..625df66d2a --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SubsystemHealthcheckResponse.java @@ -0,0 +1,36 @@ +/*- + * ============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.apihandlerinfra; + +import java.io.Serializable; + +public class SubsystemHealthcheckResponse implements Serializable { + private static final long serialVersionUID = 1L; + private String status; + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java index 4900696546..f9e6c276ec 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java @@ -46,14 +46,14 @@ import org.onap.so.apihandler.common.ResponseHandler; import org.onap.so.apihandlerinfra.exceptions.ApiException; import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; -import org.onap.so.apihandlerinfra.logging.AlarmLoggerInfo; + import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.apihandlerinfra.tasksbeans.TaskList; import org.onap.so.apihandlerinfra.tasksbeans.TaskVariableValue; import org.onap.so.apihandlerinfra.tasksbeans.TaskVariables; import org.onap.so.apihandlerinfra.tasksbeans.TasksGetResponse; import org.onap.so.logger.MessageEnum; -import org.onap.so.logger.MsoAlarmLogger; + import org.onap.so.logger.MsoLogger; import org.onap.so.utils.UUIDChecker; import org.springframework.beans.factory.annotation.Autowired; @@ -71,7 +71,7 @@ import io.swagger.annotations.ApiOperation; @Component public class TasksHandler { - private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger (); + private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH,TasksHandler.class); @Value("${mso.camunda.rest.task.uri}") @@ -174,15 +174,7 @@ public class TasksHandler { throw validateException; } catch(IOException e) { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.AvailabilityError).build(); - AlarmLoggerInfo alarmLoggerInfo = new AlarmLoggerInfo.Builder("MsoConfigurationError", - MsoAlarmLogger.CRITICAL, - Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_BPEL)).build(); - - - - BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),HttpStatus.SC_BAD_GATEWAY,ErrorNumbers.SVC_NO_SERVER_RESOURCES) - .errorInfo(errorLoggerInfo).alarmInfo(alarmLoggerInfo).build(); - + BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),HttpStatus.SC_BAD_GATEWAY,ErrorNumbers.SVC_NO_SERVER_RESOURCES).build(); throw bpmnFailureException; } TasksGetResponse trr = new TasksGetResponse(); @@ -256,13 +248,7 @@ public class TasksHandler { getResponse = requestClient.get(); }catch(IOException e){ ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.AvailabilityError).build(); - AlarmLoggerInfo alarmLoggerInfo = new AlarmLoggerInfo.Builder("MsoConfigurationError", - MsoAlarmLogger.CRITICAL, Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_BPEL)).build(); - - - - BPMNFailureException validateException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES) - .errorInfo(errorLoggerInfo).alarmInfo(alarmLoggerInfo).build(); + BPMNFailureException validateException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build(); throw validateException; } ResponseHandler respHandler = new ResponseHandler (getResponse, requestClient.getType ()); @@ -274,24 +260,24 @@ public class TasksHandler { } else { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.AvailabilityError).build(); - AlarmLoggerInfo alarmLoggerInfo = new AlarmLoggerInfo.Builder("MsoConfigurationError", MsoAlarmLogger.CRITICAL, Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_BPEL)).build(); - BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES) - .errorInfo(errorLoggerInfo).alarmInfo(alarmLoggerInfo).build(); + + BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build(); + throw bpmnFailureException; } } else { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.AvailabilityError).build(); - AlarmLoggerInfo alarmLoggerInfo = new AlarmLoggerInfo.Builder("MsoConfigurationError", MsoAlarmLogger.CRITICAL, Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_BPEL)).build(); - BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus, ErrorNumbers.SVC_NO_SERVER_RESOURCES) - .errorInfo(errorLoggerInfo).alarmInfo(alarmLoggerInfo).build(); + + BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build(); + throw bpmnFailureException; } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java index f7d719048f..3aa54bdfb3 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java @@ -25,7 +25,7 @@ import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; +import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java index 2298ccdb26..908b864536 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java @@ -25,7 +25,7 @@ import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; +import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java index a35f40baf6..6d8ca96080 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java @@ -46,7 +46,7 @@ import org.onap.so.apihandlerinfra.Constants; import org.onap.so.apihandlerinfra.Messages; import org.onap.so.apihandlerinfra.exceptions.ApiException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; -import org.onap.so.apihandlerinfra.logging.AlarmLoggerInfo; + import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.apihandlerinfra.tenantisolationbeans.CloudOrchestrationRequestList; import org.onap.so.apihandlerinfra.tenantisolationbeans.CloudOrchestrationResponse; @@ -58,7 +58,7 @@ import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.exceptions.ValidationException; import org.onap.so.logger.MessageEnum; -import org.onap.so.logger.MsoAlarmLogger; + import org.onap.so.logger.MsoLogger; import org.onap.so.utils.UUIDChecker; import org.springframework.beans.factory.annotation.Autowired; @@ -117,13 +117,8 @@ public class CloudResourcesOrchestration { } try { infraActiveRequest = requestDbClient.getInfraActiveRequestbyRequestId(requestId); - }catch(Exception e){ - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, MsoLogger.ErrorCode.AvailabilityError).build(); - AlarmLoggerInfo alarmLoggerInfo = new AlarmLoggerInfo.Builder("MsoDatabaseAccessError", MsoAlarmLogger.CRITICAL, - Messages.getErrors().get (ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB)).build(); - ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e) - .errorInfo(errorLoggerInfo).alarmInfo(alarmLoggerInfo).build(); - + }catch(Exception e){ + ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).build(); throw validateException; } if(infraActiveRequest == null) { @@ -178,14 +173,9 @@ public class CloudResourcesOrchestration { requestDB = requestDbClient.getInfraActiveRequestbyRequestId(requestId); } catch (Exception e) { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, MsoLogger.ErrorCode.AvailabilityError).build(); - AlarmLoggerInfo alarmLoggerInfo = new AlarmLoggerInfo.Builder("MsoDatabaseAccessError", MsoAlarmLogger.CRITICAL, - Messages.getErrors().get (ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB)).build(); ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e) - .errorInfo(errorLoggerInfo).alarmInfo(alarmLoggerInfo).build(); - - throw validateException; - // TODO Will need to set Status for tenantIsolationRequest - // tenantIsolationRequest.setStatus (org.onap.so.apihandlerinfra.vnfbeans.RequestStatusType.FAILED); + .errorInfo(errorLoggerInfo).build(); + throw validateException; } if(requestDB == null) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/GrmClientPropertiesImpl.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/GrmClientPropertiesImpl.java index f83e707258..60a05d74e5 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/GrmClientPropertiesImpl.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/GrmClientPropertiesImpl.java @@ -32,15 +32,14 @@ import org.springframework.context.ApplicationContext; public class GrmClientPropertiesImpl implements GRMProperties { private String grmEndpoint; - private String grmUsername; - private String grmPassword; + private String grmAuth; + private String grmKey; public GrmClientPropertiesImpl() { - ApplicationContext context = SpringContextHelper.getAppContext(); - + ApplicationContext context = SpringContextHelper.getAppContext(); grmEndpoint = context.getEnvironment().getProperty("mso.grm.endpoint"); - grmUsername = context.getEnvironment().getProperty("mso.grm.username"); - grmPassword = context.getEnvironment().getProperty("mso.grm.password"); + grmAuth = context.getEnvironment().getProperty("mso.grm.auth"); + grmKey = context.getEnvironment().getProperty("mso.msoKey"); } @Override @@ -59,13 +58,13 @@ public class GrmClientPropertiesImpl implements GRMProperties { } @Override - public String getUsername() { - return grmUsername; + public String getAuth() { + return grmAuth; } @Override - public String getPassword() { - return grmPassword; + public String getKey() { + return grmKey; } @Override diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelper.java index 804eb696cb..5ead7ddd7f 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelper.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelper.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. @@ -20,6 +20,7 @@ package org.onap.so.apihandlerinfra.tenantisolation.helpers; +import java.net.URL; import java.util.UUID; import javax.ws.rs.core.Response; @@ -32,13 +33,12 @@ import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandlerinfra.exceptions.ApiException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; +import org.onap.so.client.HttpClient; +import org.onap.so.client.HttpClientFactory; import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; -import org.onap.so.rest.APIResponse; -import org.onap.so.rest.RESTClient; -import org.onap.so.rest.RESTConfig; -import org.onap.so.rest.RESTException; import org.onap.so.utils.CryptoUtils; +import org.onap.so.utils.TargetEntity; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @@ -47,12 +47,13 @@ public class SDCClientHelper { private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.APIH, SDCClientHelper.class); private static final String SDC_CONTENT_TYPE = "application/json"; - private static final String SDC_ACCEPT_TYPE = "application/json"; + private static final String SDC_ACCEPT_TYPE = "application/json"; private static String PARTIAL_SDC_URI = "/sdc/v1/catalog/services/"; - + private static String MESSAGE_UNDEFINED_ERROR = "Undefined Error Message!"; - private static String MESSAGE_UNEXPECTED_FORMAT = "Unexpected response format from SDC."; - + private static String MESSAGE_UNEXPECTED_FORMAT = "Unexpected response format from SDC."; + private final HttpClientFactory httpClientFactory = new HttpClientFactory(); + @Value("${mso.sdc.endpoint}") private String sdcEndpoint; @Value("${mso.sdc.activate.userid}") @@ -63,23 +64,23 @@ public class SDCClientHelper { private String sdcClientAuth; @Value("${mso.msoKey}") private String msoKey; - + /** * Send POST request to SDC for operational activation * @param serviceModelVersionI - String * @param operationalEnvironmentId - String - * @param workloadContext - String + * @param workloadContext - String * @return sdcResponseJsonObj - JSONObject object - * @throws JSONException - */ + * @throws JSONException + */ public JSONObject postActivateOperationalEnvironment(String serviceModelVersionId, String operationalEnvironmentId, String workloadContext) throws ApiException { JSONObject sdcResponseJsonObj = new JSONObject(); - + try { - String url = this.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId); + String urlString = this.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId); String jsonPayload = this.buildJsonWorkloadContext(workloadContext); String basicAuthCred = getBasicAuth(); - + if ( basicAuthCred == null || "".equals(basicAuthCred) ) { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build(); ValidateException validateException = new ValidateException.Builder(" SDC credentials 'mso.sdc.client.auth' not setup in properties file!", @@ -87,148 +88,140 @@ public class SDCClientHelper { throw validateException; } - - RESTConfig config = new RESTConfig(url); - RESTClient client = setRestClient(config); - client.addAuthorizationHeader(basicAuthCred); - - APIResponse apiResponse = setHttpPostResponse(client, jsonPayload); - int statusCode = apiResponse.getStatusCode(); - - String responseData = apiResponse.getResponseBodyAsString(); + + URL url = new URL(urlString); + + HttpClient httpClient = httpClientFactory.newJsonClient(url, TargetEntity.SDC); + httpClient.addBasicAuthHeader(sdcClientAuth, msoKey); + httpClient.addAdditionalHeader("X-ECOMP-InstanceID", sdcActivateInstanceId); + httpClient.addAdditionalHeader("X-ECOMP-RequestID", UUID.randomUUID().toString()); + httpClient.addAdditionalHeader("Content-Type", SDCClientHelper.SDC_CONTENT_TYPE); + httpClient.addAdditionalHeader("Accept", SDCClientHelper.SDC_ACCEPT_TYPE); + httpClient.addAdditionalHeader("USER_ID", sdcActivateUserId); + + Response apiResponse = setHttpPostResponse(httpClient, jsonPayload); + int statusCode = apiResponse.getStatus();; + + String responseData = apiResponse.readEntity(String.class); sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode); - + } catch (Exception ex) { msoLogger.debug("calling SDC Exception message: " + ex.getMessage()); String errorMessage = " Encountered Error while calling SDC POST Activate. " + ex.getMessage(); msoLogger.debug(errorMessage); - sdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())); - sdcResponseJsonObj.put("messageId", ""); + sdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())); + sdcResponseJsonObj.put("messageId", ""); sdcResponseJsonObj.put("message", errorMessage); } return sdcResponseJsonObj; } - - /** - * set RESTClient - * @param config - RESTConfig object - * @return client - RestClient object - */ - public RESTClient setRestClient(RESTConfig config) throws Exception { - RESTClient client = new RESTClient(config).addHeader("X-ECOMP-InstanceID", sdcActivateInstanceId) - .addHeader("X-ECOMP-RequestID", UUID.randomUUID().toString()) - .addHeader("Content-Type", SDCClientHelper.SDC_CONTENT_TYPE) - .addHeader("Accept", SDCClientHelper.SDC_ACCEPT_TYPE) - .addHeader("USER_ID", sdcActivateUserId); - return client; - } - + /** - * set HttpPostResponse + * set HttpPostResponse * @param config - RESTConfig object * @param jsonPayload - String * @return client - RestClient object - */ - public APIResponse setHttpPostResponse(RESTClient client, String jsonPayload) throws ApiException { + */ + public Response setHttpPostResponse(HttpClient client, String jsonPayload) throws ApiException { try { - return client.httpPost(jsonPayload); - }catch(RESTException ex){ + return client.post(jsonPayload); + }catch(Exception ex){ ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build(); ValidateException validateException = new ValidateException.Builder("Bad request could not post payload", HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build(); throw validateException; } - } - + } + /** - * enhance Response + * enhance Response * @param sdcResponseJsonObj - JSONObject object * @param statusCode - int * @return enhancedAsdcResponseJsonObj - JSONObject object - */ + */ public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) throws JSONException { JSONObject enhancedAsdcResponseJsonObj = new JSONObject(); String message = ""; - String messageId = ""; - + String messageId = ""; + if (statusCode == Response.Status.ACCEPTED.getStatusCode()) { // Accepted - enhancedAsdcResponseJsonObj.put("distributionId", sdcResponseJsonObj.get("distributionId")); + enhancedAsdcResponseJsonObj.put("distributionId", sdcResponseJsonObj.get("distributionId")); enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode)); enhancedAsdcResponseJsonObj.put("messageId", ""); - enhancedAsdcResponseJsonObj.put("message", "Success"); - + enhancedAsdcResponseJsonObj.put("message", "Success"); + } else { // error if (sdcResponseJsonObj.has("requestError") ) { JSONObject requestErrorObj = sdcResponseJsonObj.getJSONObject("requestError"); if (sdcResponseJsonObj.getJSONObject("requestError").has("serviceException") ) { message = requestErrorObj.getJSONObject("serviceException").getString("text"); messageId = requestErrorObj.getJSONObject("serviceException").getString("messageId"); - } + } if (sdcResponseJsonObj.getJSONObject("requestError").has("policyException") ) { message = requestErrorObj.getJSONObject("policyException").getString("text"); messageId = requestErrorObj.getJSONObject("policyException").getString("messageId"); } - enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode)); + enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode)); enhancedAsdcResponseJsonObj.put("messageId", messageId); enhancedAsdcResponseJsonObj.put("message", message); - } else { + } else { // unexpected format - enhancedAsdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())); + enhancedAsdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())); enhancedAsdcResponseJsonObj.put("messageId", MESSAGE_UNDEFINED_ERROR); enhancedAsdcResponseJsonObj.put("message", MESSAGE_UNEXPECTED_FORMAT); } } return enhancedAsdcResponseJsonObj; - + } - + /** - * Build Uri + * Build Uri * @param serviceModelVersionId - String * @param operationalEnvironmentId - String * @return uriBuilder - String - */ + */ public String buildUriBuilder(String serviceModelVersionId, String operationalEnvironmentId) { String path = serviceModelVersionId + "/distribution/" + operationalEnvironmentId +"/activate"; UriBuilder uriBuilder = UriBuilder.fromPath(sdcEndpoint + SDCClientHelper.PARTIAL_SDC_URI) .path(path); return uriBuilder.build().toString(); } - + /** - * Build JSON context + * Build JSON context * @param workloadContext - String * @return String json - * @throws JSONException - */ + * @throws JSONException + */ public String buildJsonWorkloadContext(String workloadContext) throws JSONException { return new JSONObject().put("workloadContext", workloadContext).toString(); - + } - + /** - * decrypt value + * decrypt value * @param toDecrypt - String * @param msokey - String * @return result - String - */ + */ public synchronized String decrypt(String toDecrypt, String msokey){ String result = null; try { result = CryptoUtils.decrypt(toDecrypt, msokey); - + } catch (Exception e) { msoLogger.debug("Failed to decrypt credentials: " + toDecrypt, e); } return result; } - + private String getBasicAuth() { return decrypt(sdcClientAuth, msoKey); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CloudConfigurationValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CloudConfigurationValidation.java index b0ea85779c..937ce19741 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CloudConfigurationValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CloudConfigurationValidation.java @@ -39,25 +39,26 @@ public class CloudConfigurationValidation implements ValidationRule{ Actions action = info.getAction(); Boolean aLaCarteFlag = info.getALaCarteFlag(); - - if(cloudConfiguration == null && reqVersion >= 5 && (aLaCarteFlag != null && aLaCarteFlag)){ - if((!requestScope.equalsIgnoreCase(ModelType.service.name()) && !requestScope.equalsIgnoreCase(ModelType.configuration.name())) && - (action == Action.createInstance || action == Action.deleteInstance || action == Action.updateInstance)){ - throw new ValidationException ("cloudConfiguration"); - } - if((requestScope.equalsIgnoreCase(ModelType.vnf.name()) || requestScope.equalsIgnoreCase(ModelType.vfModule.name())) && - action == Action.replaceInstance){ - throw new ValidationException ("cloudConfiguration"); - } - if(requestScope.equalsIgnoreCase(ModelType.configuration.name()) && - (action == Action.enablePort || action == Action.disablePort || action == Action.activateInstance || action == Action.deactivateInstance)){ - throw new ValidationException ("cloudConfiguration"); - } - if(requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && (action == Action.deactivateAndCloudDelete || action == Action.scaleOut)){ - throw new ValidationException("cloudConfiguration"); - } - if(requestScope.equals(ModelType.vnf.name()) && action == Action.recreateInstance){ - throw new ValidationException("cloudConfiguration", true); + if(!requestScope.equals(ModelType.instanceGroup.toString())){ + if(cloudConfiguration == null && reqVersion >= 5 && (aLaCarteFlag != null && aLaCarteFlag)){ + if((!requestScope.equalsIgnoreCase(ModelType.service.name()) && !requestScope.equalsIgnoreCase(ModelType.configuration.name())) && + (action == Action.createInstance || action == Action.deleteInstance || action == Action.updateInstance)){ + throw new ValidationException ("cloudConfiguration"); + } + if((requestScope.equalsIgnoreCase(ModelType.vnf.name()) || requestScope.equalsIgnoreCase(ModelType.vfModule.name())) && + action == Action.replaceInstance){ + throw new ValidationException ("cloudConfiguration"); + } + if(requestScope.equalsIgnoreCase(ModelType.configuration.name()) && + (action == Action.enablePort || action == Action.disablePort || action == Action.activateInstance || action == Action.deactivateInstance)){ + throw new ValidationException ("cloudConfiguration"); + } + if(requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && (action == Action.deactivateAndCloudDelete || action == Action.scaleOut)){ + throw new ValidationException("cloudConfiguration"); + } + if(requestScope.equals(ModelType.vnf.name()) && action == Action.recreateInstance){ + throw new ValidationException("cloudConfiguration", true); + } } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java index a42a13c676..f1985e9fcf 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java @@ -23,6 +23,7 @@ package org.onap.so.apihandlerinfra.validation; import java.util.HashMap; +import org.onap.so.apihandler.common.CommonConstants; import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.onap.so.utils.UUIDChecker; @@ -75,6 +76,13 @@ public class InstanceIdMapValidation implements ValidationRule{ } sir.setConfigurationId(instanceIdMap.get("configurationInstanceId")); } + + if(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_ID) != null){ + if (!UUIDChecker.isValidUUID (instanceIdMap.get (CommonConstants.INSTANCE_GROUP_ID))) { + throw new ValidationException (CommonConstants.INSTANCE_GROUP_ID, true); + } + sir.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_ID)); + } } return info; } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/MembersValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/MembersValidation.java new file mode 100644 index 0000000000..89bb15dcb1 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/MembersValidation.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. 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.apihandlerinfra.validation; + +import org.onap.so.exceptions.ValidationException; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.RelatedInstance; +import org.onap.so.serviceinstancebeans.RelatedInstanceList; +import org.onap.so.serviceinstancebeans.RequestInfo; + +public class MembersValidation implements ValidationRule{ + private static boolean empty(String s) { + return (s == null || s.trim().isEmpty()); + } + @Override + public ValidationInformation validate(ValidationInformation info) throws ValidationException{ + RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo(); + RelatedInstanceList[] relatedInstanceList = info.getSir().getRequestDetails().getRelatedInstanceList(); + boolean vnfRelatedInstance = false; + + if(requestInfo == null){ + throw new ValidationException("requestInfo", true); + }else if(empty(requestInfo.getRequestorId())) { + throw new ValidationException ("requestorId", true); + }else if (empty (requestInfo.getSource ())) { + throw new ValidationException ("source", true); + } + if(relatedInstanceList == null){ + throw new ValidationException("related instances", true); + }else{ + for(RelatedInstanceList instanceList : relatedInstanceList){ + RelatedInstance relatedInstance = instanceList.getRelatedInstance(); + ModelType modelType = relatedInstance.getModelInfo().getModelType(); + if(empty(relatedInstance.getInstanceId())){ + throw new ValidationException("instanceId in relatedInstances", true); + } + if (modelType == null) { + throw new ValidationException("modelType in relatedInstance", true); + } + if(modelType == ModelType.vnf){ + vnfRelatedInstance = true; + } + } + if(!vnfRelatedInstance){ + throw new ValidationException("vnf relatedInstance", true); + } + } + return info; + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ModelInfoValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ModelInfoValidation.java index c6fae6e872..e2a1bdc46a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ModelInfoValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ModelInfoValidation.java @@ -30,9 +30,9 @@ import org.onap.so.serviceinstancebeans.ModelType; import org.onap.so.serviceinstancebeans.RequestParameters; import org.onap.so.utils.UUIDChecker; public class ModelInfoValidation implements ValidationRule{ - private static boolean empty(String s) { - return (s == null || s.trim().isEmpty()); - } + private static boolean empty(String s) { + return (s == null || s.trim().isEmpty()); + } @Override public ValidationInformation validate(ValidationInformation info) throws ValidationException{ ModelInfo modelInfo = info.getSir().getRequestDetails().getModelInfo(); @@ -42,89 +42,96 @@ public class ModelInfoValidation implements ValidationRule{ int reqVersion = info.getReqVersion(); Boolean aLaCarteFlag = info.getALaCarteFlag(); - if(!empty(modelInfo.getModelNameVersionId())){ - modelInfo.setModelVersionId(modelInfo.getModelNameVersionId()); - } - // modelCustomizationId is required when usePreLoad is false for v4 and higher for VF Module Create - if(requestParameters != null && reqVersion >= 4 && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.createInstance && !requestParameters.isUsePreload()) { - if(!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) { - throw new ValidationException("modelCustomizationId"); - } - } - - // modelCustomizationId is required for v5 and higher for VF Module Replace - if(requestParameters != null && reqVersion > 4 && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.replaceInstance) { - if(!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) { - throw new ValidationException("modelCustomizationId"); - } - } - - // modelCustomizationId or modelCustomizationName are required for VNF Replace - if(requestParameters != null && reqVersion > 4 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.replaceInstance || action == Action.recreateInstance) { - if(!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId()) && modelInfo.getModelCustomizationName() == null) { - throw new ValidationException("modelCustomizationId or modelCustomizationName"); - } - } + if(!requestScope.equals(ModelType.instanceGroup.toString())){ + + if(!empty(modelInfo.getModelNameVersionId())){ + modelInfo.setModelVersionId(modelInfo.getModelNameVersionId()); + } + // modelCustomizationId is required when usePreLoad is false for v4 and higher for VF Module Create + if(requestParameters != null && reqVersion >= 4 && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.createInstance && !requestParameters.isUsePreload()) { + if(!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) { + throw new ValidationException("modelCustomizationId"); + } + } + + // modelCustomizationId is required for v5 and higher for VF Module Replace + if(requestParameters != null && reqVersion > 4 && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.replaceInstance) { + if(!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) { + throw new ValidationException("modelCustomizationId"); + } + } + + // modelCustomizationId or modelCustomizationName are required for VNF Replace + if(requestParameters != null && reqVersion > 4 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.replaceInstance || action == Action.recreateInstance) { + if(!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId()) && modelInfo.getModelCustomizationName() == null) { + throw new ValidationException("modelCustomizationId or modelCustomizationName"); + } + } + + //is required for serviceInstance delete macro when aLaCarte=false (v3) + //create and updates except for network (except v4) + if (empty (modelInfo.getModelInvariantId ()) && ((reqVersion >2 && (aLaCarteFlag != null && !aLaCarteFlag) && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance) || + !(reqVersion < 4 && requestScope.equalsIgnoreCase (ModelType.network.name ())) && + (action == Action.createInstance || action == Action.updateInstance || action == Action.enablePort || action == Action.disablePort || action == Action.addRelationships || action == Action.removeRelationships || + (requestScope.equalsIgnoreCase(ModelType.configuration.name()) && (action == Action.activateInstance || action == Action.deactivateInstance))))) { + throw new ValidationException ("modelInvariantId"); + } + if(empty(modelInfo.getModelInvariantId()) && (requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut)){ + throw new ValidationException("modelInvariantId"); + } + if(empty(modelInfo.getModelInvariantId()) && (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.recreateInstance)){ + throw new ValidationException("modelInvariantId", true); + } + if (!empty (modelInfo.getModelInvariantId ()) && !UUIDChecker.isValidUUID (modelInfo.getModelInvariantId ())) { + throw new ValidationException ("modelInvariantId format"); + } + + if(reqVersion >= 4 && !(requestScope.equalsIgnoreCase(ModelType.configuration.name())) && empty (modelInfo.getModelName ()) && (action == Action.createInstance || action == Action.updateInstance || + action == Action.addRelationships || action == Action.removeRelationships || action == Action.recreateInstance || ((action == Action.deleteInstance || action == Action.scaleOut) && (requestScope.equalsIgnoreCase (ModelType.vfModule.name ()))))){ + throw new ValidationException ("modelName", true); + } - //is required for serviceInstance delete macro when aLaCarte=false (v3) - //create and updates except for network (except v4) - if (empty (modelInfo.getModelInvariantId ()) && ((reqVersion >2 && (aLaCarteFlag != null && !aLaCarteFlag) && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance) || - !(reqVersion < 4 && requestScope.equalsIgnoreCase (ModelType.network.name ())) && - (action == Action.createInstance || action == Action.updateInstance || action == Action.enablePort || action == Action.disablePort || action == Action.addRelationships || action == Action.removeRelationships || - (requestScope.equalsIgnoreCase(ModelType.configuration.name()) && (action == Action.activateInstance || action == Action.deactivateInstance))))) { - throw new ValidationException ("modelInvariantId"); - } - if(empty(modelInfo.getModelInvariantId()) && (requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut)){ - throw new ValidationException("modelInvariantId"); - } - if(empty(modelInfo.getModelInvariantId()) && (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.recreateInstance)){ - throw new ValidationException("modelInvariantId", true); - } - if (!empty (modelInfo.getModelInvariantId ()) && !UUIDChecker.isValidUUID (modelInfo.getModelInvariantId ())) { - throw new ValidationException ("modelInvariantId format"); - } + if (empty (modelInfo.getModelVersion ()) && !(requestScope.equalsIgnoreCase(ModelType.configuration.name())) && + (!(reqVersion < 4 && requestScope.equalsIgnoreCase (ModelType.network.name ())) + && (action == Action.createInstance || action == Action.updateInstance || action == Action.addRelationships || action == Action.removeRelationships || action == Action.scaleOut))) { + throw new ValidationException ("modelVersion"); + } - if(reqVersion >= 4 && !(requestScope.equalsIgnoreCase(ModelType.configuration.name())) && empty (modelInfo.getModelName ()) && (action == Action.createInstance || action == Action.updateInstance || - action == Action.addRelationships || action == Action.removeRelationships || action == Action.recreateInstance || ((action == Action.deleteInstance || action == Action.scaleOut) && (requestScope.equalsIgnoreCase (ModelType.vfModule.name ()))))){ - throw new ValidationException ("modelName", true); - } + if(empty(modelInfo.getModelVersion()) && (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.recreateInstance)){ + throw new ValidationException("modelVersion", true); + } - if (empty (modelInfo.getModelVersion ()) && !(requestScope.equalsIgnoreCase(ModelType.configuration.name())) && - (!(reqVersion < 4 && requestScope.equalsIgnoreCase (ModelType.network.name ())) - && (action == Action.createInstance || action == Action.updateInstance || action == Action.addRelationships || action == Action.removeRelationships || action == Action.scaleOut))) { - throw new ValidationException ("modelVersion"); - } - - if(empty(modelInfo.getModelVersion()) && (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.recreateInstance)){ - throw new ValidationException("modelVersion", true); - } + // is required for serviceInstance delete macro when aLaCarte=false in v4 + if (reqVersion >= 4 && empty (modelInfo.getModelVersionId()) && (((aLaCarteFlag != null && !aLaCarteFlag) && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance) || + (action == Action.createInstance || action == Action.updateInstance || action == Action.enablePort || action == Action.disablePort || action == Action.addRelationships || action == Action.removeRelationships || + (requestScope.equalsIgnoreCase(ModelType.configuration.name()) && (action == Action.activateInstance || action == Action.deactivateInstance))))) { + throw new ValidationException ("modelVersionId"); + } + if(empty(modelInfo.getModelVersionId()) && (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.recreateInstance)){ + throw new ValidationException("modelVersionId", true); + } + if(empty(modelInfo.getModelVersionId()) && (requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut)){ + throw new ValidationException("modelVersionId"); + } - // is required for serviceInstance delete macro when aLaCarte=false in v4 - if (reqVersion >= 4 && empty (modelInfo.getModelVersionId()) && (((aLaCarteFlag != null && !aLaCarteFlag) && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance) || - (action == Action.createInstance || action == Action.updateInstance || action == Action.enablePort || action == Action.disablePort || action == Action.addRelationships || action == Action.removeRelationships || - (requestScope.equalsIgnoreCase(ModelType.configuration.name()) && (action == Action.activateInstance || action == Action.deactivateInstance))))) { - throw new ValidationException ("modelVersionId"); - } - if(empty(modelInfo.getModelVersionId()) && (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.recreateInstance)){ - throw new ValidationException("modelVersionId", true); - } - if(empty(modelInfo.getModelVersionId()) && (requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut)){ - throw new ValidationException("modelVersionId"); - } - - if(requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action != Action.deleteInstance && empty (modelInfo.getModelCustomizationName ())) { - if (!UUIDChecker.isValidUUID (modelInfo.getModelCustomizationId())) { - throw new ValidationException ("modelCustomizationId or modelCustomizationName"); - } - } + if(requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action != Action.deleteInstance && empty (modelInfo.getModelCustomizationName ())) { + if (!UUIDChecker.isValidUUID (modelInfo.getModelCustomizationId())) { + throw new ValidationException ("modelCustomizationId or modelCustomizationName"); + } + } - if(reqVersion >= 4 && (!UUIDChecker.isValidUUID (modelInfo.getModelCustomizationId())) && (requestScope.equalsIgnoreCase (ModelType.network.name ()) || requestScope.equalsIgnoreCase(ModelType.configuration.name())) - && (action == Action.updateInstance || action == Action.createInstance)){ - throw new ValidationException ("modelCustomizationId"); - } - if(empty(modelInfo.getModelCustomizationId()) && action == Action.scaleOut && !(requestParameters.getTestApi() == TestApi.VNF_API.name() && requestParameters.isUsePreload() == true)){ - throw new ValidationException ("modelCustomizationId"); - } - return info; + if(reqVersion >= 4 && (!UUIDChecker.isValidUUID (modelInfo.getModelCustomizationId())) && (requestScope.equalsIgnoreCase (ModelType.network.name ()) || requestScope.equalsIgnoreCase(ModelType.configuration.name())) + && (action == Action.updateInstance || action == Action.createInstance)){ + throw new ValidationException ("modelCustomizationId"); + } + if(empty(modelInfo.getModelCustomizationId()) && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut && !(requestParameters.getTestApi() == TestApi.VNF_API.name() && requestParameters.isUsePreload() == true)){ + throw new ValidationException ("modelCustomizationId"); + } + }else{ + if(empty(modelInfo.getModelVersionId()) && action == Action.createInstance){ + throw new ValidationException("modelVersionId", true); + } + } + return info; } -}
\ No newline at end of file +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java index 9af26af91c..a6fdcc958d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java @@ -100,9 +100,14 @@ public class RelatedInstancesValidation implements ValidationRule{ if (!empty(relatedInstance.getInstanceId ()) && !UUIDChecker.isValidUUID (relatedInstance.getInstanceId ())) { throw new ValidationException ("instanceId format in relatedInstance"); } - - - if (action != Action.deleteInstance) { + if(empty(relatedInstanceModelInfo.getModelVersionId()) && requestScope.equals(ModelType.instanceGroup.toString()) && relatedInstanceModelInfo.getModelType().equals(ModelType.service)){ + throw new ValidationException("modelVersionId in relatedInstance", true); + } + if(requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString()) && relatedInstanceModelInfo.getModelType().equals(ModelType.service)){ + isRelatedServiceInstancePresent = true; + } + + if (action != Action.deleteInstance && !requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())) { if(!( relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup) || relatedInstanceModelInfo.getModelType().equals(ModelType.connectionPoint) || relatedInstanceModelInfo.getModelType().equals(ModelType.pnf) || @@ -144,7 +149,7 @@ public class RelatedInstancesValidation implements ValidationRule{ } } - if(relatedInstanceModelInfo.getModelType().equals(ModelType.service)) { + if(relatedInstanceModelInfo.getModelType().equals(ModelType.service) && !(requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString()) && action == Action.createInstance)) { isRelatedServiceInstancePresent = true; if (!relatedInstance.getInstanceId ().equals (sir.getServiceInstanceId ())) { throw new ValidationException ("serviceInstanceId matching the serviceInstanceId in request URI"); @@ -177,7 +182,11 @@ public class RelatedInstancesValidation implements ValidationRule{ throw new ValidationException ("connectionPoint relatedInstance for Port Configuration"); } } - + if(requestScope.equals(ModelType.instanceGroup.toString())){ + if(!isRelatedServiceInstancePresent){ + throw new ValidationException("related service instance for instanceGroup request", true); + } + } if(requestScope.equalsIgnoreCase (ModelType.volumeGroup.name ())) { if (!isRelatedServiceInstancePresent) { throw new ValidationException ("related service instance for volumeGroup request"); @@ -223,6 +232,9 @@ public class RelatedInstancesValidation implements ValidationRule{ msoLogger.debug ("related instance exception"); throw new ValidationException ("related instances"); } + if(instanceList == null && requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString()) && action == Action.createInstance){ + throw new ValidationException("relatedInstanceList", true); + } info.setVfModuleModelName(vfModuleModelName); info.setServiceInstanceType(serviceInstanceType); info.setVnfType(vnfType); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/UserParamsValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/UserParamsValidation.java index da1f1f6e90..894e488e92 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/UserParamsValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/UserParamsValidation.java @@ -27,56 +27,60 @@ import java.util.List; import org.onap.so.apihandlerinfra.Action; import org.onap.so.apihandlerinfra.Actions; import org.onap.so.exceptions.ValidationException; +import org.onap.so.serviceinstancebeans.ModelInfo; import org.onap.so.serviceinstancebeans.Networks; import org.onap.so.serviceinstancebeans.Service; import org.onap.so.serviceinstancebeans.VfModules; import org.onap.so.serviceinstancebeans.Vnfs; public class UserParamsValidation implements ValidationRule{ - private static boolean empty(String s) { - return (s == null || s.trim().isEmpty()); - } @Override public ValidationInformation validate(ValidationInformation info) throws ValidationException{ Service validate = info.getUserParams(); Actions action = info.getAction(); if(validate.getModelInfo() == null){ - throw new ValidationException ("model-info in userParams"); + throw new ValidationException ("modelInfo in userParams", true); + }else if(validate.getModelInfo().getModelType() == null){ + throw new ValidationException("modelType in userParams service modelInfo", true); }else if(validate.getModelInfo().getModelVersionId() == null){ - throw new ValidationException("modelVersionId in userParams"); + throw new ValidationException("modelVersionId in userParams service modelInfo", true); + } + modelInfoValidation(info.getSir().getRequestDetails().getModelInfo(), validate.getModelInfo()); + if(validate.getInstanceName() != null && info.getRequestInfo().getInstanceName() != null){ + instanceNameValidation(info, validate); } for(Vnfs vnf : validate.getResources().getVnfs()){ if(vnf.getModelInfo() == null){ - throw new ValidationException ("model-info in userParams vnf resources"); + throw new ValidationException ("modelInfo in userParams vnf resources", true); }else if(vnf.getModelInfo().getModelCustomizationId() == null){ - throw new ValidationException ("modelCustomizationId in userParams vnf resources"); + throw new ValidationException ("modelCustomizationId in userParams vnf resources", true); }else if(vnf.getModelInfo().getModelVersionId() == null){ - throw new ValidationException("modelVersionId in userParams vnf resources"); + throw new ValidationException("modelVersionId in userParams vnf resources", true); } if(vnf.getCloudConfiguration() == null){ - throw new ValidationException ("cloudConfiguration in userParams vnf resources"); + throw new ValidationException ("cloudConfiguration in userParams vnf resources", true); } if(action == Action.createInstance || action == Action.assignInstance){ if(vnf.getPlatform() == null){ - throw new ValidationException ("platform in userParams vnf resources"); + throw new ValidationException ("platform in userParams vnf resources", true); }if(vnf.getProductFamilyId() == null){ - throw new ValidationException ("productFamilyId in userParams vnf resources"); + throw new ValidationException ("productFamilyId in userParams vnf resources", true); } } if (vnf.getPlatform() != null && vnf.getPlatform().getPlatformName() == null){ - throw new ValidationException ("platformName in userParams vnf resources"); + throw new ValidationException ("platformName in userParams vnf resources", true); } if(vnf.getVfModules().isEmpty()){ - throw new ValidationException ("vfModules in userParams vnf resources"); + throw new ValidationException ("vfModules in userParams vnf resources", true); } for(VfModules vfModules : vnf.getVfModules()){ if(vfModules.getModelInfo() == null){ - throw new ValidationException ("model-info in userParams vfModules resources"); + throw new ValidationException ("modelInfo in userParams vfModules resources", true); }else if(vfModules.getModelInfo().getModelCustomizationId() == null){ - throw new ValidationException ("modelCustomizationId in userParams vfModule resources"); + throw new ValidationException ("modelCustomizationId in userParams vfModule resources", true); }else if(vfModules.getModelInfo().getModelVersionId() == null){ - throw new ValidationException("modelVersionId in userParams vfModule resources"); + throw new ValidationException("modelVersionId in userParams vfModule resources", true); } } } @@ -86,17 +90,46 @@ public class UserParamsValidation implements ValidationRule{ if(validateNetworks != null){ for(Networks networks : validateNetworks){ if(networks.getModelInfo() == null){ - throw new ValidationException ("model-info in userParams network resources"); + throw new ValidationException ("modelInfo in userParams network resources", true); }else if(networks.getModelInfo().getModelCustomizationId() == null){ - throw new ValidationException ("modelCustomizationId in userParams network resources"); + throw new ValidationException ("modelCustomizationId in userParams network resources", true); }else if(networks.getModelInfo().getModelVersionId() == null){ - throw new ValidationException("modelVersionId in userParams network resources"); + throw new ValidationException("modelVersionId in userParams network resources", true); } if(networks.getCloudConfiguration() == null){ - throw new ValidationException ("cloudConfiguration in userParams network resources"); + throw new ValidationException ("cloudConfiguration in userParams network resources", true); } } } return info; } + public void instanceNameValidation(ValidationInformation info, Service validate) throws ValidationException{ + if(!info.getRequestInfo().getInstanceName().equals(validate.getInstanceName())){ + throw new ValidationException("instanceName in requestInfo", "instanceName in userParams service"); + } + } + public void modelInfoValidation(ModelInfo info, ModelInfo userParamInfo) throws ValidationException{ + if(!info.getModelType().equals(userParamInfo.getModelType())){ + throw new ValidationException("modelType in modelInfo", "modelType in userParams service"); + } + if((info.getModelInvariantId() != null && userParamInfo.getModelInvariantId() != null) && + (!info.getModelInvariantId().equals(userParamInfo.getModelInvariantId()))){ + throw new ValidationException("modelInvariantId in modelInfo", "modelInvariantId in userParams service"); + } + if(!info.getModelVersionId().equals(userParamInfo.getModelVersionId())){ + throw new ValidationException("modelVersionId in modelInfo", "modelVersionId in userParams service"); + } + if((info.getModelName() != null && userParamInfo.getModelName() != null) && + (!info.getModelName().equals(userParamInfo.getModelName()))){ + throw new ValidationException("modelName in modelInfo", "modelName in userParams service"); + } + if((info.getModelVersion() != null && userParamInfo.getModelVersion() != null) && + (!info.getModelVersion().equals(userParamInfo.getModelVersion()))){ + throw new ValidationException("modelVersion in modelInfo", "modelVersion in userParams service"); + } + if((info.getModelCustomizationId() != null && userParamInfo.getModelCustomizationId() != null) && + (!info.getModelCustomizationId().equals(userParamInfo.getModelCustomizationId()))){ + throw new ValidationException("modelCustomizationId in modelInfo", "modelCustomizationId in userParams service"); + } + } }
\ No newline at end of file |